Skip to content

DataStore Class

Interface to qi2lab MERFISH datastore.

This module provides methods and attributes to create or interact with the qi2lab MERFISH datastore. The filestore structure is further described in the merfish3d-analysis documentation.

History:
  • 2024/12: Refactored repo structure.
  • 2024/12: Updated docstrings and exception types.
  • 2024/07: Initial commit.

Classes:

Name Description
qi2labDataStore

API to qi2lab MERFISH store.

qi2labDataStore

API to qi2lab MERFISH store.

Parameters:

Name Type Description Default
datastore_path str or Path

Path to qi2lab MERFISH store

required
validate bool

Validate datastore contents on open. Set False to skip expensive zarr readability checks and load only metadata/path structure.

True

Methods:

Name Description
__init__

Initialize a qi2lab datastore handle.

baysor_3d_available

Return whether Baysor 3D molecules and cell boundaries are present.

decoded_temporary_dir

Return the temporary decoded-output directory for a decode run.

fused_image_path

Return the OME-Zarr path for a fused image.

image_shape

Read image shape without loading all pixels.

initialize_tile

Initialize directory structure for a tile.

list_proseg_3d_runs

List available Proseg 3D output runs.

load_baysor_cell_boundaries_3d

Load Baysor 3D cell boundary polygons.

load_baysor_molecules_3d

Load Baysor 3D molecule assignments.

load_chromatic_affine_transform_zyx_um

Load one chromatic affine transform with identity fallback.

load_chromatic_affine_transforms_zyx_um

Load chromatic affine calibration metadata.

load_codebook_parsed

Load and split codebook into gene_ids and codebook matrix.

load_coord_of_xform_px

Local fiducial optical flow matrix for one round and tile.

load_decode_normalization_metadata

Load provenance for default or run-scoped normalization vectors.

load_decode_normalization_vectors

Load run-scoped normalization and background vectors.

load_global_cellpose_outlines

Load Cellpose max projection cell outlines.

load_global_cellpose_roi_zip

Load global Cellpose outlines from an ImageJ ROI zip.

load_global_cellpose_segmentation_image

Load Cellpose max projection, downsampled segmentation image.

load_global_coord_xforms_um

Load global registration transform for one tile.

load_global_fiducial_image

Load downsampled, fused fiducial image.

load_global_filtered_decoded_spots

Load all decoded and filtered spots.

load_image_metadata

Load extra attributes through yaozarrs.

load_local_bit_linker

Load readout bits linked to fiducial round for one tile.

load_local_corrected_image

Load gain and offset corrected image for fiducial OR readout bit for one tile.

load_local_decoded_spots

Load decoded spots and features for one tile.

load_local_deconvolved_fiducial_image

Load a native-frame deconvolved fiducial image.

load_local_deconvolved_readout_image

Load a native-frame deconvolved readout bit image.

load_local_feature_predictor_image

Load readout bit feature_predictor prediction image for one tile.

load_local_feature_predictor_spots

Load feature_predictor spot localizations and features for one tile.

load_local_fiducial_image

Load the best available native-frame fiducial image.

load_local_image_metadata

Load image and sidecar metadata for one fiducial round or readout bit.

load_local_readout_image

Load the best available native-frame readout bit image.

load_local_rigid_xform_xyz_px

Load calculated rigid registration transform for one round and tile.

load_local_round_linker

Load fiducial round linked to readout bit for one tile.

load_local_round_transform_zyx_um

Load the local fiducial round transform for one tile.

load_local_sofima_flow_field

Load the SOFIMA flow field for one local fiducial round.

load_local_stage_position_zyx_um

Load tile stage position for one tile.

load_local_wavelengths_um

Load wavelengths for fiducial OR readout bit for one tile.

load_proseg_cell_polygons_3d

Load Proseg 3D refined cell polygons.

load_proseg_transcripts_3d

Load Proseg 3D transcript metadata.

local_feature_predictor_spots_path

Return the localization table path for a tile and readout identifier.

local_image_path

Return a native fiducial or readout OME-Zarr image path.

save_chromatic_affine_transforms_zyx_um

Save chromatic affine calibration metadata.

save_coord_of_xform_px

Save fiducial optical flow matrix for one round and tile.

save_decode_normalization_vectors

Save default or run-scoped normalization and background vectors.

save_global_cellpose_segmentation_image

Save Cellpose max projection, downsampled segmentation image.

save_global_coord_xforms_um

Save global registration transform for one tile.

save_global_fiducial_image

Save downsampled, fused fiducial image.

save_global_filtered_decoded_spots

Save all decoded and filtered spots.

save_image_metadata

Write image-level extra attributes for externally-created OME-Zarr stores.

save_local_bit_linker

Save readout bits linked to fiducial round for one tile.

save_local_corrected_image

Save gain and offset corrected image.

save_local_decoded_spots

Save decoded spots and features for one tile.

save_local_deconvolved_fiducial_image

Save a native-frame deconvolved fiducial image.

save_local_deconvolved_readout_image

Save a native-frame deconvolved readout bit image.

save_local_feature_predictor_image

Save feature_predictor prediction image.

save_local_feature_predictor_spots

Save feature_predictor localizations and features.

save_local_rigid_xform_xyz_px

Save calculated rigid registration transform for one round and tile.

save_local_round_linker

Save fiducial round linker attribute to readout bit for one tile.

save_local_round_transform_zyx_um

Save the local fiducial round transform for one tile.

save_local_sofima_flow_field

Save the SOFIMA flow field for one local fiducial round.

save_local_stage_position_zyx_um

Save tile stage position for one tile.

save_local_wavelengths_um

Save wavelengths for fiducial OR readout bit for one tile.

Attributes:

Name Type Description
binning int | None

Camera binning.

bit_ids Collection[str] | None

Bit IDs.

camera_model str | None

Camera model.

channel_psfs ArrayLike | None

Channel point spread functions (PSF).

channel_shading_maps ArrayLike | None

Channel shaiding images.

channels_in_data Collection[int] | None

Channel indices.

codebook DataFrame | None

Codebook.

datastore_path Path

Experiment datastore directory.

datastore_state dict | None

Datastore state.

e_per_ADU float | None

Electrons per camera ADU.

experiment_order DataFrame | None

Round and bit order.

global_background_vector ArrayLike | None

Global background vector.

global_normalization_vector ArrayLike | None

Global normalization vector.

iterative_background_vector ArrayLike | None

Iterative background vector.

iterative_normalization_vector ArrayLike | None

Iterative normalization vector.

microscope_type str | None

Microscope type.

na float | None

Detection objective numerical aperture (NA).

noise_map ArrayLike | None

Camera noise image.

num_bits int

Number of bits.

num_rounds int | None

Number of rounds.

num_tiles int | None

Number of tiles.

ri float | None

Detection objective refractive index (RI).

round_ids Collection[str] | None

Round IDs.

tile_ids Collection[str] | None

Tile IDs.

tile_overlap float | None

XY tile overlap.

voxel_size_zyx_um ArrayLike | None

Voxel size, zyx order (microns).

Source code in src/merfish3danalysis/qi2labDataStore.py
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
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
1031
1032
1033
1034
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
1195
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
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
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
1463
1464
1465
1466
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
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
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
1861
1862
1863
1864
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
2005
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
2159
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
2226
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
2441
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
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
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
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
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
2823
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
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
class qi2labDataStore:
    """API to qi2lab MERFISH store.

    Parameters
    ----------
    datastore_path : str or Path
        Path to qi2lab MERFISH store
    validate : bool, default True
        Validate datastore contents on open. Set False to skip expensive
        zarr readability checks and load only metadata/path structure.

    """

    def __init__(self, datastore_path: str | Path, validate: bool = True) -> None:
        """
        Initialize a qi2lab datastore handle.

        Parameters
        ----------
        datastore_path : str | Path
            Datastore root path.
        validate : bool
            Whether to validate existing image arrays while parsing the store.
        """
        self._datastore_path = Path(datastore_path)
        if self._datastore_path.exists():
            self._parse_datastore(validate=validate)
        else:
            self._init_datastore()

    @property
    def datastore_path(self) -> Path:
        """Experiment datastore directory."""
        return self._datastore_path

    def fused_image_path(self, image_name: str | None = None) -> Path:
        """Return the OME-Zarr path for a fused image.

        Parameters
        ----------
        image_name : str or None
            Logical image name. None selects the fused fiducial volume.

        Returns
        -------
        Path
            Fused image directory, without opening or creating it.
        """
        if image_name is None:
            image_name = f"fused_{self.fiducial_folder_name}_zyx"
        return self._image_store_path(self._fused_root_path / image_name)

    def local_image_path(
        self,
        tile: int | str,
        image_name: str,
        *,
        round: int | str | None = None,
        bit: int | str | None = None,
    ) -> Path:
        """Return a native fiducial or readout OME-Zarr image path.

        Parameters
        ----------
        tile : int or str
            Zero-based tile index or stored tile identifier.
        image_name : str
            Logical image name such as corrected_data or decon_data.
        round : int or str or None
            Zero-based fiducial round index or identifier; excludes bit.
        bit : int or str or None
            Zero-based readout bit index or identifier; excludes round.

        Returns
        -------
        Path
            Image path without loading pixels or creating directories.
        """
        if (round is None) == (bit is None):
            raise ValueError("Provide exactly one of round or bit.")
        if isinstance(tile, int) and not 0 <= tile < len(self._tile_ids):
            raise ValueError(f"Invalid tile: {tile}")
        tile_id = self._tile_ids[tile] if isinstance(tile, int) else tile
        if tile_id not in self._tile_ids:
            raise ValueError(f"Invalid tile: {tile}")
        ids = self._round_ids if round is not None else self._bit_ids
        selection = round if round is not None else bit
        if isinstance(selection, int) and not 0 <= selection < len(ids):
            raise ValueError(f"Invalid round or bit: {selection}")
        entity_id = ids[selection] if isinstance(selection, int) else selection
        if entity_id not in ids:
            raise ValueError(f"Invalid round or bit: {selection}")
        root = (
            self._fiducial_root_path if round is not None else self._readouts_root_path
        )
        return self._image_store_path(root / tile_id / entity_id / image_name)

    def local_feature_predictor_spots_path(self, tile: str, bit: str) -> Path:
        """Return the localization table path for a tile and readout identifier."""
        if tile not in self._tile_ids or bit not in self._bit_ids:
            raise ValueError(f"Invalid tile or bit: {tile}, {bit}")
        return (
            self._feature_predictor_localizations_root_path / tile / (bit + ".parquet")
        )

    def load_local_image_metadata(
        self,
        tile: int | str,
        *,
        round: int | str | None = None,
        bit: int | str | None = None,
        image_names: Sequence[str] | None = None,
    ) -> dict[str, Any]:
        """Load image and sidecar metadata for one fiducial round or readout bit.

        Parameters
        ----------
        tile : int or str
            Tile index or identifier.
        round : int or str or None
            Fiducial round index or identifier; excludes bit.
        bit : int or str or None
            Readout bit index or identifier; excludes round.

        image_names : Sequence[str] or None
            Image names to inspect, in metadata precedence order.

        Returns
        -------
        dict[str, Any]
            Merged image metadata, with sidecar values taking precedence.
        """
        path = self.local_image_path(tile, "corrected_data", round=round, bit=bit)
        return self._load_entity_attributes(path.parent, image_names=image_names)

    @property
    def datastore_state(self) -> dict | None:
        """Datastore state.

        Returns
        -------
        datastore_state : dict or None
            Datastore state.
        """
        return getattr(self, "_datastore_state", None)

    @datastore_state.setter
    def datastore_state(self, value: dict) -> None:
        """Set the datastore state.

        Parameters
        ----------
        value : dict
            New datastore state.
        """
        state = dict(self.datastore_state or {})
        state.update(value)
        self._save_to_json(state, self._datastore_state_json_path)
        self._datastore_state = state

    def _calibrations_attributes_path(self) -> Path:
        """
        Path to calibrations metadata sidecar.

        Returns
        -------
        Path
            Path to ``calibrations/attributes.json``.
        """
        return self._calibrations_zarr_path / Path("attributes.json")

    def _load_calibrations_attributes(self) -> dict[str, Any]:
        """
        Load calibrations metadata sidecar.

        Returns
        -------
        dict[str, Any]
            Calibration metadata loaded from disk.
        """
        attributes_path = self._calibrations_attributes_path()
        if not attributes_path.is_file():
            raise FileNotFoundError(
                f"Calibration attributes not found: {attributes_path}"
            )
        return self._load_from_json(attributes_path)

    def _save_calibrations_attributes(self, attributes: Mapping[str, Any]) -> None:
        """
        Persist calibrations metadata sidecar.

        Parameters
        ----------
        attributes : Mapping[str, Any]
            Calibration metadata to write.

        Returns
        -------
        None
            No return value.
        """
        self._save_to_json(
            {str(k): self._to_json_compatible(v) for k, v in dict(attributes).items()},
            self._calibrations_attributes_path(),
        )

    def _set_calibration_attribute(self, key: str, value: Any) -> None:
        """
        Update one calibration metadata field.

        Parameters
        ----------
        key : str
            Calibration metadata key.
        value : Any
            Value to store after JSON conversion.

        Returns
        -------
        None
            No return value.
        """
        attributes = self._load_calibrations_attributes()
        attributes[str(key)] = self._to_json_compatible(value)
        self._save_calibrations_attributes(attributes)

    def save_chromatic_affine_transforms_zyx_um(
        self,
        calibration: Mapping[str, Any],
    ) -> None:
        """
        Save chromatic affine calibration metadata.

        Parameters
        ----------
        calibration : Mapping[str, Any]
            Calibration metadata containing one 4x4 ``affine_zyx_um`` matrix
            per channel. Each affine maps that channel's physical Z, Y, X
            coordinates onto the lowest-wavelength reference channel.

        Returns
        -------
        None
            Metadata are written to ``calibrations/attributes.json``.
        """
        calibration = dict(calibration)
        if "voxel_size_zyx_um" in calibration:
            calibration["voxel_size_zyx_um"] = round_spacing_um(
                calibration["voxel_size_zyx_um"]
            ).tolist()
        self._set_calibration_attribute(
            "chromatic_affine_transforms_zyx_um",
            calibration,
        )

    def load_chromatic_affine_transforms_zyx_um(self) -> dict[str, Any]:
        """
        Load chromatic affine calibration metadata.

        Returns
        -------
        dict[str, Any]
            Stored calibration metadata. Returns an empty dictionary when no
            chromatic calibration is present.
        """
        try:
            attributes = self._load_calibrations_attributes()
        except (FileNotFoundError, json.JSONDecodeError, ValueError):
            return {}
        calibration = attributes.get("chromatic_affine_transforms_zyx_um", {})
        if isinstance(calibration, dict):
            if "voxel_size_zyx_um" in calibration:
                calibration["voxel_size_zyx_um"] = round_spacing_um(
                    calibration["voxel_size_zyx_um"]
                ).tolist()
            return calibration
        return {}

    def load_chromatic_affine_transform_zyx_um(
        self,
        channel_name: str | None = None,
        channel_index: int | None = None,
        wavelength_um: float | None = None,
    ) -> np.ndarray:
        """
        Load one chromatic affine transform with identity fallback.

        Parameters
        ----------
        channel_name : str or None, default=None
            Channel name from the calibration metadata.
        channel_index : int or None, default=None
            Channel index from the calibration metadata.
        wavelength_um : float or None, default=None
            Channel wavelength in microns. Used only when channel name/index do
            not find a match.

        Returns
        -------
        numpy.ndarray
            4x4 affine matrix in physical Z, Y, X microns. Identity is returned
            if the calibration or requested channel is absent.
        """
        calibration = self.load_chromatic_affine_transforms_zyx_um()
        channels = calibration.get("channels", {})
        if not isinstance(channels, Mapping):
            return np.eye(4, dtype=np.float32)

        candidates = []
        if channel_name is not None:
            channel = channels.get(str(channel_name))
            if isinstance(channel, Mapping):
                candidates.append(channel)
        if channel_index is not None:
            for channel in channels.values():
                if isinstance(channel, Mapping) and int(
                    channel.get("channel_index", -1)
                ) == int(channel_index):
                    candidates.append(channel)
        if wavelength_um is not None:
            wavelength = float(wavelength_um)
            for channel in channels.values():
                if not isinstance(channel, Mapping):
                    continue
                stored = channel.get("wavelength_um")
                if stored is not None and np.isclose(float(stored), wavelength):
                    candidates.append(channel)

        for channel in candidates:
            affine = channel.get("affine_zyx_um")
            if affine is not None:
                return np.asarray(affine, dtype=np.float32)
        return np.eye(4, dtype=np.float32)

    @staticmethod
    def _strict_id_sort_key(name: str, prefix: str, width: int) -> int:
        """
        Validate and parse strict zero-padded identifiers.

        Parameters
        ----------
        name : str
            Identifier to validate.
        prefix : str
            Required identifier prefix.
        width : int
            Required number of zero-padded digits.

        Returns
        -------
        int
            Parsed numeric identifier.
        """
        match = re.fullmatch(rf"{re.escape(prefix)}(\d{{{width}}})", name)
        if match is None:
            raise ValueError(
                f"Invalid identifier '{name}'. Expected '{prefix}' followed by {width} digits."
            )
        return int(match.group(1))

    @classmethod
    def _collect_strict_ids(cls, parent: Path, prefix: str, width: int) -> list[str]:
        """
        Collect and sort strict identifiers under a folder.

        Parameters
        ----------
        parent : Path
            Folder containing identifier-named child directories.
        prefix : str
            Required identifier prefix.
        width : int
            Required number of zero-padded digits.

        Returns
        -------
        list[str]
            Strict identifiers sorted by numeric value.
        """

        def sort_id(value: str) -> tuple[int, int, str]:
            """
            Return the strict identifier sort key.

            Parameters
            ----------
            value : str
                Identifier string.

            Returns
            -------
            tuple[int, int, str]
                Numeric and lexical sort key.
            """
            return cls._strict_id_sort_key(value, prefix, width)

        ids = [entry.name for entry in parent.iterdir() if entry.is_dir()]
        ids.sort(key=sort_id)
        return ids

    @property
    def microscope_type(self) -> str | None:
        """Microscope type.

        Returns
        -------
        microscope_type : str or None
            Microscope type.
        """
        return getattr(self, "_microscope_type", None)

    @microscope_type.setter
    def microscope_type(self, value: str) -> None:
        """Set the microscope type.

        Parameters
        ----------
        value : str
            New microscope type.
        """
        self._microscope_type = value
        self._set_calibration_attribute("microscope_type", value)

    @property
    def camera_model(self) -> str | None:
        """Camera model.

        Returns
        -------
        camera_model : str or None
            Camera model.
        """
        return getattr(self, "_camera_model", None)

    @camera_model.setter
    def camera_model(self, value: str) -> None:
        """Set the camera model.

        Parameters
        ----------
        value : str
            New camera model.
        """
        self._camera_model = value
        self._set_calibration_attribute("camera_model", value)

    @property
    def num_rounds(self) -> int | None:
        """Number of rounds.

        Returns
        -------
        num_rounds : int
            Number of rounds.
        """
        return getattr(self, "_num_rounds", None)

    @num_rounds.setter
    def num_rounds(self, value: int) -> None:
        """Set the number of rounds.

        Parameters
        ----------
        value : int
            New number of rounds.
        """
        self._num_rounds = value
        self._set_calibration_attribute("num_rounds", value)

    @property
    def num_bits(self) -> int:
        """Number of bits.

        Returns
        -------
        num_bits : int
            Number of bits.
        """
        return getattr(self, "_num_bits", None)

    @num_bits.setter
    def num_bits(self, value: int) -> None:
        """Set the number of bits.

        Parameters
        ----------
        value : int
            Number of bits.
        """
        self._num_bits = value
        self._set_calibration_attribute("num_bits", value)

    @property
    def num_tiles(self) -> int | None:
        """Number of tiles.

        Returns
        -------
        num_tiles : int
            Number of tiles.
        """
        return getattr(self, "_num_tiles", None)

    @num_tiles.setter
    def num_tiles(self, value: int) -> None:
        """Set the number of tiles.

        Parameters
        ----------
        value : int
            New number of tiles.
        """
        self._num_tiles = value
        self._set_calibration_attribute("num_tiles", value)

        self._tile_ids = []
        for tile_idx in range(value):
            self._tile_ids.append("tile" + str(tile_idx).zfill(4))

    @property
    def channels_in_data(self) -> Collection[int] | None:
        """Channel indices.

        Returns
        -------
        channels_in_data : Collection[int]
            Channel indices.
        """
        return getattr(self, "_channels_in_data", None)

    @channels_in_data.setter
    def channels_in_data(self, value: Collection[int]) -> None:
        """Set the channels in the data.

        Parameters
        ----------
        value : Collection[int]
            New channels in data (int values starting from zero).
        """
        self._channels_in_data = value
        self._set_calibration_attribute("channels_in_data", value)

    @property
    def tile_overlap(self) -> float | None:
        """XY tile overlap.

        Returns
        -------
        tile_overlap : float
            XY tile overlap.
        """
        return getattr(self, "_tile_overlap", None)

    @tile_overlap.setter
    def tile_overlap(self, value: float) -> None:
        """Set the tile overlap.

        Parameters
        ----------
        value : float
            New tile overlap.
        """
        self._tile_overlap = value
        self._set_calibration_attribute("tile_overlap", value)

    @property
    def binning(self) -> int | None:
        """Camera binning.

        Returns
        -------
        binning : int
            Camera binning.
        """
        return getattr(self, "_binning", None)

    @binning.setter
    def binning(self, value: int) -> None:
        """Set the camera binning.

        Parameters
        ----------
        value : int
            New camera binning.
        """
        self._binning = value
        self._set_calibration_attribute("binning", value)

    @property
    def e_per_ADU(self) -> float | None:
        """Electrons per camera ADU.

        Returns
        -------
        e_per_ADU : float
            Electrons per camera ADU.
        """
        return getattr(self, "_e_per_ADU", None)

    @e_per_ADU.setter
    def e_per_ADU(self, value: float) -> None:
        """Set the camera conversion (e- per ADU).

        Parameters
        ----------
        value : float
            New camera conversion (e- per ADU).
        """
        self._e_per_ADU = value
        self._set_calibration_attribute("e_per_ADU", value)

    @property
    def na(self) -> float | None:
        """Detection objective numerical aperture (NA).

        Returns
        -------
        na : float
            Detection objective numerical aperture (NA).
        """
        return getattr(self, "_na", None)

    @na.setter
    def na(self, value: float) -> None:
        """Set detection objective numerical aperture (NA).

        Parameters
        ----------
        value: float
            New detection objective numerical aperture (NA)
        """
        self._na = value
        self._set_calibration_attribute("na", value)

    @property
    def ri(self) -> float | None:
        """Detection objective refractive index (RI).

        Returns
        -------
        ri : float
            Detection objective refractive index (RI).
        """
        return getattr(self, "_ri", None)

    @ri.setter
    def ri(self, value: float) -> None:
        """Set detection objective refractive index (RI).

        Parameters
        ----------
        value: float
            New detection objective refractive index (RI)
        """
        self._ri = value
        self._set_calibration_attribute("ri", value)

    @property
    def noise_map(self) -> ArrayLike | None:
        """Camera noise image.

        Returns
        -------
        noise_map : ArrayLike
            Camera noise image.
        """
        return getattr(self, "_noise_map", None)

    @noise_map.setter
    def noise_map(self, value: ArrayLike) -> None:
        """Set the camera noise image.

        Parameters
        ----------
        value : ArrayLike
            New camera noise image.
        """
        current_local_zarr_path = str(self._calibrations_zarr_path / Path("noise_map"))

        self._save_to_zarr_array(value, current_local_zarr_path, return_future=False)
        self._noise_map = value

    @property
    def channel_shading_maps(self) -> ArrayLike | None:
        """Channel shaiding images.

        Returns
        -------
        channel_shading_maps : ArrayLike
            Channel shading images.
        """
        return getattr(self, "_shading_maps", None)

    @channel_shading_maps.setter
    def channel_shading_maps(self, value: ArrayLike) -> None:
        """Set the channel shading images.

        Parameters
        ----------
        value : ArrayLike
            New channel shading images.
        """
        shading_maps = np.asarray(value, dtype=np.float32)
        if shading_maps.ndim == 2:
            shading_maps = np.expand_dims(shading_maps, axis=0)
        if shading_maps.ndim != 3:
            raise ValueError(
                f"Shading maps must be 2D or 3D, got shape {shading_maps.shape}"
            )
        if shading_maps.shape[0] > 1:
            reference_shape = tuple(shading_maps[0].shape)
            for channel_map in shading_maps[1:]:
                if tuple(channel_map.shape) != reference_shape:
                    raise ValueError(
                        "All shading maps must share the same YX shape "
                        f"(expected {reference_shape}, got {tuple(channel_map.shape)})."
                    )

        current_local_zarr_path = str(
            self._calibrations_zarr_path / Path("shading_maps")
        )

        self._save_to_zarr_array(
            shading_maps, current_local_zarr_path, return_future=False
        )
        self._shading_maps = shading_maps

    @property
    def channel_psfs(self) -> ArrayLike | None:
        """Channel point spread functions (PSF).

        Returns
        -------
        channel_psfs : ArrayLike
            Channel point spread functions (PSF).
        """
        psfs = getattr(self, "_psfs", None)
        if psfs is None:
            return None
        if isinstance(psfs, list):
            if len(psfs) == 0:
                return []
            shapes = {tuple(np.asarray(psf).shape) for psf in psfs}
            if len(shapes) == 1:
                return np.stack(psfs, axis=0)
            return psfs
        return psfs

    @channel_psfs.setter
    def channel_psfs(self, value: ArrayLike) -> None:
        """Set the channel point spread functions (PSF).

        Parameters
        ----------
        value : ArrayLike
            New channel point spread functions (PSF).
        """
        if isinstance(value, np.ndarray):
            if value.dtype == object:
                psf_list = [np.asarray(psf, dtype=np.float32) for psf in list(value)]
            elif value.ndim >= 3:
                psf_list = [
                    np.asarray(value[idx], dtype=np.float32)
                    for idx in range(value.shape[0])
                ]
            else:
                psf_list = [np.asarray(value, dtype=np.float32)]
        else:
            psf_list = [np.asarray(psf, dtype=np.float32) for psf in list(value)]

        if len(psf_list) == 0:
            raise ValueError("channel_psfs cannot be empty.")

        psf_root_path = self._calibrations_zarr_path / Path("psf_data")
        psf_root_path.mkdir(exist_ok=True, parents=True)
        psf_manifest: dict[str, Any] = {}

        for psf_idx, psf_array in enumerate(psf_list):
            psf_id = f"psf_{psf_idx:03d}"
            current_psf_path = psf_root_path / Path(psf_id)
            self._save_to_zarr_array(psf_array, current_psf_path, return_future=False)
            psf_manifest[str(psf_idx)] = {
                "id": psf_id,
                "shape_zyx": list(psf_array.shape),
            }

        self._set_calibration_attribute("psf_manifest", psf_manifest)
        self._psfs = psf_list

    @property
    def experiment_order(self) -> pd.DataFrame | None:
        """Round and bit order.

        Returns
        -------
        experiment_order : pd.DataFrame
            Round and bit order.
        """
        experiment_order = getattr(self, "_experiment_order", None)
        if experiment_order is not None:
            return experiment_order

        legacy_experiment_order = getattr(self, "_exp_order", None)
        if legacy_experiment_order is None:
            return None

        self._experiment_order = self._coerce_experiment_order_dataframe(
            legacy_experiment_order
        )
        return self._experiment_order

    def _coerce_experiment_order_dataframe(
        self, value: ArrayLike | pd.DataFrame
    ) -> pd.DataFrame:
        """
        Normalize experiment order into the canonical DataFrame form.

        Parameters
        ----------
        value : ArrayLike | pd.DataFrame
            Experiment order table or array to normalize.

        Returns
        -------
        pd.DataFrame
            Experiment order as a DataFrame with channel columns.
        """
        if isinstance(value, pd.DataFrame):
            return value

        channel_list = [str(channel) for channel in self._channels_in_data]
        return pd.DataFrame(value, columns=channel_list, dtype="int64")

    @experiment_order.setter
    def experiment_order(self, value: ArrayLike | pd.DataFrame) -> None:
        """Set the round and bit order.

        Parameters
        ----------
        value : ArrayLike or pandas.DataFrame
            New round and bit order.
        """
        self._experiment_order = self._coerce_experiment_order_dataframe(value)

        self._set_calibration_attribute("exp_order", self._experiment_order.values)

        if self.num_rounds is None:
            self.num_rounds = int(value[-1, 0])
        else:
            assert self.num_rounds == int(value[-1, 0]), (
                "Number of rounds does not match experiment order file."
            )

        if self.num_bits is None:
            self.num_bits = int(np.max(value[:, 1:]))
        else:
            assert self.num_bits == int(np.max(value[:, 1:])), (
                "Number of bits does not match experiment order file."
            )

        self._round_ids = []
        for round_idx in range(self.num_rounds):
            self._round_ids.append("round" + str(round_idx + 1).zfill(3))

        self._bit_ids = []
        for bit_idx in range(self.num_bits):
            self._bit_ids.append("bit" + str(bit_idx + 1).zfill(3))

    @property
    def codebook(self) -> pd.DataFrame | None:
        """Codebook.

        Returns
        -------
        codebook : pd.DataFrame
            Codebook.
        """
        data = getattr(self, "_codebook", None)

        if data is None:
            return None
        num_columns = len(data[0]) if data else 0
        columns = ["gene_id"] + [f"bit{i:02d}" for i in range(1, num_columns)]

        return pd.DataFrame(data, columns=columns)

    @codebook.setter
    def codebook(self, value: pd.DataFrame) -> None:
        """Set the codebook.

        Parameters
        ----------
        value : pd.DataFrame
            New codebook.
        """
        self._codebook = value
        self._set_calibration_attribute("codebook", self._codebook.values)

    @property
    def voxel_size_zyx_um(self) -> ArrayLike | None:
        """Voxel size, zyx order (microns).

        Returns
        -------
        voxel_size_zyx_um : ArrayLike
            Voxel size, zyx order (microns).
        """
        value = getattr(self, "_voxel_size_zyx_um", None)
        return None if value is None else self._normalize_voxel_size_zyx_um(value)

    @voxel_size_zyx_um.setter
    def voxel_size_zyx_um(self, value: ArrayLike) -> None:
        """Set the voxel size, zyx order (microns).

        Parameters
        ----------
        value : ArrayLike
            New voxel size, zyx order (microns).
        """
        spacing = self._normalize_voxel_size_zyx_um(value)
        self._set_calibration_attribute("voxel_size_zyx_um", spacing)
        self._voxel_size_zyx_um = spacing

    @staticmethod
    def _normalize_voxel_size_zyx_um(value: ArrayLike) -> list[float]:
        """Validate three positive finite ZYX spacings at stored precision."""
        spacing = round_spacing_um(value)
        if (
            spacing.shape != (3,)
            or not np.all(np.isfinite(spacing))
            or np.any(spacing <= 0)
        ):
            raise ValueError(
                "voxel_size_zyx_um must contain three positive finite ZYX spacings."
            )
        return spacing.tolist()

    @property
    def global_normalization_vector(self) -> ArrayLike | None:
        """Global normalization vector.

        Returns
        -------
        global_normalization_vector : ArrayLike
            Global normalization vector.
        """
        value = getattr(self, "_global_normalization_vector", None)
        if value is None:
            calib_attrs = self._load_calibrations_attributes()

            try:
                value = np.asarray(
                    calib_attrs["global_normalization_vector"], dtype=np.float32
                )
                return value
            except KeyError:
                print("Global normalization vector not calculated.")
                return None
        else:
            return value

    @global_normalization_vector.setter
    def global_normalization_vector(self, value: ArrayLike) -> None:
        """Set the global normalization vector.

        Parameters
        ----------
        value : ArrayLike
            New global normalization vector.
        """
        self._global_normalization_vector = np.asarray(value, dtype=np.float32)
        self._set_calibration_attribute(
            "global_normalization_vector",
            self._global_normalization_vector,
        )

    @property
    def global_background_vector(self) -> ArrayLike | None:
        """Global background vector.

        Returns
        -------
        global_background_vector : ArrayLike
            Global background vector.
        """
        value = getattr(self, "_global_background_vector", None)
        if value is None:
            calib_attrs = self._load_calibrations_attributes()
            try:
                value = np.asarray(
                    calib_attrs["global_background_vector"], dtype=np.float32
                )
                return value
            except KeyError:
                print("Global background vector not calculated.")
                return None
        else:
            return value

    @global_background_vector.setter
    def global_background_vector(self, value: ArrayLike) -> None:
        """Set the global background vector.

        Parameters
        ----------
        value : ArrayLike
            New global background vector.
        """
        self._global_background_vector = np.asarray(value, dtype=np.float32)
        self._set_calibration_attribute(
            "global_background_vector",
            self._global_background_vector,
        )

    @property
    def iterative_normalization_vector(self) -> ArrayLike | None:
        """Iterative normalization vector.

        Returns
        -------
        iterative_normalization_vector : ArrayLike
            Iterative normalization vector.
        """
        value = getattr(self, "_iterative_normalization_vector", None)
        if value is None:
            calib_attrs = self._load_calibrations_attributes()
            try:
                value = np.asarray(
                    calib_attrs["iterative_normalization_vector"], dtype=np.float32
                )
            except KeyError:
                value = None

            if value is None:
                print("Iterative normalization vector not calculated.")
                return None

            return value
        else:
            return value

    @iterative_normalization_vector.setter
    def iterative_normalization_vector(self, value: ArrayLike) -> None:
        """Set the iterative normalization vector.

        Parameters
        ----------
        value : ArrayLike
            New iterative normalization vector.
        """
        self._iterative_normalization_vector = value
        self._set_calibration_attribute(
            "iterative_normalization_vector",
            self._iterative_normalization_vector,
        )

    @property
    def iterative_background_vector(self) -> ArrayLike | None:
        """Iterative background vector.

        Returns
        -------
        iterative_background_vector : ArrayLike
            Iterative background vector.
        """
        value = getattr(self, "_iterative_background_vector", None)
        if value is None:
            calib_attrs = self._load_calibrations_attributes()
            try:
                value = np.asarray(
                    calib_attrs["iterative_background_vector"], dtype=np.float32
                )
            except KeyError:
                value = None
            if value is None:
                print("Iterative background vector not calculated.")
                return None

            return value
        else:
            return value

    @iterative_background_vector.setter
    def iterative_background_vector(self, value: ArrayLike) -> None:
        """Set the iterative background vector.

        Parameters
        ----------
        value : ArrayLike
            New iterative background vector.
        """
        self._iterative_background_vector = value
        self._set_calibration_attribute(
            "iterative_background_vector",
            self._iterative_background_vector,
        )

    @staticmethod
    def _validate_decode_run_key(decode_run_key: str | None) -> str | None:
        """
        Validate an optional decoded-output run key.

        Parameters
        ----------
        decode_run_key : str or None
            Optional subfolder name under decoded-output roots.

        Returns
        -------
        str or None
            Validated run key.
        """
        if decode_run_key is None:
            return None
        decode_run_key = str(decode_run_key)
        if not re.fullmatch(r"[A-Za-z0-9_.-]+", decode_run_key):
            raise ValueError(
                "decode_run_key may only contain letters, numbers, '.', '_', and '-'."
            )
        return decode_run_key

    def _decoded_run_root(self, decode_run_key: str | None = None) -> Path:
        """
        Return the local decoded output root for an optional decode run.

        Parameters
        ----------
        decode_run_key : str or None, default None
            Optional decoded-output run key.

        Returns
        -------
        pathlib.Path
            Decoded output root.
        """
        decode_run_key = self._validate_decode_run_key(decode_run_key)
        if decode_run_key is None:
            return self._decoded_root_path
        return self._decoded_root_path / Path(decode_run_key)

    def decoded_temporary_dir(
        self,
        decode_run_key: str | None = None,
        iteration: int | None = None,
    ) -> Path:
        """
        Return the temporary decoded-output directory for a decode run.

        Parameters
        ----------
        decode_run_key : str or None, default None
            Optional decoded-output run key.
        iteration : int or None, default None
            Optional optimization iteration index.

        Returns
        -------
        pathlib.Path
            Temporary decoded-output directory.
        """
        root = self._decoded_run_root(decode_run_key) / Path("temporary")
        if iteration is not None:
            root = root / Path(f"iteration_{int(iteration):03d}")
        return root

    def _global_filtered_decoded_root(
        self,
        decode_run_key: str | None = None,
    ) -> Path:
        """
        Return the global filtered decoded-output root for an optional decode run.

        Parameters
        ----------
        decode_run_key : str or None, default None
            Optional decoded-output run key.

        Returns
        -------
        pathlib.Path
            Global filtered decoded-output root.
        """
        root = self._datastore_path / Path("all_tiles_filtered_decoded_features")
        decode_run_key = self._validate_decode_run_key(decode_run_key)
        if decode_run_key is None:
            return root
        return root / Path(decode_run_key)

    def load_decode_normalization_vectors(
        self,
        decode_run_key: str | None,
        kind: str,
    ) -> tuple[np.ndarray | None, np.ndarray | None]:
        """
        Load run-scoped normalization and background vectors.

        Parameters
        ----------
        decode_run_key : str or None
            Optional decoded-output run key. None reads the default vectors.
        kind : {'global', 'iterative'}
            Normalization vector kind.

        Returns
        -------
        tuple[numpy.ndarray or None, numpy.ndarray or None]
            Normalization and background vectors.
        """
        if kind == "global":
            if decode_run_key is None:
                return self.global_normalization_vector, self.global_background_vector
            norm_key = "global_normalization_vector"
            background_key = "global_background_vector"
        elif kind == "iterative":
            if decode_run_key is None:
                return (
                    self.iterative_normalization_vector,
                    self.iterative_background_vector,
                )
            norm_key = "iterative_normalization_vector"
            background_key = "iterative_background_vector"
        else:
            raise ValueError("kind must be one of 'global' or 'iterative'.")

        decode_run_key = self._validate_decode_run_key(decode_run_key)
        calib_attrs = self._load_calibrations_attributes()
        run_attrs = calib_attrs.get("decode_normalization_runs", {}).get(
            decode_run_key, {}
        )
        normalization_vector = run_attrs.get(norm_key)
        background_vector = run_attrs.get(background_key)
        if normalization_vector is None or background_vector is None:
            return None, None
        return (
            np.asarray(normalization_vector, dtype=np.float32),
            np.asarray(background_vector, dtype=np.float32),
        )

    def save_decode_normalization_vectors(
        self,
        decode_run_key: str | None,
        kind: str,
        normalization_vector: ArrayLike,
        background_vector: ArrayLike,
        decode_mode: str | None = None,
        metadata: Mapping[str, Any] | None = None,
    ) -> None:
        """
        Save default or run-scoped normalization and background vectors.

        Parameters
        ----------
        decode_run_key : str or None
            Optional decoded-output run key. None writes the default vectors.
        kind : {'global', 'iterative'}
            Normalization vector kind.
        normalization_vector : ArrayLike
            Foreground normalization vector.
        background_vector : ArrayLike
            Background vector.
        decode_mode : str or None, default None
            Decode mode metadata.
        metadata : Mapping[str, Any] or None, default None
            Additional provenance for these normalization vectors.
        """
        if kind == "global":
            if decode_run_key is None:
                self.global_normalization_vector = normalization_vector
                self.global_background_vector = background_vector
                self._save_default_decode_normalization_metadata(kind, metadata)
                return
            norm_key = "global_normalization_vector"
            background_key = "global_background_vector"
        elif kind == "iterative":
            if decode_run_key is None:
                self.iterative_normalization_vector = normalization_vector
                self.iterative_background_vector = background_vector
                self._save_default_decode_normalization_metadata(kind, metadata)
                return
            norm_key = "iterative_normalization_vector"
            background_key = "iterative_background_vector"
        else:
            raise ValueError("kind must be one of 'global' or 'iterative'.")

        decode_run_key = self._validate_decode_run_key(decode_run_key)
        calib_attrs = self._load_calibrations_attributes()
        runs = dict(calib_attrs.get("decode_normalization_runs", {}))
        run_attrs = dict(runs.get(decode_run_key, {}))
        if decode_mode is not None:
            run_attrs["decode_mode"] = str(decode_mode)
        if metadata is not None:
            run_attrs[f"{kind}_metadata"] = dict(metadata)
        run_attrs[norm_key] = np.asarray(normalization_vector, dtype=np.float32)
        run_attrs[background_key] = np.asarray(background_vector, dtype=np.float32)
        runs[decode_run_key] = run_attrs
        calib_attrs["decode_normalization_runs"] = runs
        self._save_calibrations_attributes(calib_attrs)

    def _save_default_decode_normalization_metadata(
        self,
        kind: str,
        metadata: Mapping[str, Any] | None,
    ) -> None:
        """Save provenance for default, non-run-scoped normalization vectors."""
        if metadata is None:
            return
        calib_attrs = self._load_calibrations_attributes()
        all_metadata = dict(calib_attrs.get("decode_normalization_metadata", {}))
        all_metadata[kind] = dict(metadata)
        calib_attrs["decode_normalization_metadata"] = all_metadata
        self._save_calibrations_attributes(calib_attrs)

    def load_decode_normalization_metadata(
        self,
        decode_run_key: str | None,
        kind: str,
    ) -> dict[str, Any] | None:
        """Load provenance for default or run-scoped normalization vectors."""
        if kind not in {"global", "iterative"}:
            raise ValueError("kind must be one of 'global' or 'iterative'.")
        calib_attrs = self._load_calibrations_attributes()
        if decode_run_key is None:
            metadata = calib_attrs.get("decode_normalization_metadata", {}).get(kind)
        else:
            decode_run_key = self._validate_decode_run_key(decode_run_key)
            metadata = (
                calib_attrs.get("decode_normalization_runs", {})
                .get(decode_run_key, {})
                .get(f"{kind}_metadata")
            )
        return dict(metadata) if isinstance(metadata, Mapping) else None

    @property
    def tile_ids(self) -> Collection[str] | None:
        """Tile IDs.

        Returns
        -------
        tile_ids : Collection[str]
            Tile IDs.
        """
        return getattr(self, "_tile_ids", None)

    @property
    def round_ids(self) -> Collection[str] | None:
        """Round IDs.

        Returns
        -------
        round_ids : Collection[str]
            Round IDs.
        """
        return getattr(self, "_round_ids", None)

    @property
    def bit_ids(self) -> Collection[str] | None:
        """Bit IDs.

        Returns
        -------
        bit_ids : Collection[str]
            Bit IDs.
        """
        return getattr(self, "_bit_ids", None)

    def _init_datastore(self) -> None:
        """Initialize datastore.

        Create directory structure and initialize datastore state.
        """
        self._datastore_path.mkdir(parents=True)
        self._calibrations_zarr_path = self._datastore_path / Path(r"calibrations")
        self._calibrations_zarr_path.mkdir()
        self._save_to_json({}, self._calibrations_attributes_path())
        self.fiducial_folder_name = r"fiducial"
        self._fiducial_root_path = self._datastore_path / Path(
            self.fiducial_folder_name
        )
        self._fiducial_root_path.mkdir()
        self._readouts_root_path = self._datastore_path / Path(r"readouts")
        self._readouts_root_path.mkdir()
        self.feature_predictor_folder_name = r"feature_predictor"
        self._feature_predictor_localizations_root_path = self._datastore_path / Path(
            f"{self.feature_predictor_folder_name}_localizations"
        )
        self._feature_predictor_localizations_root_path.mkdir()
        self._decoded_root_path = self._datastore_path / Path(r"decoded")
        self._decoded_root_path.mkdir()
        self._fused_root_path = self._datastore_path / Path(r"fused")
        self._fused_root_path.mkdir()
        self._segmentation_root_path = self._datastore_path / Path(r"segmentation")
        self._segmentation_root_path.mkdir()

        # initialize datastore state
        self._datastore_state_json_path = self._datastore_path / Path(
            r"datastore_state.json"
        )
        self._datastore_state = {
            "Version": 0.6,
            "Initialized": True,
            "Calibrations": False,
            "Corrected": False,
            "LocalRegistered": False,
            "GlobalRegistered": False,
            "Fused": False,
            "SegmentedCells": False,
            "DecodedSpots": False,
            "FilteredSpots": False,
        }

        self._save_to_json(self._datastore_state, self._datastore_state_json_path)

    @staticmethod
    def _create_array_tensorstore_qi2lab(
        path: Path,
        shape: tuple[int, ...],
        dtype: Any,
        chunks: tuple[int, ...],
        *,
        shards: tuple[int, ...] | None,
        dimension_names: list[str] | None,
        overwrite: bool,
        compression: str,
    ) -> Any:
        """
        Create a Zarr v3 array for the yaozarrs image writer.

        yaozarrs accepts a custom array creator but does not expose compression
        level or shuffle settings. This TensorStore adapter preserves the
        datastore's Blosc level 5 and bitshuffle settings; yaozarrs handles
        the OME group, axes, and image metadata.

        Parameters
        ----------
        path : Path
            Destination zarr array path.
        shape : tuple[int, ...]
            Array shape.
        dtype : Any
            Array dtype.
        chunks : tuple[int, ...]
            Chunk shape.
        shards : tuple[int, ...] | None
            Optional shard shape.
        dimension_names : list[str] | None
            Optional dimension names for metadata.
        overwrite : bool
            Whether to replace an existing array.
        compression : str
            Compression preset name.

        Returns
        -------
        Any
            Open tensorstore array handle.
        """
        import tensorstore as ts

        if compression == "blosc-zstd":
            chunk_codecs = [
                {
                    "name": "blosc",
                    "configuration": {
                        "cname": "zstd",
                        "clevel": 5,
                        "shuffle": "bitshuffle",
                    },
                }
            ]
        elif compression == "blosc-lz4":
            chunk_codecs = [
                {
                    "name": "blosc",
                    "configuration": {
                        "cname": "lz4",
                        "clevel": 5,
                        "shuffle": "bitshuffle",
                    },
                }
            ]
        elif compression == "zstd":
            chunk_codecs = [{"name": "zstd", "configuration": {"level": 3}}]
        elif compression == "none":
            chunk_codecs = []
        else:
            raise ValueError(f"Unknown compression: {compression}")

        codecs = chunk_codecs
        chunk_layout: dict[str, Any] = {"chunk": {"shape": list(chunks)}}
        if shards is not None:
            codecs = [
                {
                    "name": "sharding_indexed",
                    "configuration": {
                        "chunk_shape": list(chunks),
                        "codecs": chunk_codecs,
                    },
                }
            ]
            chunk_layout = {"write_chunk": {"shape": list(shards)}}

        domain: dict[str, Any] = {"shape": list(shape)}
        if dimension_names:
            domain["labels"] = dimension_names

        try:
            dtype_str = dtype.name
        except AttributeError:
            dtype_str = str(dtype)

        return ts.open(
            {
                "driver": "zarr3",
                "kvstore": {"driver": "file", "path": str(path)},
                "schema": {
                    "dtype": dtype_str,
                    "domain": domain,
                    "chunk_layout": chunk_layout,
                    "codec": {"driver": "zarr3", "codecs": codecs},
                },
                "create": True,
                "delete_existing": overwrite,
            }
        ).result()

    @staticmethod
    def _normalize_transform(
        values: Sequence[float] | None, ndim: int, fill: float
    ) -> list[float]:
        """
        Normalize transform vectors to match array dimensionality.

        Parameters
        ----------
        values : Sequence[float] | None
            Optional transform vector.
        ndim : int
            Target array dimensionality.
        fill : float
            Fill value for missing leading dimensions.

        Returns
        -------
        list[float]
            Transform vector with one value per array dimension.
        """
        if values is None:
            return [fill] * ndim
        cast = [float(v) for v in values]
        if len(cast) == ndim:
            return cast
        if len(cast) == 3:
            if ndim == 2:
                return cast[1:]
            if ndim >= 3:
                return [fill] * (ndim - 3) + cast
        raise ValueError(f"Cannot map {len(cast)} transform values onto {ndim} axes.")

    @staticmethod
    def _default_chunks(
        array: np.ndarray,
        spatial_chunk_zyx: tuple[int, int, int] = (16, 512, 512),
    ) -> list[int]:
        """
        Create sane default chunk sizes based on dimensionality.

        Parameters
        ----------
        array : np.ndarray
            Array that will be written.
        spatial_chunk_zyx : tuple[int, int, int], default=(16, 512, 512)
            Desired Z, Y, X storage chunks for local fiducial and readout images.

        Returns
        -------
        list[int]
            Chunk shape matched to the array dimensionality.
        """
        z_chunk, y_chunk, x_chunk = (int(value) for value in spatial_chunk_zyx)
        if array.ndim == 2:
            return [
                min(int(array.shape[0]), y_chunk),
                min(int(array.shape[1]), x_chunk),
            ]
        if array.ndim == 3:
            return [
                min(int(array.shape[0]), z_chunk),
                min(int(array.shape[1]), y_chunk),
                min(int(array.shape[2]), x_chunk),
            ]
        if array.ndim == 4:
            return [
                1,
                min(int(array.shape[1]), z_chunk),
                min(int(array.shape[2]), y_chunk),
                min(int(array.shape[3]), x_chunk),
            ]
        if array.ndim == 5:
            return [
                1,
                1,
                min(int(array.shape[2]), z_chunk),
                min(int(array.shape[3]), y_chunk),
                min(int(array.shape[4]), x_chunk),
            ]
        return list(array.shape)

    @staticmethod
    def _fused_image_chunks(array: np.ndarray) -> list[int]:
        """
        Create chunk sizes tailored for fused image storage.

        Parameters
        ----------
        array : np.ndarray
            Fused image array that will be written.

        Returns
        -------
        list[int]
            Chunk shape for fused image storage.
        """
        shape = [int(dim) for dim in array.shape]
        if array.ndim == 2:
            return [min(shape[0], 2048), min(shape[1], 2048)]
        if array.ndim == 3:
            return [min(shape[0], 16), min(shape[1], 512), min(shape[2], 512)]
        if array.ndim == 4:
            return [
                min(shape[0], 1),
                min(shape[1], 16),
                min(shape[2], 512),
                min(shape[3], 512),
            ]
        if array.ndim == 5:
            return [
                min(shape[0], 1),
                min(shape[1], 1),
                min(shape[2], 16),
                min(shape[3], 512),
                min(shape[4], 512),
            ]
        return list(array.shape)

    @staticmethod
    def _build_axes(v05: Any, ndim: int) -> list[Any]:
        """
        Build NGFF axes models for a given dimensionality.

        Parameters
        ----------
        v05 : Any
            yaozarrs NGFF model namespace.
        ndim : int
            Number of array dimensions.

        Returns
        -------
        list[Any]
            NGFF axis models ordered to match array dimensions.
        """
        axis_names = ["t", "c", "z", "y", "x"][-ndim:]
        axes: list[Any] = []
        for axis_name in axis_names:
            if axis_name in {"z", "y", "x"}:
                axes.append(v05.SpaceAxis(name=axis_name, unit="micrometer"))
            elif axis_name == "c":
                axes.append(v05.ChannelAxis(name="c"))
            else:
                axes.append(v05.TimeAxis(name="t", unit="second"))
        return axes

    @staticmethod
    def _entity_attributes_path(entity_root_path: Path | str) -> Path:
        """
        Path to per-entity metadata sidecar.

        Parameters
        ----------
        entity_root_path : Path | str
            Entity folder path.

        Returns
        -------
        Path
            Entity metadata sidecar path.
        """
        return Path(entity_root_path) / Path("attributes.json")

    @staticmethod
    def _image_store_path(image_path: Path | str) -> Path:
        """
        Normalize image path to the *.ome.zarr folder naming scheme.

        Parameters
        ----------
        image_path : Path | str
            Logical image path or OME-Zarr path.

        Returns
        -------
        Path
            Normalized path ending in ``.ome.zarr``.
        """
        path = Path(image_path)
        if path.name.endswith(".ome.zarr"):
            return path
        if path.name.endswith(".zarr"):
            raise ValueError(
                f"Invalid image store name '{path.name}'. Expected '.ome.zarr' suffix."
            )
        if path.suffixes:
            raise ValueError(
                f"Invalid image store name '{path.name}'. Use bare logical names or '.ome.zarr'."
            )
        return path.with_name(path.name + ".ome.zarr")

    @staticmethod
    def load_image_metadata(image_path: Path | str) -> dict[str, Any]:
        """
        Load extra attributes through yaozarrs.

        Parameters
        ----------
        image_path : Path | str
            Image store path.

        Returns
        -------
        dict[str, Any]
            Extra attributes stored on the image root.
        """
        image_root = qi2labDataStore._image_store_path(image_path)
        attrs = dict(open_group(str(image_root)).attrs)
        attrs.pop("ome", None)
        for key in ("spacing_zyx_um", "voxel_size_zyx_um"):
            if key in attrs:
                attrs[key] = round_spacing_um(attrs[key]).tolist()
        return attrs

    @staticmethod
    def save_image_metadata(
        image_path: Path | str,
        extra_attributes: Mapping[str, Any],
        merge: bool = True,
    ) -> None:
        """
        Write image-level extra attributes for externally-created OME-Zarr stores.

        Parameters
        ----------
        image_path : Path | str
            Image group path. Both the directory path and the corresponding
            OME-Zarr store path are accepted.
        extra_attributes : Mapping[str, Any]
            Attribute updates to write at the image root.
        merge : bool, default=True
            If True, merge updates into existing attributes. If False, replace
            the existing image-level attributes with ``extra_attributes``.

        Returns
        -------
        None
            Attributes are written to the Zarr v3 ``zarr.json``. The OME
            metadata is preserved when replacing extra attributes.
        """
        image_root = qi2labDataStore._image_store_path(image_path)
        payload = {
            str(k): qi2labDataStore._to_json_compatible(v)
            for k, v in dict(extra_attributes).items()
        }

        for key in ("spacing_zyx_um", "voxel_size_zyx_um"):
            if key in payload:
                payload[key] = round_spacing_um(payload[key]).tolist()

        group = open_group(image_root)
        metadata = group.metadata.model_dump(mode="json", exclude_none=True)
        if metadata["zarr_format"] != 3:
            raise ValueError("Datastore images must use OME-Zarr on Zarr v3.")
        existing = dict(group.attrs)
        attributes = existing if merge else {"ome": existing["ome"]}
        attributes.update(payload)
        round_ome_spatial_scales(attributes)
        metadata["attributes"] = attributes
        # yaozarrs exposes attributes read-only. Updating metadata for an
        # externally fused image requires replacing the local Zarr v3 JSON.
        qi2labDataStore._save_to_json(metadata, image_root / "zarr.json")

    @staticmethod
    def _to_json_compatible(value: Any) -> Any:
        """
        Convert numpy/scalar containers to JSON-compatible values.

        Parameters
        ----------
        value : Any
            Value to convert before JSON serialization.

        Returns
        -------
        Any
            JSON-compatible representation.
        """
        if isinstance(value, np.ndarray):
            return value.tolist()
        if isinstance(value, np.generic):
            return value.item()
        if isinstance(value, Mapping):
            return {
                str(k): qi2labDataStore._to_json_compatible(v) for k, v in value.items()
            }
        if isinstance(value, tuple):
            return [qi2labDataStore._to_json_compatible(v) for v in value]
        if isinstance(value, list):
            return [qi2labDataStore._to_json_compatible(v) for v in value]
        return value

    @staticmethod
    def image_shape(image_path: Path | str) -> tuple[int, ...] | None:
        """
        Read image shape without loading all pixels.

        Parameters
        ----------
        image_path : Path | str
            Image store path.

        Returns
        -------
        tuple[int, ...] | None
            Image array shape, or ``None`` when the image is unavailable.
        """
        path = qi2labDataStore._image_store_path(image_path)
        if not path.exists():
            return None

        try:
            group = open_group(str(path))
            array_0 = group["0"]
            shape = array_0.metadata.shape
            return tuple(int(dim) for dim in shape)
        except (FileNotFoundError, KeyError):
            return None

    def _load_entity_attributes(
        self,
        entity_root_path: Path | str,
        image_names: Sequence[str] | None = None,
    ) -> dict[str, Any]:
        """
        Load entity metadata from sidecar + image extra_attributes.

        Parameters
        ----------
        entity_root_path : Path | str
            Entity folder path.
        image_names : Sequence[str] | None
            Optional image names whose extra attributes should be merged.

        Returns
        -------
        dict[str, Any]
            Merged entity metadata.
        """
        entity_root = Path(entity_root_path)
        merged: dict[str, Any] = {}

        default_images = (
            "corrected_data",
            "decon_data",
            f"{self.feature_predictor_folder_name}_data",
            "opticalflow_xform_px",
        )
        candidate_names = image_names if image_names is not None else default_images
        for image_name in candidate_names:
            image_path = self._image_store_path(entity_root / Path(image_name))
            if not image_path.exists():
                continue
            merged.update(self.load_image_metadata(image_path))

        merged.update(self._load_from_json(self._entity_attributes_path(entity_root)))

        return merged

    def _save_entity_attributes(
        self,
        entity_root_path: Path | str,
        updates: Mapping[str, Any],
    ) -> None:
        """
        Save metadata to the entity sidecar.

        Parameters
        ----------
        entity_root_path : Path | str
            Entity folder path.
        updates : Mapping[str, Any]
            Metadata updates to persist.

        Returns
        -------
        None
            No return value.
        """
        if not updates:
            return

        entity_root = Path(entity_root_path)
        payload = {
            str(k): self._to_json_compatible(v) for k, v in dict(updates).items()
        }

        sidecar_path = self._entity_attributes_path(entity_root)
        sidecar_attrs = self._load_from_json(sidecar_path)
        sidecar_attrs.update(payload)
        self._save_to_json(sidecar_attrs, sidecar_path)

    def _update_image_translation_transform(
        self,
        image_root: Path,
        stage_zyx_um: Sequence[float],
    ) -> None:
        """
        Update an existing OME-Zarr image translation transform.

        Parameters
        ----------
        image_root : Path
            Image root path, without or with the ``.ome.zarr`` suffix.
        stage_zyx_um : Sequence[float]
            Physical Z, Y, X translation to write into the image metadata.

        Returns
        -------
        None
            The image metadata is updated in place when it already exists.
        """
        image_path = self._image_store_path(image_root)
        metadata_path = image_path / Path("zarr.json")
        if not metadata_path.exists():
            return

        metadata = open_group(image_path).metadata.model_dump(
            mode="json", exclude_none=True
        )

        transforms = (
            metadata.get("attributes", {})
            .get("ome", {})
            .get("multiscales", [{}])[0]
            .get("datasets", [{}])[0]
            .get("coordinateTransformations", [])
        )
        for transform in transforms:
            if transform.get("type") == "translation":
                transform["translation"] = [float(v) for v in stage_zyx_um]
                self._save_to_json(metadata, metadata_path)
                return

    @staticmethod
    def _normalize_stage_position_zyx_um(stage_zyx_um: ArrayLike) -> np.ndarray:
        """Return ZYX stage coordinates, padding legacy YX positions with Z=0."""
        stage = np.asarray(stage_zyx_um, dtype=np.float32)
        if stage.shape == (2,):
            return np.asarray((0.0, stage[0], stage[1]), dtype=np.float32)
        if stage.shape != (3,):
            raise ValueError(
                "Stage position must contain two (Y, X) or three (Z, Y, X) "
                f"coordinates; got shape {stage.shape}."
            )
        return stage

    def _resolve_original_tile_position_zyx_um(
        self,
        tile_id: str,
        round_id: str | None = None,
        bit_id: str | None = None,
    ) -> list[float] | None:
        """
        Resolve original tile stage position used for OME translation.

        Parameters
        ----------
        tile_id : str
            Tile identifier.
        round_id : str | None
            Optional fiducial round identifier.
        bit_id : str | None
            Optional readout bit identifier.

        Returns
        -------
        list[float] | None
            Original stage position in Z, Y, X microns, if available.
        """
        if round_id is not None:
            fiducial_entity = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            attrs = self._load_entity_attributes(fiducial_entity)
            stage = attrs.get("stage_zyx_um")
            if stage is not None:
                return self._normalize_stage_position_zyx_um(stage).tolist()

        if bit_id is not None:
            round_linker = self.load_local_round_linker(tile=tile_id, bit=bit_id)
            if round_linker is not None and int(round_linker) > 0:
                linked_round_id = self._round_ids[int(round_linker) - 1]
                fiducial_entity = (
                    self._fiducial_root_path / Path(tile_id) / Path(linked_round_id)
                )
                attrs = self._load_entity_attributes(fiducial_entity)
                stage = attrs.get("stage_zyx_um")
                if stage is not None:
                    return self._normalize_stage_position_zyx_um(stage).tolist()

        if getattr(self, "_round_ids", None):
            fiducial_entity = (
                self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
            )
            attrs = self._load_entity_attributes(fiducial_entity)
            stage = attrs.get("stage_zyx_um")
            if stage is not None:
                return self._normalize_stage_position_zyx_um(stage).tolist()
        return None

    def _resolve_reference_tile_position_zyx_um(
        self, tile_id: str
    ) -> list[float] | None:
        """
        Resolve the first-round reference stage position for derived outputs.

        Parameters
        ----------
        tile_id : str
            Tile identifier.

        Returns
        -------
        list[float] or None
            First fiducial round stage position in Z, Y, X microns.
        """
        if not getattr(self, "_round_ids", None):
            return None
        return self._resolve_original_tile_position_zyx_um(
            tile_id=tile_id, round_id=self._round_ids[0]
        )

    def _validate_core_image_shape(
        self,
        entity_root_path: Path | str,
        image_name: str,
        image: ArrayLike,
    ) -> None:
        """
        Enforce corrected/deconvolved/feature image shape consistency.

        Parameters
        ----------
        entity_root_path : Path | str
            Entity folder path.
        image_name : str
            Logical image name being validated.
        image : ArrayLike
            Image data to validate.

        Returns
        -------
        None
            No return value.
        """
        entity_root = Path(entity_root_path)
        shape = tuple(int(v) for v in np.asarray(image).shape)
        required_names = {
            "corrected_data",
            "decon_data",
            f"{self.feature_predictor_folder_name}_data",
        }
        for candidate_name in required_names:
            if candidate_name == image_name:
                continue
            candidate_shape = self.image_shape(entity_root / Path(candidate_name))
            if candidate_shape is None:
                continue
            if tuple(candidate_shape) != shape:
                raise ValueError(
                    f"Image shape mismatch in {entity_root.name}: "
                    f"{image_name}={shape} but {candidate_name}={candidate_shape}. "
                    "corrected_data, optional decon_data, and "
                    "feature_predictor_data must match."
                )

    @staticmethod
    def _load_from_json(dictionary_path: Path | str) -> dict:
        """Load json as dictionary.

        Parameters
        ----------
        dictionary_path : Path or str
            Path to json file.

        Returns
        -------
        dictionary : dict
            Dictionary from json file.
        """
        try:
            with open(dictionary_path) as f:
                dictionary = json.load(f)
        except FileNotFoundError:
            return {}
        if not isinstance(dictionary, dict):
            raise ValueError(f"Expected a JSON object in {dictionary_path}")
        return dictionary

    @staticmethod
    def _save_to_json(dictionary: dict, dictionary_path: Path | str) -> None:
        """Save dictionary to json.

        Parameters
        ----------
        dictionary : dict
            The data to be saved.
        dictionary_path : Path or str
            The path to the JSON file where the data will be saved.
        """
        serialized = json.dumps(dictionary, indent=4)
        with open(dictionary_path, "w", encoding="utf-8") as file:
            file.write(serialized)

    @staticmethod
    def _load_from_microjson(dictionary_path: Path | str) -> dict:
        """Load cell outlines outlines microjson as dictionary.

        Parameters
        ----------
        dictionary_path : Path or str
            Path to microjson file.

        Returns
        -------
        outlines : dict
            Cell outlines dictionary.
        """
        try:
            with open(dictionary_path) as f:
                data = json.load(f)
                outlines = {}
                for feature in data["features"]:
                    cell_id = feature["properties"]["cell_id"]
                    coordinates = feature["geometry"]["coordinates"][0]
                    outlines[cell_id] = np.array(coordinates)
        except (
            FileNotFoundError,
            json.JSONDecodeError,
            KeyError,
            TypeError,
            ValueError,
        ):
            outlines = {}
        return outlines

    @staticmethod
    def _check_for_zarr_array(image_path: Path | str) -> None:
        """Check if image exists and is readable via yaozarrs.

        Parameters
        ----------
        image_path : Path or str
            Image store path.
        """
        image_path = qi2labDataStore._image_store_path(image_path)
        if not image_path.exists():
            raise FileNotFoundError(image_path)

        group = open_group(str(image_path))
        _ = group["0"]

    @staticmethod
    def _load_from_zarr_array(
        image_path: Path | str, return_future: bool | None = True
    ) -> "np.ndarray | Future | TensorStore":
        """Read image data via yaozarrs.

        Parameters
        ----------
        image_path : Path or str
            Image store path.
        return_future : bool or None
            Return read future (True), immediately read (False), or return the
            TensorStore array without issuing a read (None).

        Returns
        -------
        array : tensorstore.Future or numpy.ndarray or tensorstore.TensorStore
            Read future, immediate array, or lazy TensorStore handle obtained
            through yaozarrs.
        """
        image_path = qi2labDataStore._image_store_path(image_path)
        group = open_group(str(image_path))
        current_array = group["0"].to_tensorstore()

        if return_future is None:
            return current_array
        read_future = current_array.read()
        return read_future if return_future else read_future.result()

    @staticmethod
    def _save_to_zarr_array(
        array: ArrayLike,
        image_path: Path | str,
        return_future: bool | None = False,
        *,
        chunks: Sequence[int] | None = None,
        ome_scale: Sequence[float] | None = None,
        ome_translation: Sequence[float] | None = None,
        extra_attributes: Mapping[str, Any] | None = None,
    ) -> "WriteFutures | None":
        """Save image data as OME-Zarr v0.5 using yaozarrs tensorstore writer.

        Parameters
        ----------
        array : ArrayLike
            Array to save.
        image_path : Path or str
            Image store path.
        chunks : Sequence[int] or None
            Storage chunk shape. None selects the datastore default.
        ome_scale : Sequence[float] or None
            Pixel spacing in microns, in image-axis order or ZYX order.
        ome_translation : Sequence[float] or None
            Image origin in microns, in image-axis order or ZYX order.
        extra_attributes : Mapping or None
            Additional image metadata.
        return_future : bool or None
            Return the write-completion handle (True), or wait for the write
            to finish and return None (False or None).

        Returns
        -------
        write_future : tensorstore.WriteFutures or None
            Pixel-write completion handle when return_future is True.

        Raises
        ------
        OSError, ValueError
            Storage or metadata errors. Failed writes are not reported as success.
        """
        image_path = qi2labDataStore._image_store_path(image_path)
        image_path.parent.mkdir(parents=True, exist_ok=True)

        image_array = np.asarray(array)
        if image_array.dtype == np.float64:
            image_array = image_array.astype(np.float32)

        if image_array.ndim < 2 or image_array.ndim > 5:
            raise ValueError(
                f"Unsupported array ndim for image write: {image_array.ndim}"
            )

        if chunks is None:
            chunks = qi2labDataStore._default_chunks(image_array)
        scale = qi2labDataStore._normalize_transform(ome_scale, image_array.ndim, 1.0)
        translation = qi2labDataStore._normalize_transform(
            ome_translation, image_array.ndim, 0.0
        )

        axes = qi2labDataStore._build_axes(v05, image_array.ndim)
        scale[-3:] = round_spacing_um(scale[-3:]).tolist()
        transforms = [
            v05.ScaleTransformation(scale=scale),
            v05.TranslationTransformation(translation=translation),
        ]
        datasets = [v05.Dataset(path="0", coordinateTransformations=transforms)]
        multiscales = [v05.Multiscale(axes=axes, datasets=datasets)]

        image_metadata = v05.Image(multiscales=multiscales)

        chunk_spec = tuple(int(c) for c in chunks)
        write_options = {
            "extra_attributes": qi2labDataStore._to_json_compatible(extra_attributes)
            if extra_attributes
            else None,
            "writer": qi2labDataStore._create_array_tensorstore_qi2lab,
            "overwrite": True,
            "chunks": chunk_spec,
            "compression": "blosc-zstd",
        }
        if return_future:
            from yaozarrs.write.v05 import prepare_image

            # yaozarrs creates the complete OME-Zarr v3 structure. Its write_image
            # API is synchronous; writing the prepared array is necessary to
            # preserve the datastore's TensorStore write-completion handle.
            _, arrays = prepare_image(
                dest=str(image_path),
                image=image_metadata,
                datasets=(image_array.shape, image_array.dtype),
                **write_options,
            )
            return arrays["0"].write(image_array)
        write_image(
            dest=str(image_path),
            image=image_metadata,
            datasets=image_array,
            **write_options,
        )
        return None

    @staticmethod
    def _load_from_parquet(parquet_path: Path | str) -> pd.DataFrame:
        """Load dataframe from parquet.

        Parameters
        ----------
        parquet_path : Path or str
            Path to parquet file.

        Returns
        -------
        df : pd.DataFrame
            Dataframe from parquet file.
        """
        return pd.read_parquet(parquet_path)

    @staticmethod
    def _save_to_parquet(df: pd.DataFrame, parquet_path: Path | str) -> None:
        """Save dataframe to parquet.

        Parameters
        ----------
        df : pd.DataFrame
            Dataframe to save.
        parquet_path : Path or str
            Path to parquet file.
        """
        df.to_parquet(parquet_path, engine="fastparquet", index=False)

    @staticmethod
    def _save_to_csv_gz(df: pd.DataFrame, csv_gz_path: Path | str) -> None:
        """Save dataframe to gzipped CSV.

        Parameters
        ----------
        df : pd.DataFrame
            Dataframe to save.
        csv_gz_path : Path or str
            Path to gzipped CSV file.
        """
        df.to_csv(csv_gz_path, index=False, compression="gzip")

    def _parse_datastore(self, validate: bool = True) -> None:
        """
        Parse datastore to discover available components.

        Parameters
        ----------
        validate : bool
            Whether to validate existing zarr arrays while parsing.

        Returns
        -------
        None
            No return value.
        """
        # directory structure as defined by qi2lab spec
        self._datastore_state_json_path = self._datastore_path / Path(
            r"datastore_state.json"
        )
        # read in .json in root directory that indicates what steps have been run
        with open(self._datastore_state_json_path) as json_file:
            self._datastore_state = json.load(json_file)
        if float(self._datastore_state["Version"]) != 0.6:
            raise ValueError("Only datastore version 0.6 is supported by this build.")

        self.fiducial_folder_name = "fiducial"
        self.feature_predictor_folder_name = "feature_predictor"
        self._fiducial_root_path = self._datastore_path / Path(
            self.fiducial_folder_name
        )
        self._feature_predictor_localizations_root_path = self._datastore_path / Path(
            f"{self.feature_predictor_folder_name}_localizations"
        )
        self._calibrations_zarr_path = self._datastore_path / Path(r"calibrations")
        self._readouts_root_path = self._datastore_path / Path(r"readouts")
        self._decoded_root_path = self._datastore_path / Path(r"decoded")
        self._fused_root_path = self._datastore_path / Path(r"fused")
        self._segmentation_root_path = self._datastore_path / Path(r"segmentation")

        # validate calibrations
        if self._datastore_state["Calibrations"]:
            if not (self._calibrations_zarr_path.exists()):
                raise FileNotFoundError("Calibration data directory is missing.")
            attributes = self._load_calibrations_attributes()

            keys_to_check = [
                "num_rounds",
                "num_tiles",
                "channels_in_data",
                "tile_overlap",
                "binning",
                "e_per_ADU",
                "na",
                "ri",
                "exp_order",
                "codebook",
                "num_bits",
                "microscope_type",
                "camera_model",
                "voxel_size_zyx_um",
            ]
            for key in keys_to_check:
                if key not in attributes.keys():
                    raise KeyError("Calibration attributes incomplete")

            self._num_rounds = attributes["num_rounds"]
            self._num_tiles = attributes["num_tiles"]
            self._channels_in_data = attributes["channels_in_data"]
            self._tile_overlap = attributes["tile_overlap"]
            self._binning = attributes["binning"]
            self._e_per_ADU = attributes["e_per_ADU"]
            self._na = attributes["na"]
            self._ri = attributes["ri"]
            self._exp_order = attributes["exp_order"]
            self._codebook = attributes["codebook"]
            self._num_bits = attributes["num_bits"]
            self._microscope_type = attributes["microscope_type"]
            self._camera_model = attributes["camera_model"]
            self._voxel_size_zyx_um = self._normalize_voxel_size_zyx_um(
                attributes["voxel_size_zyx_um"]
            )

            if getattr(self, "_exp_order", None) is not None:
                self._experiment_order = self._coerce_experiment_order_dataframe(
                    self._exp_order
                )

            if getattr(self, "_num_tiles", None) is not None:
                self._tile_ids = [
                    "tile" + str(tile_idx).zfill(4)
                    for tile_idx in range(self._num_tiles)
                ]
            if getattr(self, "_num_rounds", None) is not None:
                self._round_ids = [
                    "round" + str(round_idx + 1).zfill(3)
                    for round_idx in range(self._num_rounds)
                ]
            if getattr(self, "_num_bits", None) is not None:
                self._bit_ids = [
                    "bit" + str(bit_idx + 1).zfill(3)
                    for bit_idx in range(self._num_bits)
                ]

            if validate:
                psf_root_path = self._calibrations_zarr_path / Path("psf_data")
                try:
                    if psf_root_path.exists():

                        def psf_sort_key(path: Path) -> int:
                            """
                            Return the numeric PSF directory index.

                            Parameters
                            ----------
                            path : Path
                                PSF directory path.

                            Returns
                            -------
                            int
                                PSF directory index.
                            """
                            return int(path.name[len("psf_") : len("psf_") + 3])

                        psf_dirs = sorted(
                            [
                                entry
                                for entry in psf_root_path.iterdir()
                                if entry.is_dir()
                                and re.fullmatch(r"psf_\d{3}\.ome\.zarr", entry.name)
                            ],
                            key=psf_sort_key,
                        )
                    else:
                        psf_dirs = []

                    if len(psf_dirs) > 0:
                        psf_list = []
                        for psf_dir in psf_dirs:
                            psf_array = self._load_from_zarr_array(
                                psf_dir, return_future=False
                            )
                            psf_list.append(np.asarray(psf_array, dtype=np.float32))
                        self._psfs = psf_list
                except (OSError, ValueError):
                    print("Calibration psfs missing.")

        # validate fiducial and readout bits data
        if self._datastore_state["Corrected"] and validate:
            if not (self._fiducial_root_path.exists()):
                raise FileNotFoundError("fiducial directory not initialized")
            else:
                fiducial_tile_ids = self._collect_strict_ids(
                    self._fiducial_root_path, prefix="tile", width=4
                )
                if len(fiducial_tile_ids) == 0:
                    raise FileNotFoundError("No tile folders found under fiducial/")
                current_tile_dir_path = self._fiducial_root_path / Path(
                    fiducial_tile_ids[0]
                )
                self._round_ids = self._collect_strict_ids(
                    current_tile_dir_path, prefix="round", width=3
                )
            if not (self._readouts_root_path.exists()):
                raise FileNotFoundError("Readout directory not initialized")
            else:
                readout_tile_ids = self._collect_strict_ids(
                    self._readouts_root_path, prefix="tile", width=4
                )
                if len(readout_tile_ids) == 0:
                    raise FileNotFoundError("No tile folders found under readouts/")
                current_tile_dir_path = self._readouts_root_path / Path(
                    readout_tile_ids[0]
                )
                self._bit_ids = self._collect_strict_ids(
                    current_tile_dir_path, prefix="bit", width=3
                )
            assert fiducial_tile_ids == readout_tile_ids, (
                "fiducial and readout tile ids do not match. Conversion error."
            )
            self._tile_ids = fiducial_tile_ids.copy()
            del fiducial_tile_ids, readout_tile_ids

            for tile_id, round_id in product(self._tile_ids, self._round_ids):
                entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
                attributes = self._load_entity_attributes(entity_root)

                keys_to_check = [
                    "stage_zyx_um",
                    "excitation_um",
                    "emission_um",
                    # "exposure_ms",
                    "psf_idx",
                ]

                for key in keys_to_check:
                    if key not in attributes.keys():
                        print(tile_id, round_id, key)
                        raise KeyError("Corrected fiducial attributes incomplete")
                if "bit_linker" not in attributes:
                    print(tile_id, round_id, "bit_linker")
                    raise KeyError("Corrected fiducial attributes incomplete")

                current_local_zarr_path = str(entity_root / Path("corrected_data"))

                try:
                    self._check_for_zarr_array(current_local_zarr_path)
                except (OSError, ValueError):
                    print(tile_id, round_id)
                    print("Corrected fiducial data missing.")

            for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
                entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
                attributes = self._load_entity_attributes(entity_root)

                keys_to_check = [
                    "excitation_um",
                    "emission_um",
                    # "exposure_ms",
                    "psf_idx",
                ]
                for key in keys_to_check:
                    if key not in attributes.keys():
                        raise KeyError("Corrected readout attributes incomplete")
                if "round_linker" not in attributes:
                    raise KeyError("Corrected readout attributes incomplete")

                current_local_zarr_path = str(entity_root / Path("corrected_data"))

                try:
                    self._check_for_zarr_array(current_local_zarr_path)
                except (OSError, ValueError):
                    print(tile_id, bit_id)
                    print("Corrected readout data missing.")

        # check and validate local transform and preprocessing data
        if self._datastore_state["LocalRegistered"] and validate:
            for tile_id, round_id in product(self._tile_ids, self._round_ids):
                entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
                if round_id != self._round_ids[0]:
                    attributes = self._load_entity_attributes(entity_root)

                    keys_to_check = ["local_round_transform_zyx_um"]

                    for key in keys_to_check:
                        if key not in attributes.keys():
                            raise KeyError(
                                f"{round_id, tile_id} local round transform missing"
                            )

                    current_local_zarr_path = str(
                        entity_root / Path("opticalflow_xform_px")
                    )

                    try:
                        self._check_for_zarr_array(current_local_zarr_path)
                    except (OSError, ValueError):
                        # print(tile_id, round_id)
                        # print("Optical flow registration data missing.")
                        pass

                corrected_shape = self.image_shape(entity_root / Path("corrected_data"))
                decon_shape = self.image_shape(entity_root / Path("decon_data"))
                if (
                    corrected_shape is not None
                    and decon_shape is not None
                    and corrected_shape != decon_shape
                ):
                    raise ValueError(
                        f"{tile_id} {round_id} corrected and decon shapes differ: "
                        f"{corrected_shape} != {decon_shape}"
                    )

            for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
                entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
                current_local_zarr_path = str(
                    entity_root / Path(f"{self.feature_predictor_folder_name}_data")
                )

                try:
                    self._check_for_zarr_array(current_local_zarr_path)
                except (OSError, ValueError):
                    print(tile_id, bit_id)
                    print("feature_predictor prediction missing.")
                corrected_shape = self.image_shape(entity_root / Path("corrected_data"))
                decon_shape = self.image_shape(entity_root / Path("decon_data"))
                feature_shape = self.image_shape(
                    entity_root / Path(f"{self.feature_predictor_folder_name}_data")
                )
                shapes = [
                    shape
                    for shape in (corrected_shape, decon_shape, feature_shape)
                    if shape is not None
                ]
                if len(shapes) > 1 and any(shape != shapes[0] for shape in shapes[1:]):
                    raise ValueError(
                        f"{tile_id} {bit_id} corrected/decon/feature image shapes differ: "
                        f"{corrected_shape}, {decon_shape}, {feature_shape}"
                    )

            for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
                current_feature_predictor_path = (
                    self._feature_predictor_localizations_root_path
                    / Path(tile_id)
                    / Path(bit_id + ".parquet")
                )
                if not (current_feature_predictor_path.exists()):
                    raise FileNotFoundError(
                        tile_id
                        + " "
                        + bit_id
                        + " feature_predictor localization missing"
                    )

        # check and validate global registered data
        if self._datastore_state["GlobalRegistered"] and validate:
            for tile_id in self._tile_ids:
                entity_root = (
                    self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
                )
                attributes = self._load_entity_attributes(entity_root)

                keys_to_check = ["affine_zyx_um", "origin_zyx_um", "spacing_zyx_um"]

                for key in keys_to_check:
                    if key not in attributes.keys():
                        raise KeyError("Global registration missing")

        # check and validate fused
        if self._datastore_state["Fused"] and validate:
            fused_image_path = self._fused_root_path / Path(
                f"fused_{self.fiducial_folder_name}_zyx"
            )
            attributes = self.load_image_metadata(fused_image_path)

            keys_to_check = ["affine_zyx_um", "origin_zyx_um", "spacing_zyx_um"]

            for key in keys_to_check:
                if key not in attributes.keys():
                    raise KeyError("Fused image metadata missing")

            current_local_zarr_path = str(fused_image_path)

            try:
                self._check_for_zarr_array(current_local_zarr_path)
            except (OSError, ValueError):
                print("Fused data missing.")

        # check and validate cellpose segmentation
        if self._datastore_state["SegmentedCells"] and validate:
            current_local_zarr_path = str(
                self._segmentation_root_path
                / Path("cellpose")
                / Path(f"masks_{self.fiducial_folder_name}_iso_zyx")
            )

            try:
                self._check_for_zarr_array(current_local_zarr_path)
            except (OSError, ValueError):
                print("Cellpose data missing.")

            cell_outlines_path = (
                self._segmentation_root_path
                / Path("cellpose")
                / Path("imagej_rois")
                / Path("global_coords_rois.zip")
            )
            if not (cell_outlines_path.exists()):
                raise FileNotFoundError("Cellpose cell outlines missing.")

        # check and validate decoded spots
        if self._datastore_state["DecodedSpots"] and validate:
            for tile_id in self._tile_ids:
                decoded_path = self._decoded_root_path / Path(
                    tile_id + "_decoded_features.parquet"
                )

                if not (decoded_path.exists()):
                    raise FileNotFoundError(tile_id + " decoded spots missing.")

        # check and validate filtered decoded spots
        if self._datastore_state["FilteredSpots"] and validate:
            filtered_path = self._decoded_root_path / Path(
                "all_tiles_filtered_decoded_features.parquet"
            )

            if not (filtered_path.exists()):
                raise FileNotFoundError("filtered decoded spots missing.")

    def load_codebook_parsed(
        self,
    ) -> tuple[Collection[str], ArrayLike] | None:
        """Load and split codebook into gene_ids and codebook matrix.

        Returns
        -------
        gene_ids : Collection[str]
            Gene IDs.
        codebook_matrix : ArrayLike
            Codebook matrix.
        """
        try:
            data = getattr(self, "_codebook", None)

            if data is None:
                return None
            num_columns = len(data[0]) if data else 0
            columns = ["gene_id"] + [f"bit{i:02d}" for i in range(1, num_columns)]
            codebook_df = pd.DataFrame(data, columns=columns)

            gene_ids = codebook_df.iloc[:, 0].tolist()
            codebook_matrix = codebook_df.iloc[:, 1:].to_numpy().astype(int)
            del data, codebook_df
            return gene_ids, codebook_matrix
        except (KeyError, ValueError, TypeError):
            print("Error parsing codebook.")
            return None

    def initialize_tile(
        self,
        tile: int | str,
    ) -> None:
        """Initialize directory structure for a tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        """
        if getattr(self, "_experiment_order", None) is None:
            print("Assign experimental order before creating tiles.")
            return None

        if getattr(self, "_num_tiles", None) is None:
            print("Assign number of tiles before creating tiles.")
            return None

        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tile id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        try:
            fiducial_tile_path = self._fiducial_root_path / Path(tile_id)
            fiducial_tile_path.mkdir()
            for round_idx, round_id in enumerate(self._round_ids):
                fiducial_round_path = fiducial_tile_path / Path(round_id)
                fiducial_round_path.mkdir()
                fiducial_round_attrs_path = self._entity_attributes_path(
                    fiducial_round_path
                )
                round_attrs = {
                    "bit_linker": self._experiment_order.to_numpy()[round_idx, 1:]
                    .astype(int)
                    .tolist(),
                }
                self._save_to_json(round_attrs, fiducial_round_attrs_path)
        except FileExistsError:
            print("Error creating fiducial tile. Does it exist already?")

        try:
            readout_tile_path = self._readouts_root_path / Path(tile_id)
            readout_tile_path.mkdir()
            for bit_idx, bit_id in enumerate(self._bit_ids):
                readout_bit_path = readout_tile_path / Path(bit_id)
                readout_bit_path.mkdir()
                readout_bit_attrs_path = self._entity_attributes_path(readout_bit_path)
                fiducial_channel = str(self._channels_in_data[0])
                readout_one_channel = str(self._channels_in_data[1])

                if len(self._channels_in_data) == 3:
                    readout_two_channel = str(self._channels_in_data[2])
                    condition_one = self._experiment_order[readout_one_channel] == (
                        bit_idx + 1
                    )
                    condition_two = self._experiment_order[readout_two_channel] == (
                        bit_idx + 1
                    )
                    combined_condition = condition_one | condition_two

                else:
                    combined_condition = self._experiment_order[
                        readout_one_channel
                    ] == (bit_idx + 1)
                matching_rows = self._experiment_order.loc[combined_condition]

                bit_attrs = {
                    "round_linker": int(matching_rows[fiducial_channel].values[0])
                }
                self._save_to_json(bit_attrs, readout_bit_attrs_path)
        except FileExistsError:
            print("Error creating readout tile. Does it exist already?")

    def load_local_bit_linker(
        self,
        tile: int | str,
        round: int | str,
    ) -> Sequence[int] | None:
        """Load readout bits linked to fiducial round for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.

        Returns
        -------
        bit_linker : Sequence[int] or None
            Readout bits linked to fiducial round for one tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id.")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            attributes = self._load_entity_attributes(entity_root)
            bit_linker = attributes.get("bit_linker")
            if bit_linker is None:
                print(tile_id, round_id)
                print("Bit linker attribute not found.")
                return None
            return [int(v) for v in list(bit_linker)]
        except (TypeError, ValueError):
            print(tile_id, round_id)
            print("Bit linker attribute not found.")
            return None

    def save_local_bit_linker(
        self,
        bit_linker: Sequence[int],
        tile: int | str,
        round: int | str,
    ) -> None:
        """Save readout bits linked to fiducial round for one tile.

        Parameters
        ----------
        bit_linker : Sequence[int]
            Readout bits linked to fiducial round for one tile.
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id.")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            values = [int(v) for v in list(bit_linker)]
            self._save_entity_attributes(
                entity_root_path=entity_root, updates={"bit_linker": values}
            )
        except (TypeError, ValueError):
            print(tile_id, round_id)
            print("Error writing bit linker attribute.")
            return None

    def load_local_round_linker(
        self,
        tile: int | str,
        bit: int | str,
    ) -> Sequence[int] | None:
        """Load fiducial round linked to readout bit for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.

        Returns
        -------
        round_linker : Sequence[int] or None
            Fiducial round linked to readout bit for one tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id.")
                return None
            else:
                bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        try:
            entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
            attributes = self._load_entity_attributes(entity_root)
            round_linker = attributes.get("round_linker")
            if round_linker is None:
                print(tile_id, bit_id)
                print("Round linker attribute not found.")
                return None
            return int(round_linker)
        except (TypeError, ValueError):
            print(tile_id, bit_id)
            print("Round linker attribute not found.")
            return None

    def save_local_round_linker(
        self,
        round_linker: int,
        tile: int | str,
        bit: int | str,
    ) -> None:
        """Save fiducial round linker attribute to readout bit for one tile.

        Parameters
        ----------
        round_linker : int
            Fiducial round linked to readout bit for one tile.
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id.")
                return None
            else:
                bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        try:
            entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
            self._save_entity_attributes(
                entity_root_path=entity_root,
                updates={"round_linker": int(round_linker)},
            )
        except (TypeError, ValueError):
            print(tile_id, bit_id)
            print("Error writing round linker attribute.")
            return None

    def load_local_stage_position_zyx_um(
        self,
        tile: int | str,
        round: int | str,
    ) -> tuple[np.ndarray, np.ndarray] | None:
        """Load tile stage position for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.

        Returns
        -------
        stage_zyx_um : ArrayLike or None
            Tile stage position in Z, Y, X microns. Legacy two-coordinate Y, X
            metadata is returned with Z=0 without modifying the stored data.
        affine_zyx_um: ArrayLike or None
            Affine transformation between stage and camera
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id.")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            attributes = self._load_entity_attributes(entity_root)
            stage_zyx_um = attributes.get("stage_zyx_um")
            affine_zyx_px = attributes.get("affine_zyx_px")
            if stage_zyx_um is None or affine_zyx_px is None:
                print(tile_id, round_id)
                print("Stage position attribute not found.")
                return None
            return self._normalize_stage_position_zyx_um(stage_zyx_um), np.asarray(
                affine_zyx_px, dtype=np.float32
            )
        except (TypeError, ValueError):
            print(tile_id, round_id)
            print("Stage position attribute not found.")
            return None

    def save_local_stage_position_zyx_um(
        self,
        stage_zyx_um: ArrayLike,
        affine_zyx_px: ArrayLike,
        tile: int | str,
        round: int | str,
    ) -> None:
        """Save tile stage position for one tile.

        Parameters
        ----------
        stage_zyx_um : ArrayLike
            Tile stage position in Z, Y, X microns. Two-coordinate Y, X input
            is accepted and stored as Z, Y, X with Z=0.
        affine_zyx_px: ArrayLike
            4x4 homogeneous affine matrix for stage transformation
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id.")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id.")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            stage_zyx_um = self._normalize_stage_position_zyx_um(stage_zyx_um)
            self._save_entity_attributes(
                entity_root_path=entity_root,
                updates={
                    "stage_zyx_um": stage_zyx_um.tolist(),
                    "affine_zyx_px": np.asarray(
                        affine_zyx_px, dtype=np.float32
                    ).tolist(),
                },
            )
            self._update_image_translation_transform(
                entity_root / Path("corrected_data"), stage_zyx_um
            )
        except (TypeError, ValueError):
            print(tile_id, round_id)
            print("Error writing stage position attribute.")
            return None

    def load_local_wavelengths_um(
        self,
        tile: int | str,
        round: int | str | None = None,
        bit: int | str | None = None,
    ) -> tuple[float, float] | None:
        """Load wavelengths for fiducial OR readout bit for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str or None
            Round index or round id.
        bit : int or str or None
            Bit index or bit id.

        Returns
        -------
        wavelengths_um : tuple[float, float] or None
            Wavelengths for fiducial OR readout bit for one tile.
        """
        if (round is None and bit is None) or (round is not None and bit is not None):
            print("Provide either 'round' or 'bit', but not both")
            return None

        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if bit is not None:
            if isinstance(bit, int):
                if bit < 0 or bit >= len(self._bit_ids):
                    print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                    return None
                else:
                    local_id = self._bit_ids[bit]
            elif isinstance(bit, str):
                if bit not in self._bit_ids:
                    print("Set valid bit id")
                    return None
                else:
                    local_id = bit
            else:
                print("'bit' must be integer index or string identifier")
                return None
            entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
        else:
            if isinstance(round, int):
                if round < 0 or round >= len(self._round_ids):
                    print("Set round index >=0 and <" + str(self._num_rounds))
                    return None
                else:
                    local_id = self._round_ids[round]
            elif isinstance(round, str):
                if round not in self._round_ids:
                    print("Set valid round id")
                    return None
                else:
                    local_id = round
            else:
                print("'round' must be integer index or string identifier")
                return None
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)

        try:
            attributes = self._load_entity_attributes(entity_root)
            ex_wavelength_um = attributes["excitation_um"]
            em_wavelength_um = attributes["emission_um"]
            return (ex_wavelength_um, em_wavelength_um)
        except KeyError:
            print("Wavelength attributes not found.")
            return None

    def save_local_wavelengths_um(
        self,
        wavelengths_um: tuple[float, float],
        tile: int | str,
        round: int | str | None = None,
        bit: int | str | None = None,
    ) -> tuple[float, float] | None:
        """Save wavelengths for fiducial OR readout bit for one tile.

        Parameters
        ----------
        wavelengths_um : tuple[float, float]
            Wavelengths for fiducial OR readout bit for one tile.
        tile : int or str
            Tile index or tile id.
        round : int or str or None
            Round index or round id.
        bit : int or str or None
            Bit index or bit id.

        Returns
        -------
        wavelengths_um : tuple[float, float] or None
            Wavelengths for fiducial OR readout bit for one tile.
        """
        if (round is None and bit is None) or (round is not None and bit is not None):
            print("Provide either 'round' or 'bit', but not both")
            return None

        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if bit is not None:
            if isinstance(bit, int):
                if bit < 0 or bit >= len(self._bit_ids):
                    print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                    return None
                else:
                    local_id = self._bit_ids[bit]
            elif isinstance(bit, str):
                if bit not in self._bit_ids:
                    print("Set valid bit id")
                    return None
                else:
                    local_id = bit
            else:
                print("'bit' must be integer index or string identifier")
                return None
            entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
        else:
            if isinstance(round, int):
                if round < 0 or round >= len(self._round_ids):
                    print("Set round index >=0 and <" + str(self._num_rounds))
                    return None
                else:
                    local_id = self._round_ids[round]
            elif isinstance(round, str):
                if round not in self._round_ids:
                    print("Set valid round id")
                    return None
                else:
                    local_id = round
            else:
                print("'round' must be integer index or string identifier")
                return None
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)

        try:
            self._save_entity_attributes(
                entity_root_path=entity_root,
                updates={
                    "excitation_um": float(wavelengths_um[0]),
                    "emission_um": float(wavelengths_um[1]),
                },
            )
        except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
            print("Error writing wavelength attributes.")
            return None

    def load_local_corrected_image(
        self,
        tile: int | str,
        round: int | str | None = None,
        bit: int | str | None = None,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load gain and offset corrected image for fiducial OR readout bit for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str or None
            Round index or round id.
        bit : int or str or None
            Bit index or bit id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        corrected_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Gain and offset corrected image for fiducial OR readout bit for one tile.
        """
        if (round is None and bit is None) or (round is not None and bit is not None):
            print("Provide either 'round' or 'bit', but not both")
            return None

        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if bit is not None:
            if isinstance(bit, int):
                if bit < 0 or bit >= len(self._bit_ids):
                    print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                    return None
                else:
                    local_id = self._bit_ids[bit]
            elif isinstance(bit, str):
                if bit not in self._bit_ids:
                    print("Set valid bit id")
                    return None
                else:
                    local_id = bit
            else:
                print("'bit' must be integer index or string identifier")
                return None
            current_local_zarr_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(local_id)
                / Path("corrected_data")
            )
        else:
            if isinstance(round, int):
                if round < 0 or round >= len(self._round_ids):
                    print("Set round index >=0 and <" + str(self._num_rounds))
                    return None
                else:
                    local_id = self._round_ids[round]
            elif isinstance(round, str):
                if round not in self._round_ids:
                    print("Set valid round id")
                    return None
                else:
                    local_id = round
            else:
                print("'round' must be integer index or string identifier")
                return None
            current_local_zarr_path = str(
                self._fiducial_root_path
                / Path(tile_id)
                / Path(local_id)
                / Path("corrected_data")
            )

        image_path = self._image_store_path(current_local_zarr_path)
        if not image_path.exists():
            print("Corrected image not found.")
            return None

        try:
            corrected_image = self._load_from_zarr_array(image_path, return_future)
            return corrected_image
        except (OSError, ValueError):
            print("Error loading corrected image.")
            return None

    def save_local_corrected_image(
        self,
        image: ArrayLike,
        tile: int | str,
        gain_correction: bool = True,
        hotpixel_correction: bool = True,
        shading_correction: bool = False,
        psf_idx: int = 0,
        round: int | str | None = None,
        bit: int | str | None = None,
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """Save gain and offset corrected image.

        Parameters
        ----------
        image : ArrayLike
            Local corrected image.
        tile : int or str
            Tile index or tile id.
        gain_correction : bool
            Gain correction applied (True) or not (False).
        hotpixel_correction : bool
            Hotpixel correction applied (True) or not (False).
        shading_correction : bool
            Shading correction applied (True) or not (False).
        psf_idx : int
            PSF index.
        round : int or str or None
            Round index or round id.
        bit : int or str or None
            Bit index or bit id.
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None. Invalid tile/round/bit selections also return None.
        """
        if (round is None and bit is None) or (round is not None and bit is not None):
            print("Provide either 'round' or 'bit', but not both")
            return None

        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if bit is not None:
            if isinstance(bit, int):
                if bit < 0 or bit >= len(self._bit_ids):
                    print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                    return None
                else:
                    local_id = self._bit_ids[bit]
            elif isinstance(bit, str):
                if bit not in self._bit_ids:
                    print("Set valid bit id")
                    return None
                else:
                    local_id = bit
            else:
                print("'bit' must be integer index or string identifier")
                return None
            entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
            current_local_zarr_path = entity_root / Path("corrected_data")
            stage_position = self._resolve_original_tile_position_zyx_um(
                tile_id=tile_id, bit_id=local_id
            )
        else:
            if isinstance(round, int):
                if round < 0 or round >= len(self._round_ids):
                    print("Set round index >=0 and <" + str(self._num_rounds))
                    return None
                else:
                    local_id = self._round_ids[round]
            elif isinstance(round, str):
                if round not in self._round_ids:
                    print("Set valid round id")
                    return None
                else:
                    local_id = round
            else:
                print("'round' must be integer index or string identifier")
                return None
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)
            current_local_zarr_path = entity_root / Path("corrected_data")
            stage_position = self._resolve_original_tile_position_zyx_um(
                tile_id=tile_id, round_id=local_id
            )

        try:
            self._validate_core_image_shape(
                entity_root_path=entity_root, image_name="corrected_data", image=image
            )
            attributes = self._load_entity_attributes(entity_root)
            attributes.update(
                {
                    "gain_correction": bool(gain_correction),
                    "hotpixel_correction": bool(hotpixel_correction),
                    "shading_correction": bool(shading_correction),
                    "psf_idx": int(psf_idx),
                }
            )
            write_future = self._save_to_zarr_array(
                image,
                current_local_zarr_path,
                return_future,
                ome_scale=self.voxel_size_zyx_um,
                ome_translation=stage_position,
                extra_attributes=attributes,
            )
            if write_future is not None:
                write_future.result()
            self._save_entity_attributes(
                entity_root_path=entity_root, updates=attributes
            )
            return write_future
        except (OSError, TimeoutError, ValueError) as e:
            print(e)
            print("Error saving corrected image.")
            raise

    def load_local_rigid_xform_xyz_px(
        self,
        tile: int | str,
        round: int | str,
    ) -> ArrayLike | None:
        """Load calculated rigid registration transform for one round and tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.

        Returns
        -------
        rigid_xform_xyz_px : ArrayLike or None
            Local rigid registration transform for one round and tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            attributes = self._load_entity_attributes(entity_root)
            rigid_xform_xyz_px = np.asarray(
                attributes["rigid_xform_xyz_px"], dtype=np.float32
            )
            return rigid_xform_xyz_px
        except (FileNotFoundError, json.JSONDecodeError, KeyError):
            print(tile_id, round_id)
            print("Rigid transform mapping back to first round not found.")
            return None

    def save_local_rigid_xform_xyz_px(
        self,
        rigid_xform_xyz_px: ArrayLike,
        tile: int | str,
        round: int | str,
    ) -> ArrayLike | None:
        """Save calculated rigid registration transform for one round and tile.

        Parameters
        ----------
        rigid_xform_xyz_px : ArrayLike
            Local rigid registration transform for one round and tile.
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.

        Returns
        -------
        rigid_xform_xyz_px : ArrayLike or None
            Local rigid registration transform for one round and tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            self._save_entity_attributes(
                entity_root_path=entity_root,
                updates={
                    "rigid_xform_xyz_px": np.asarray(
                        rigid_xform_xyz_px, dtype=np.float32
                    ).tolist()
                },
            )
        except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
            print("Error writing rigid transform attribute.")
            return None

    def load_local_round_transform_zyx_um(
        self,
        tile: int | str,
        round: int | str,
    ) -> ArrayLike | None:
        """
        Load the local fiducial round transform for one tile.

        Parameters
        ----------
        tile : int | str
            Tile index or tile identifier.
        round : int | str
            Fiducial round index or round identifier.

        Returns
        -------
        ArrayLike or None
            Homogeneous 4x4 affine transform in physical Z, Y, X microns. The
            transform maps first-round reference coordinates to coordinates in
            the requested moving round. Returns None when the transform is not
            present.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            attributes = self._load_entity_attributes(entity_root)
            return np.asarray(
                attributes["local_round_transform_zyx_um"], dtype=np.float32
            )
        except (FileNotFoundError, json.JSONDecodeError, KeyError):
            print(tile_id, round_id)
            print("Local round transform mapping back to first round not found.")
            return None

    def save_local_round_transform_zyx_um(
        self,
        transform_zyx_um: ArrayLike,
        tile: int | str,
        round: int | str,
    ) -> None:
        """
        Save the local fiducial round transform for one tile.

        Parameters
        ----------
        transform_zyx_um : ArrayLike
            Homogeneous 4x4 affine transform in physical Z, Y, X microns. The
            transform maps first-round reference coordinates to coordinates in
            the requested moving round.
        tile : int | str
            Tile index or tile identifier.
        round : int | str
            Fiducial round index or round identifier.

        Returns
        -------
        None
            The transform is stored in the entity attributes for the requested
            fiducial tile and round.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        try:
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            self._save_entity_attributes(
                entity_root_path=entity_root,
                updates={
                    "local_round_transform_zyx_um": np.asarray(
                        transform_zyx_um, dtype=np.float32
                    ).tolist()
                },
            )
        except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
            print("Error writing local round transform attribute.")
            return None

    def load_coord_of_xform_px(
        self,
        tile: int | str | None,
        round: int | str | None,
        return_future: bool | None = True,
    ) -> "tuple[np.ndarray | Future | TensorStore, np.ndarray, np.ndarray] | None":
        """Local fiducial optical flow matrix for one round and tile.

        Parameters
        ----------
        tile : int or str or None
            Tile index or tile id.
        round : int or str or None
            Round index or round id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        of_xform_px : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore
            Local fiducial optical flow matrix for one round and tile.
        block_size : numpy.ndarray
            Block size used for the pixel warp.
        block_stride : numpy.ndarray
            Block stride used for the pixel warp.

        Returns None when the image or required metadata is unavailable.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        current_local_zarr_path = entity_root / Path("opticalflow_xform_px")

        image_path = self._image_store_path(current_local_zarr_path)
        if not image_path.exists():
            print("Optical flow transform mapping back to first round not found.")
            return None

        try:
            of_xform_px = self._load_from_zarr_array(image_path, return_future)
            attributes = self._load_entity_attributes(
                entity_root, image_names=("opticalflow_xform_px",)
            )
            block_size = np.asarray(attributes["block_size"], dtype=np.float32)
            block_stride = np.asarray(attributes["block_stride"], dtype=np.float32)

            return (of_xform_px, block_size, block_stride)
        except (OSError, ValueError, KeyError) as e:
            print(e)
            print("Error loading optical flow transform.")
            return None

    def save_coord_of_xform_px(
        self,
        of_xform_px: ArrayLike,
        tile: int | str,
        block_size: Sequence[float],
        block_stride: Sequence[float],
        round: int | str,
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """Save fiducial optical flow matrix for one round and tile.

        Parameters
        ----------
        of_xform_px : ArrayLike
            Local fiducial optical flow matrix for one round and tile.
        tile : int or str
            Tile index or tile id.
        block_size : Sequence[float]
            Block size for pixel warp
        block_stride: Sequence[float]
            Block stride for pixel warp
        round : int or str
            Round index or round id.
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None. Invalid tile/round/bit selections also return None.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                local_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                local_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)
        current_local_zarr_path = entity_root / Path("opticalflow_xform_px")

        try:
            opticalflow_attrs = {
                "block_size": np.asarray(block_size, dtype=np.float32).tolist(),
                "block_stride": np.asarray(block_stride, dtype=np.float32).tolist(),
            }
            # Optical flow is a dense pixel-space field, so we do not encode
            # physical voxel scale or stage translation transforms here.
            write_future = self._save_to_zarr_array(
                of_xform_px,
                current_local_zarr_path,
                return_future,
                extra_attributes=opticalflow_attrs,
            )
            if write_future is not None:
                write_future.result()
            self._save_entity_attributes(
                entity_root_path=entity_root, updates=opticalflow_attrs
            )
            return write_future
        except (OSError, TimeoutError):
            print("Error saving optical flow transform.")
            raise

    def load_local_sofima_flow_field(
        self,
        *,
        tile: int | str,
        round: int | str,
        return_future: bool | None = True,
    ) -> "tuple[np.ndarray | Future | TensorStore, dict] | None":
        """
        Load the SOFIMA flow field for one local fiducial round.

        Parameters
        ----------
        tile : int or str
            Tile index or tile identifier.
        round : int or str
            Moving fiducial round index or identifier.
        return_future : bool or None, default=True
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        tuple[numpy.ndarray or tensorstore.Future or tensorstore.TensorStore, dict] or None
            SOFIMA flow field and metadata attributes. The map channels are X,
            Y, Z and spatial axes are Z, Y, X. ``map_stride_zyx_px`` is stored
            in Z, Y, X order. ``map_box_start_xyz_px`` is stored in X, Y, Z
            order and gives the reference-grid coordinate of the first flow
            sample. For fields produced by SOFIMA this is the patch center
            coordinate, not the image corner.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        image_name = "local_sofima_flow_field"
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        current_local_zarr_path = entity_root / Path(image_name)
        image_path = self._image_store_path(current_local_zarr_path)
        if not image_path.exists():
            print("SOFIMA flow field not found.")
            return None

        try:
            sofima_flow_field = self._load_from_zarr_array(image_path, return_future)
            attributes = self._load_entity_attributes(
                entity_root,
                image_names=(image_name,),
            )
            return sofima_flow_field, attributes
        except (OSError, ValueError, KeyError) as e:
            print(e)
            print("Error loading SOFIMA flow field.")
            return None

    def save_local_sofima_flow_field(
        self,
        sofima_flow_field_xyz_px: ArrayLike,
        *,
        tile: int | str,
        round: int | str,
        reference_round: int | str,
        map_stride_zyx_px: Sequence[float],
        map_box_start_xyz_px: Sequence[float],
        map_box_size_xyz_px: Sequence[float],
        reference_shape_zyx_px: Sequence[int],
        moving_shape_zyx_px: Sequence[int],
        sofima_status: str = "ok",
        valid_flow_vectors: int | None = None,
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """
        Save the SOFIMA flow field for one local fiducial round.

        The saved OME-Zarr image stores the raw float32 SOFIMA map exactly as
        used in memory. The package convention is channel-first ``(3, z, y,
        x)`` with channels ``X, Y, Z`` and spatial axes ``Z, Y, X``. Flow
        values are relative displacements in reference-image pixels from a
        reference coordinate to the affine-initialized moving coordinate.
        ``map_box_start_xyz_px`` is the reference coordinate of the first flow
        sample in ``X, Y, Z`` order. SOFIMA patch-correlation vectors are
        patch-centered, so this is normally half the patch size.

        Parameters
        ----------
        sofima_flow_field_xyz_px : ArrayLike
            Relative SOFIMA flow field with channels X, Y, Z and spatial axes
            Z, Y, X.
        tile : int or str
            Tile index or tile identifier.
        round : int or str
            Moving fiducial round index or identifier.
        reference_round : int or str
            Reference fiducial round index or identifier.
        map_stride_zyx_px : Sequence[float]
            Flow-field stride in reference pixels in Z, Y, X order.
        map_box_start_xyz_px : Sequence[float]
            Reference pixel coordinate of the first flow sample in X, Y, Z
            order.
        map_box_size_xyz_px : Sequence[float]
            Flow-field sample-lattice extent in X, Y, Z order, measured from
            ``map_box_start_xyz_px`` through the last stored map sample.
        reference_shape_zyx_px : Sequence[int]
            Reference image shape in Z, Y, X order.
        moving_shape_zyx_px : Sequence[int]
            Moving native image shape in Z, Y, X order.
        sofima_status : str, default="ok"
            Status reported by the SOFIMA estimator.
        valid_flow_vectors : int or None, default=None
            Number of valid local vectors before missing-vector fill.
        return_future : bool or None, default=False
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None. Invalid tile or round selections also return None.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        if isinstance(reference_round, int):
            if reference_round < 0 or reference_round >= len(self._round_ids):
                print("Set reference round index >=0 and <" + str(len(self._round_ids)))
                return None
            reference_round_id = self._round_ids[reference_round]
        elif isinstance(reference_round, str):
            if reference_round not in self._round_ids:
                print("Set valid reference round id")
                return None
            reference_round_id = reference_round
        else:
            print("'reference_round' must be integer index or string identifier")
            return None

        image_name = "local_sofima_flow_field"
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        current_local_zarr_path = entity_root / Path(image_name)
        attributes = {
            "registration_backend": "sofima",
            "initial_registration_source": "stored_local_affine_transform",
            "flow_field_name": image_name,
            "flow_direction": (
                f"{reference_round_id}_reference_xyz_px_to_affine_initialized_"
                f"{round_id}_xyz_px"
            ),
            "final_render_direction": (
                f"{reference_round_id}_reference_xyz_px_to_moving_native_xyz_px"
            ),
            "flow_representation": "sofima_relative_coordinate_map",
            "flow_channel_order": "xyz",
            "flow_spatial_order": "zyx",
            "map_stride_zyx_px": np.asarray(
                map_stride_zyx_px, dtype=np.float32
            ).tolist(),
            "map_box_start_xyz_px": np.asarray(
                map_box_start_xyz_px, dtype=np.float32
            ).tolist(),
            "map_box_size_xyz_px": np.asarray(
                map_box_size_xyz_px, dtype=np.float32
            ).tolist(),
            "reference_shape_zyx_px": np.asarray(
                reference_shape_zyx_px, dtype=np.int64
            ).tolist(),
            "moving_shape_zyx_px": np.asarray(
                moving_shape_zyx_px, dtype=np.int64
            ).tolist(),
            "sofima_status": str(sofima_status),
            "interpolation_count_final_image": 1,
        }
        if valid_flow_vectors is not None:
            attributes["valid_flow_vectors"] = int(valid_flow_vectors)

        try:
            write_future = self._save_to_zarr_array(
                np.asarray(sofima_flow_field_xyz_px, dtype=np.float32),
                current_local_zarr_path,
                return_future,
                ome_scale=self.voxel_size_zyx_um,
                extra_attributes=attributes,
            )
            if write_future is not None:
                write_future.result()
            self._save_entity_attributes(
                entity_root_path=entity_root, updates=attributes
            )
            return write_future
        except (OSError, TimeoutError):
            print("Error saving SOFIMA flow field.")
            raise

    def load_local_deconvolved_fiducial_image(
        self,
        tile: int | str,
        round: int | str,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load a native-frame deconvolved fiducial image.

        Deconvolved fiducials are loaded from ``decon_data`` in their native,
        unwarped tile frame. This image exists only when fiducial deconvolution
        was run during preprocessing.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Native-frame deconvolved fiducial image.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        decon_path = self._fiducial_root_path / tile_id / round_id / Path("decon_data")
        image_path = self._image_store_path(decon_path)
        if not image_path.exists():
            return None

        try:
            return self._load_from_zarr_array(image_path, return_future)
        except (OSError, ValueError) as e:
            print(e)
            print("Error loading local deconvolved fiducial image.")
            return None

    def load_local_fiducial_image(
        self,
        tile: int | str,
        round: int | str,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load the best available native-frame fiducial image.

        Deconvolved fiducial data are returned when ``decon_data`` exists;
        otherwise corrected fiducial data are returned.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Deconvolved fiducial image if available, otherwise corrected image.
        """
        image = self.load_local_deconvolved_fiducial_image(
            tile=tile,
            round=round,
            return_future=return_future,
        )
        if image is not None:
            return image
        return self.load_local_corrected_image(
            tile=tile,
            round=round,
            return_future=return_future,
        )

    def save_local_deconvolved_fiducial_image(
        self,
        image: ArrayLike,
        tile: int | str,
        round: int | str,
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """
        Save a native-frame deconvolved fiducial image.

        Deconvolved fiducials are saved under ``decon_data`` in their native,
        unwarped tile frame.

        Parameters
        ----------
        image : ArrayLike
            Image to save.
        tile : int or str
            Tile index or tile id.
        round : int or str
            Round index or round id.
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None. Invalid tile/round/bit selections also return None.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            round_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            round_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None

        entity_root = self._fiducial_root_path / tile_id / round_id
        decon_path = entity_root / Path("decon_data")
        stage_position = self._resolve_reference_tile_position_zyx_um(tile_id)

        try:
            self._validate_core_image_shape(
                entity_root_path=entity_root,
                image_name="decon_data",
                image=image,
            )
            attributes = self._load_entity_attributes(entity_root)
            attributes["deconvolution"] = True
            write_future = self._save_to_zarr_array(
                image,
                decon_path,
                return_future,
                ome_scale=self.voxel_size_zyx_um,
                ome_translation=stage_position,
                extra_attributes=attributes,
            )
            if write_future is not None:
                write_future.result()
            self._save_entity_attributes(
                entity_root_path=entity_root, updates=attributes
            )
            return write_future
        except (OSError, TimeoutError, ValueError):
            print("Error saving local deconvolved fiducial image.")
            raise

    def load_local_deconvolved_readout_image(
        self,
        tile: int | str,
        bit: int | str,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load a native-frame deconvolved readout bit image.

        Deconvolved readout bits are loaded from ``decon_data`` in their
        native, unwarped tile frame. This image exists only when readout
        deconvolution was run during preprocessing.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Native-frame deconvolved readout image.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        readout_path = (
            self._readouts_root_path / Path(tile_id) / Path(bit_id) / Path("decon_data")
        )
        image_path = self._image_store_path(readout_path)
        if not image_path.exists():
            return None

        try:
            return self._load_from_zarr_array(image_path, return_future)
        except (OSError, ValueError) as e:
            print(e)
            print("Error loading local deconvolved readout image.")
            return None

    def load_local_readout_image(
        self,
        tile: int | str,
        bit: int | str,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load the best available native-frame readout bit image.

        Deconvolved readout data are returned when ``decon_data`` exists;
        otherwise corrected readout data are returned.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Deconvolved readout image if available, otherwise corrected image.
        """
        image = self.load_local_deconvolved_readout_image(
            tile=tile,
            bit=bit,
            return_future=return_future,
        )
        if image is not None:
            return image
        return self.load_local_corrected_image(
            tile=tile,
            bit=bit,
            return_future=return_future,
        )

    def save_local_deconvolved_readout_image(
        self,
        image: ArrayLike,
        tile: int | str,
        bit: int | str,
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """
        Save a native-frame deconvolved readout bit image.

        Deconvolved readout bits are saved under ``decon_data`` in their
        native, unwarped tile frame.

        Parameters
        ----------
        image : ArrayLike
            Image to save.
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None. Invalid tile/round/bit selections also return None.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
        readout_path = entity_root / Path("decon_data")
        stage_position = self._resolve_original_tile_position_zyx_um(
            tile_id=tile_id,
            bit_id=bit_id,
        )

        try:
            self._validate_core_image_shape(
                entity_root_path=entity_root,
                image_name="decon_data",
                image=image,
            )
            attributes = self._load_entity_attributes(entity_root)
            attributes["deconvolution"] = True
            write_future = self._save_to_zarr_array(
                image,
                readout_path,
                return_future,
                ome_scale=self.voxel_size_zyx_um,
                ome_translation=stage_position,
                extra_attributes=attributes,
            )
            if write_future is not None:
                write_future.result()
            self._save_entity_attributes(
                entity_root_path=entity_root, updates=attributes
            )
            return write_future
        except (OSError, TimeoutError, ValueError):
            print("Error saving local deconvolved readout image.")
            raise

    def load_local_feature_predictor_image(
        self,
        tile: int | str,
        bit: int | str,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load readout bit feature_predictor prediction image for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        feature_predictor_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            feature_predictor prediction image for one tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        current_local_zarr_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(bit_id)
            / Path(f"{self.feature_predictor_folder_name}_data")
        )

        image_path = self._image_store_path(current_local_zarr_path)
        if not image_path.exists():
            print("feature_predictor prediction image not found.")
            return None

        try:
            feature_predictor_image = self._load_from_zarr_array(
                image_path, return_future
            )
            return feature_predictor_image
        except (OSError, ValueError) as e:
            print(e)
            print("Error loading feature_predictor image.")
            return None

    def save_local_feature_predictor_image(
        self,
        feature_predictor_image: ArrayLike,
        tile: int | str,
        bit: int | str,
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """Save feature_predictor prediction image.

        Parameters
        ----------
        feature_predictor_image : ArrayLike
            feature_predictor prediction image.
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None. Invalid tile/round/bit selections also return None.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                local_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                local_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None
        entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
        current_local_zarr_path = entity_root / Path(
            f"{self.feature_predictor_folder_name}_data"
        )

        try:
            self._validate_core_image_shape(
                entity_root_path=entity_root,
                image_name=f"{self.feature_predictor_folder_name}_data",
                image=feature_predictor_image,
            )
            stage_position = self._resolve_original_tile_position_zyx_um(
                tile_id=tile_id, bit_id=local_id
            )
            attributes = self._load_entity_attributes(entity_root)
            write_future = self._save_to_zarr_array(
                feature_predictor_image,
                current_local_zarr_path,
                return_future,
                ome_scale=self.voxel_size_zyx_um,
                ome_translation=stage_position,
                extra_attributes=attributes,
            )
            if write_future is not None:
                write_future.result()
            self._save_entity_attributes(
                entity_root_path=entity_root, updates=attributes
            )
            return write_future
        except (OSError, ValueError) as e:
            print(e)
            print("Error saving feature_predictor image.")
            raise

    def load_local_feature_predictor_spots(
        self,
        tile: int | str,
        bit: int | str,
    ) -> pd.DataFrame | None:
        """Load feature_predictor spot localizations and features for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.

        Returns
        -------
        feature_predictor_localizations : pandas.DataFrame or None
            feature_predictor localizations and features for one tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        current_feature_predictor_localizations_path = (
            self._feature_predictor_localizations_root_path
            / Path(tile_id)
            / Path(bit_id + ".parquet")
        )

        if not current_feature_predictor_localizations_path.exists():
            print("feature_predictor localizations not found.")
            return None
        else:
            feature_predictor_localizations = self._load_from_parquet(
                current_feature_predictor_localizations_path
            )
            return feature_predictor_localizations

    def save_local_feature_predictor_spots(
        self,
        spot_df: pd.DataFrame,
        tile: int | str,
        bit: int | str,
    ) -> None:
        """Save feature_predictor localizations and features.

        Parameters
        ----------
        spot_df : pd.DataFrame
            feature_predictor localizations and features.
        tile : int or str
            Tile index or tile id.
        bit : int or str
            Bit index or bit id.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                bit_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                bit_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None

        tile_localizations_path = (
            self._feature_predictor_localizations_root_path / Path(tile_id)
        )
        tile_localizations_path.mkdir(parents=True, exist_ok=True)

        current_feature_predictor_localizations_path = tile_localizations_path / Path(
            bit_id + ".parquet"
        )

        try:
            self._save_to_parquet(spot_df, current_feature_predictor_localizations_path)
        except OSError as e:
            print(e)
            print("Error saving feature_predictor localizations.")
            return None

    def load_global_coord_xforms_um(
        self,
        tile: int | str,
    ) -> tuple[ArrayLike | None, ArrayLike | None, ArrayLike | None] | None:
        """Load global registration transform for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.

        Returns
        -------
        affine_zyx_um : ArrayLike or None
            Global affine registration transform for one tile.
        origin_zyx_um : ArrayLike or None
            Global origin registration transform for one tile.
        spacing_zyx_um : ArrayLike or None
            Global spacing registration transform for one tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None, None, None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None, None, None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        try:
            entity_root = (
                self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
            )
            attributes = self._load_entity_attributes(entity_root)
            affine_zyx_um = np.asarray(attributes["affine_zyx_um"], dtype=np.float32)
            origin_zyx_um = np.asarray(attributes["origin_zyx_um"], dtype=np.float32)
            spacing_zyx_um = round_spacing_um(attributes["spacing_zyx_um"])
            return (affine_zyx_um, origin_zyx_um, spacing_zyx_um)
        except (FileNotFoundError, json.JSONDecodeError, KeyError):
            print(tile_id, self._round_ids[0])
            print("Global coordinate transforms not found")
            return None, None, None

    def save_global_coord_xforms_um(
        self,
        affine_zyx_um: ArrayLike,
        origin_zyx_um: ArrayLike,
        spacing_zyx_um: ArrayLike,
        tile: int | str,
    ) -> None:
        """Save global registration transform for one tile.

        Parameters
        ----------
        affine_zyx_um : ArrayLike
            Final 4x4 registration correction in physical Z, Y, X coordinates,
            applied after the separately stored camera-to-stage transform.
        origin_zyx_um : ArrayLike
            Native image origin in Z, Y, X micrometers, before camera mapping.
        spacing_zyx_um : ArrayLike
            Native Z, Y, X voxel spacing in micrometers.
        tile : int or str
            Tile index or tile id.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        try:
            entity_root = (
                self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
            )
            self._save_entity_attributes(
                entity_root_path=entity_root,
                updates={
                    "affine_zyx_um": np.asarray(
                        affine_zyx_um, dtype=np.float32
                    ).tolist(),
                    "origin_zyx_um": np.asarray(
                        origin_zyx_um, dtype=np.float32
                    ).tolist(),
                    "spacing_zyx_um": round_spacing_um(spacing_zyx_um).tolist(),
                },
            )
        except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError) as e:
            print(e)
            print("Could not save global coordinate transforms.")

    def load_global_fiducial_image(
        self,
        return_future: bool | None = True,
    ) -> "tuple[np.ndarray | Future | TensorStore, ArrayLike, ArrayLike, ArrayLike] | None":
        """Load downsampled, fused fiducial image.

        Parameters
        ----------
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        fused_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Downsampled, fused fiducial image.
        affine_zyx_um : ArrayLike or None
            Global affine registration transform for fused image.
        origin_zyx_um : ArrayLike or None
            Global origin registration transform for fused image.
        spacing_zyx_um : ArrayLike or None
            Global spacing registration transform for fused image.
        """
        current_local_zarr_path = self._fused_root_path / Path(
            f"fused_{self.fiducial_folder_name}_zyx"
        )

        image_path = self._image_store_path(current_local_zarr_path)
        if not image_path.exists():
            print("Globally registered, fused image not found.")
            return None

        try:
            fused_image = self._load_from_zarr_array(image_path, return_future)
            attributes = self.load_image_metadata(image_path)
            affine_zyx_um = np.asarray(attributes["affine_zyx_um"], dtype=np.float32)
            origin_zyx_um = np.asarray(attributes["origin_zyx_um"], dtype=np.float32)
            spacing_zyx_um = round_spacing_um(attributes["spacing_zyx_um"])
            return fused_image, affine_zyx_um, origin_zyx_um, spacing_zyx_um
        except (OSError, ValueError, KeyError):
            print("Error loading globally registered, fused image.")
            return None

    def save_global_fiducial_image(
        self,
        fused_image: ArrayLike,
        affine_zyx_um: ArrayLike,
        origin_zyx_um: ArrayLike,
        spacing_zyx_um: ArrayLike,
        fusion_type: str = "fiducial",
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """Save downsampled, fused fiducial image.

        The caller selects the fusion grid. This method stores the supplied
        image and spacing without choosing a dataset-specific downsampling.

        Parameters
        ----------
        fused_image : ArrayLike
            Downsampled, fused fiducial image.
        affine_zyx_um : ArrayLike
            Global affine registration transform for fused image.
        origin_zyx_um : ArrayLike
            Global origin registration transform for fused image.
        spacing_zyx_um : ArrayLike
            Caller-selected fused voxel spacing in Z, Y, X microns.
        fusion_type : str
            Type of fusion (fiducial or all_channels).
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None.
        """
        if fusion_type == "fiducial":
            filename = f"fused_{self.fiducial_folder_name}_zyx"
        else:
            filename = "fused_all_channels_zyx"
        current_local_zarr_path = self._fused_root_path / Path(filename)

        metadata_attrs = {
            "affine_zyx_um": np.asarray(affine_zyx_um, dtype=np.float32).tolist(),
            "origin_zyx_um": np.asarray(origin_zyx_um, dtype=np.float32).tolist(),
            "spacing_zyx_um": round_spacing_um(spacing_zyx_um).tolist(),
        }
        fused_array = np.asarray(fused_image)
        try:
            write_future = self._save_to_zarr_array(
                fused_array.astype(np.uint16),
                current_local_zarr_path,
                return_future,
                ome_scale=metadata_attrs["spacing_zyx_um"],
                extra_attributes=metadata_attrs,
                chunks=self._fused_image_chunks(fused_array),
            )
            if write_future is not None:
                write_future.result()
            return write_future
        except (OSError, TimeoutError):
            print("Error saving fused image.")
            raise

    def load_local_decoded_spots(
        self,
        tile: int | str,
        decode_run_key: str | None = None,
    ) -> pd.DataFrame | None:
        """Load decoded spots and features for one tile.

        Parameters
        ----------
        tile : int or str
            Tile index or tile id.
        decode_run_key : str or None, default None
            Optional decoded-output run key.

        Returns
        -------
        tile_features : pandas.DataFrame or None
            Decoded spots and features for one tile.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        current_tile_features_path = self._decoded_run_root(decode_run_key) / Path(
            tile_id + "_decoded_features.parquet"
        )

        if not current_tile_features_path.exists():
            print("Decoded spots not found.")
            return None
        else:
            tile_features = self._load_from_parquet(current_tile_features_path)
            return tile_features

    def save_local_decoded_spots(
        self,
        features_df: pd.DataFrame,
        tile: int | str,
        decode_run_key: str | None = None,
    ) -> None:
        """Save decoded spots and features for one tile.

        Parameters
        ----------
        features_df : pd.DataFrame
            Decoded spots and features for one tile.
        tile : int or str
            Tile index or tile id.
        decode_run_key : str or None, default None
            Optional decoded-output run key.
        """
        if isinstance(tile, int):
            if tile < 0 or tile >= self._num_tiles:
                print("Set tile index >=0 and <" + str(self._num_tiles))
                return None
            else:
                tile_id = self._tile_ids[tile]
        elif isinstance(tile, str):
            if tile not in self._tile_ids:
                print("set valid tiled id")
                return None
            else:
                tile_id = tile
        else:
            print("'tile' must be integer index or string identifier")
            return None

        decoded_root_path = self._decoded_run_root(decode_run_key)
        decoded_root_path.mkdir(parents=True, exist_ok=True)
        current_tile_features_path = decoded_root_path / Path(
            tile_id + "_decoded_features.parquet"
        )

        self._save_to_parquet(features_df, current_tile_features_path)

    def load_global_filtered_decoded_spots(
        self,
        decode_run_key: str | None = None,
        gene_ids: Collection[str] | None = None,
        columns: Collection[str] | None = None,
    ) -> pd.DataFrame | None:
        """Load all decoded and filtered spots.

        Parameters
        ----------
        decode_run_key : str or None, default None
            Optional decoded-output run key.
        gene_ids : Collection[str] or None, default None
            Optional gene ids to load.
        columns : Collection[str] or None, default None
            Optional columns to load.

        Returns
        -------
        all_tiles_filtered : pandas.DataFrame or None
            All decoded and filtered spots.
        """
        current_global_filtered_decoded_dir_path = self._global_filtered_decoded_root(
            decode_run_key
        )
        current_global_filtered_decoded_path = (
            current_global_filtered_decoded_dir_path / Path("decoded_features.parquet")
        )

        if not current_global_filtered_decoded_path.exists():
            print("Global, filtered, decoded spots not found.")
            return None
        elif gene_ids is not None or columns is not None:
            selected_gene_ids = (
                [str(gene_id) for gene_id in gene_ids] if gene_ids is not None else []
            )
            filters = (
                [("gene_id", "in", selected_gene_ids)] if gene_ids is not None else None
            )
            all_tiles_filtered = pd.read_parquet(
                current_global_filtered_decoded_path,
                columns=None if columns is None else list(columns),
                filters=filters,
            )
            if gene_ids is not None and "gene_id" in all_tiles_filtered.columns:
                all_tiles_filtered = all_tiles_filtered[
                    all_tiles_filtered["gene_id"].astype(str).isin(selected_gene_ids)
                ]
            return all_tiles_filtered
        else:
            all_tiles_filtered = self._load_from_parquet(
                current_global_filtered_decoded_path
            )
            return all_tiles_filtered

    def save_global_filtered_decoded_spots(
        self,
        filtered_decoded_df: pd.DataFrame,
        decode_run_key: str | None = None,
    ) -> None:
        """Save all decoded and filtered spots.

        Parameters
        ----------
        filtered_decoded_df : pd.DataFrame
            All decoded and filtered spots.
        decode_run_key : str or None, default None
            Optional decoded-output run key.
        """
        current_global_filtered_decoded_dir_path = self._global_filtered_decoded_root(
            decode_run_key
        )

        if not current_global_filtered_decoded_dir_path.exists():
            current_global_filtered_decoded_dir_path.mkdir(parents=True)

        current_global_filtered_decoded_path = (
            current_global_filtered_decoded_dir_path / Path("decoded_features.parquet")
        )
        current_global_filtered_decoded_csv_gz_path = (
            current_global_filtered_decoded_dir_path / Path("decoded_features.csv.gz")
        )

        self._save_to_parquet(filtered_decoded_df, current_global_filtered_decoded_path)
        self._save_to_csv_gz(
            filtered_decoded_df, current_global_filtered_decoded_csv_gz_path
        )

    def load_global_cellpose_outlines(
        self,
    ) -> dict | None:
        """Load Cellpose max projection cell outlines.

        Returns
        -------
        cellpose_outlines : dict or None
            Cellpose cell mask outlines.
        """
        current_cellpose_outlines_path = (
            self._segmentation_root_path / Path("cellpose") / Path("cell_outlines.json")
        )

        if not current_cellpose_outlines_path.exists():
            print("Cellpose cell mask outlines not found.")
            return None
        else:
            cellpose_outlines = self._load_from_microjson(
                current_cellpose_outlines_path
            )
            return cellpose_outlines

    def load_global_cellpose_roi_zip(
        self,
    ) -> dict[int, ArrayLike] | None:
        """Load global Cellpose outlines from an ImageJ ROI zip.

        Returns
        -------
        cellpose_outlines : dict[int, ArrayLike] or None
            Cellpose ROI outlines with global X, Y coordinates.
        """
        roi_path = (
            self._segmentation_root_path
            / Path("cellpose")
            / Path("imagej_rois")
            / Path("global_coords_rois.zip")
        )
        if not roi_path.exists():
            print("Cellpose global ROI zip not found.")
            return None

        try:
            from roifile import roiread
        except ImportError:
            print("roifile is required to load Cellpose ROI zip.")
            return None

        outlines: dict[int, ArrayLike] = {}
        try:
            for idx, roi in enumerate(roiread(roi_path)):
                coordinates = getattr(roi, "subpixel_coordinates", None)
                if coordinates is None:
                    coordinates = roi.coordinates()
                if coordinates is not None:
                    outlines[idx + 1] = np.asarray(coordinates, dtype=float)
            return outlines
        except (OSError, ValueError) as exc:
            print(exc)
            print("Error loading Cellpose ROI zip.")
            return None

    def _proseg_3d_root(self) -> Path:
        """
        Return the root path for Proseg 3D outputs.

        Returns
        -------
        Path
            Proseg 3D output root.
        """
        return self._datastore_path / Path("proseg") / Path("3D")

    def _proseg_3d_run_root(self, run_name: str | None = None) -> Path:
        """
        Return one Proseg 3D run root path.

        Parameters
        ----------
        run_name : str or None, default None
            Proseg run name. ``None`` or ``"default"`` selects ``proseg/3D``.

        Returns
        -------
        Path
            Proseg run root path.
        """
        proseg_root = self._proseg_3d_root()
        if run_name is None or run_name == "default":
            return proseg_root
        return proseg_root / Path(run_name)

    def list_proseg_3d_runs(self) -> list[str]:
        """List available Proseg 3D output runs.

        Returns
        -------
        proseg_runs : list[str]
            Available Proseg 3D run names. The direct ``proseg/3D`` output is
            named ``"default"``.
        """
        proseg_root = self._proseg_3d_root()
        if not proseg_root.exists():
            return []

        run_names: list[str] = []
        candidate_roots = [proseg_root]
        candidate_roots.extend(
            path for path in sorted(proseg_root.iterdir()) if path.is_dir()
        )
        for root in candidate_roots:
            transcript_path = root / Path("transcript_metadata_3D.csv.gz")
            polygon_path = root / Path("cell_polygons_3D.geojson.gz")
            if transcript_path.exists() and polygon_path.exists():
                run_names.append("default" if root == proseg_root else root.name)
        return sorted(run_names)

    def load_proseg_transcripts_3d(
        self,
        run_name: str | None = None,
    ) -> pd.DataFrame | None:
        """Load Proseg 3D transcript metadata.

        Parameters
        ----------
        run_name : str or None, default None
            Proseg run name. ``None`` or ``"default"`` selects ``proseg/3D``.

        Returns
        -------
        transcripts : pandas.DataFrame or None
            Proseg transcript metadata.
        """
        transcript_path = self._proseg_3d_run_root(run_name) / Path(
            "transcript_metadata_3D.csv.gz"
        )
        if not transcript_path.exists():
            print("Proseg transcript metadata not found.")
            return None
        try:
            return pd.read_csv(transcript_path, compression="gzip")
        except (OSError, ValueError) as exc:
            print(exc)
            print("Error loading Proseg transcript metadata.")
            return None

    def load_proseg_cell_polygons_3d(
        self,
        run_name: str | None = None,
    ) -> dict[Any, ArrayLike] | None:
        """Load Proseg 3D refined cell polygons.

        Parameters
        ----------
        run_name : str or None, default None
            Proseg run name. ``None`` or ``"default"`` selects ``proseg/3D``.

        Returns
        -------
        polygons : dict[Any, ArrayLike] or None
            Cell identifiers mapped to polygon vertices in X, Y order.
        """
        polygon_path = self._proseg_3d_run_root(run_name) / Path(
            "cell_polygons_3D.geojson.gz"
        )
        if not polygon_path.exists():
            print("Proseg cell polygons not found.")
            return None

        try:
            with gzip.open(polygon_path, "rt", encoding="utf-8") as file:
                geojson = json.load(file)
        except (OSError, json.JSONDecodeError) as exc:
            print(exc)
            print("Error loading Proseg cell polygons.")
            return None

        polygons: dict[Any, ArrayLike] = {}
        for idx, feature in enumerate(geojson.get("features", [])):
            properties = feature.get("properties", {})
            cell_id = properties.get("cell", idx)
            geometry = feature.get("geometry", {})
            coordinates = geometry.get("coordinates", [])
            rings: list[np.ndarray] = []
            if geometry.get("type") == "Polygon":
                rings.extend(np.asarray(ring, dtype=float) for ring in coordinates)
            elif geometry.get("type") == "MultiPolygon":
                for polygon in coordinates:
                    rings.extend(np.asarray(ring, dtype=float) for ring in polygon)
            if rings:
                polygons[cell_id] = max(rings, key=len)

        return polygons

    def baysor_3d_available(self) -> bool:
        """Return whether Baysor 3D molecules and cell boundaries are present."""
        baysor_root = self._segmentation_root_path / Path("baysor") / Path("3D")
        return (baysor_root / Path("molecules.parquet")).exists() and (
            baysor_root / Path("cell_boundaries_3d.parquet")
        ).exists()

    def load_baysor_molecules_3d(self) -> pd.DataFrame | None:
        """
        Load Baysor 3D molecule assignments.

        Returns
        -------
        pandas.DataFrame or None
            Baysor molecule table, if present.
        """
        molecules_path = (
            self._segmentation_root_path
            / Path("baysor")
            / Path("3D")
            / Path("molecules.parquet")
        )
        if not molecules_path.exists():
            print("Baysor molecules not found.")
            return None
        try:
            return self._load_from_parquet(molecules_path)
        except (OSError, ValueError) as exc:
            print(exc)
            print("Error loading Baysor molecules.")
            return None

    def load_baysor_cell_boundaries_3d(self) -> pd.DataFrame | None:
        """
        Load Baysor 3D cell boundary polygons.

        Returns
        -------
        pandas.DataFrame or None
            Baysor cell boundary table, if present.
        """
        boundaries_path = (
            self._segmentation_root_path
            / Path("baysor")
            / Path("3D")
            / Path("cell_boundaries_3d.parquet")
        )
        if not boundaries_path.exists():
            print("Baysor cell boundaries not found.")
            return None
        try:
            return self._load_from_parquet(boundaries_path)
        except (OSError, ValueError) as exc:
            print(exc)
            print("Error loading Baysor cell boundaries.")
            return None

    def load_global_cellpose_segmentation_image(
        self,
        return_future: bool | None = True,
    ) -> "np.ndarray | Future | TensorStore | None":
        """Load Cellpose max projection, downsampled segmentation image.

        Parameters
        ----------
        return_future : bool or None
            True returns a read future, False returns a NumPy array, and None
            returns a sliceable TensorStore handle opened through yaozarrs.

        Returns
        -------
        fused_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
            Cellpose max projection, downsampled segmentation image.
        """
        current_local_zarr_path = (
            self._segmentation_root_path
            / Path("cellpose")
            / Path(f"masks_{self.fiducial_folder_name}_iso_zyx")
        )

        image_path = self._image_store_path(current_local_zarr_path)
        if not image_path.exists():
            print("Cellpose prediction on global fused image not found.")
            return None

        try:
            fused_image = self._load_from_zarr_array(image_path, return_future)
            return fused_image
        except (OSError, ValueError):
            print("Error loading Cellpose image.")
            return None

    def save_global_cellpose_segmentation_image(
        self,
        cellpose_image: ArrayLike,
        downsampling: Sequence[float],
        return_future: bool | None = False,
    ) -> "WriteFutures | None":
        """Save Cellpose max projection, downsampled segmentation image.

        The caller runs segmentation and selects its image grid. This method
        stores the supplied labels unchanged and derives their physical scale
        from the native voxel calibration and supplied downsampling factors.

        Parameters
        ----------
        cellpose_image : ArrayLike
            Cellpose max projection, downsampled segmentation image.
        downsampling : Sequence[float]
            Caller-selected Z, Y, X factors: segmentation spacing divided by
            native voxel spacing. Two-dimensional masks use the resulting YX
            physical scale while retaining all three factors in metadata.
        return_future : bool or None
            Return the completed TensorStore write handle when True. Writes
            finish before associated metadata is reported as saved.

        Returns
        -------
        tensorstore.WriteFutures or None
            Completed pixel-write handle when return_future is True; otherwise
            None.
        """
        current_local_zarr_path = (
            self._segmentation_root_path
            / Path("cellpose")
            / Path(f"masks_{self.fiducial_folder_name}_iso_zyx")
        )

        downsampling = np.asarray(downsampling, dtype=np.float64)
        if (
            downsampling.shape != (3,)
            or not np.all(np.isfinite(downsampling))
            or np.any(downsampling <= 0)
        ):
            raise ValueError(
                "Downsampling must contain three positive finite Z, Y, X factors."
            )
        spacing = round_spacing_um(self.voxel_size_zyx_um) * downsampling
        attributes = {"downsampling": downsampling.tolist()}

        try:
            write_future = self._save_to_zarr_array(
                cellpose_image,
                current_local_zarr_path,
                return_future,
                ome_scale=round_spacing_um(spacing).tolist(),
                extra_attributes=attributes,
            )
            if write_future is not None:
                write_future.result()
            return write_future
        except (OSError, TimeoutError):
            print("Error saving Cellpose image.")
            raise

binning property writable

Camera binning.

Returns:

Name Type Description
binning int

Camera binning.

bit_ids property

Bit IDs.

Returns:

Name Type Description
bit_ids Collection[str]

Bit IDs.

camera_model property writable

Camera model.

Returns:

Name Type Description
camera_model str or None

Camera model.

channel_psfs property writable

Channel point spread functions (PSF).

Returns:

Name Type Description
channel_psfs ArrayLike

Channel point spread functions (PSF).

channel_shading_maps property writable

Channel shaiding images.

Returns:

Name Type Description
channel_shading_maps ArrayLike

Channel shading images.

channels_in_data property writable

Channel indices.

Returns:

Name Type Description
channels_in_data Collection[int]

Channel indices.

codebook property writable

Codebook.

Returns:

Name Type Description
codebook DataFrame

Codebook.

datastore_path property

Experiment datastore directory.

datastore_state property writable

Datastore state.

Returns:

Name Type Description
datastore_state dict or None

Datastore state.

e_per_ADU property writable

Electrons per camera ADU.

Returns:

Name Type Description
e_per_ADU float

Electrons per camera ADU.

experiment_order property writable

Round and bit order.

Returns:

Name Type Description
experiment_order DataFrame

Round and bit order.

global_background_vector property writable

Global background vector.

Returns:

Name Type Description
global_background_vector ArrayLike

Global background vector.

global_normalization_vector property writable

Global normalization vector.

Returns:

Name Type Description
global_normalization_vector ArrayLike

Global normalization vector.

iterative_background_vector property writable

Iterative background vector.

Returns:

Name Type Description
iterative_background_vector ArrayLike

Iterative background vector.

iterative_normalization_vector property writable

Iterative normalization vector.

Returns:

Name Type Description
iterative_normalization_vector ArrayLike

Iterative normalization vector.

microscope_type property writable

Microscope type.

Returns:

Name Type Description
microscope_type str or None

Microscope type.

na property writable

Detection objective numerical aperture (NA).

Returns:

Name Type Description
na float

Detection objective numerical aperture (NA).

noise_map property writable

Camera noise image.

Returns:

Name Type Description
noise_map ArrayLike

Camera noise image.

num_bits property writable

Number of bits.

Returns:

Name Type Description
num_bits int

Number of bits.

num_rounds property writable

Number of rounds.

Returns:

Name Type Description
num_rounds int

Number of rounds.

num_tiles property writable

Number of tiles.

Returns:

Name Type Description
num_tiles int

Number of tiles.

ri property writable

Detection objective refractive index (RI).

Returns:

Name Type Description
ri float

Detection objective refractive index (RI).

round_ids property

Round IDs.

Returns:

Name Type Description
round_ids Collection[str]

Round IDs.

tile_ids property

Tile IDs.

Returns:

Name Type Description
tile_ids Collection[str]

Tile IDs.

tile_overlap property writable

XY tile overlap.

Returns:

Name Type Description
tile_overlap float

XY tile overlap.

voxel_size_zyx_um property writable

Voxel size, zyx order (microns).

Returns:

Name Type Description
voxel_size_zyx_um ArrayLike

Voxel size, zyx order (microns).

__init__(datastore_path, validate=True)

Initialize a qi2lab datastore handle.

Parameters:

Name Type Description Default
datastore_path str | Path

Datastore root path.

required
validate bool

Whether to validate existing image arrays while parsing the store.

True
Source code in src/merfish3danalysis/qi2labDataStore.py
def __init__(self, datastore_path: str | Path, validate: bool = True) -> None:
    """
    Initialize a qi2lab datastore handle.

    Parameters
    ----------
    datastore_path : str | Path
        Datastore root path.
    validate : bool
        Whether to validate existing image arrays while parsing the store.
    """
    self._datastore_path = Path(datastore_path)
    if self._datastore_path.exists():
        self._parse_datastore(validate=validate)
    else:
        self._init_datastore()

_build_axes(v05, ndim) staticmethod

Build NGFF axes models for a given dimensionality.

Parameters:

Name Type Description Default
v05 Any

yaozarrs NGFF model namespace.

required
ndim int

Number of array dimensions.

required

Returns:

Type Description
list[Any]

NGFF axis models ordered to match array dimensions.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _build_axes(v05: Any, ndim: int) -> list[Any]:
    """
    Build NGFF axes models for a given dimensionality.

    Parameters
    ----------
    v05 : Any
        yaozarrs NGFF model namespace.
    ndim : int
        Number of array dimensions.

    Returns
    -------
    list[Any]
        NGFF axis models ordered to match array dimensions.
    """
    axis_names = ["t", "c", "z", "y", "x"][-ndim:]
    axes: list[Any] = []
    for axis_name in axis_names:
        if axis_name in {"z", "y", "x"}:
            axes.append(v05.SpaceAxis(name=axis_name, unit="micrometer"))
        elif axis_name == "c":
            axes.append(v05.ChannelAxis(name="c"))
        else:
            axes.append(v05.TimeAxis(name="t", unit="second"))
    return axes

_calibrations_attributes_path()

Path to calibrations metadata sidecar.

Returns:

Type Description
Path

Path to calibrations/attributes.json.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _calibrations_attributes_path(self) -> Path:
    """
    Path to calibrations metadata sidecar.

    Returns
    -------
    Path
        Path to ``calibrations/attributes.json``.
    """
    return self._calibrations_zarr_path / Path("attributes.json")

_check_for_zarr_array(image_path) staticmethod

Check if image exists and is readable via yaozarrs.

Parameters:

Name Type Description Default
image_path Path or str

Image store path.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _check_for_zarr_array(image_path: Path | str) -> None:
    """Check if image exists and is readable via yaozarrs.

    Parameters
    ----------
    image_path : Path or str
        Image store path.
    """
    image_path = qi2labDataStore._image_store_path(image_path)
    if not image_path.exists():
        raise FileNotFoundError(image_path)

    group = open_group(str(image_path))
    _ = group["0"]

_coerce_experiment_order_dataframe(value)

Normalize experiment order into the canonical DataFrame form.

Parameters:

Name Type Description Default
value ArrayLike | DataFrame

Experiment order table or array to normalize.

required

Returns:

Type Description
DataFrame

Experiment order as a DataFrame with channel columns.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _coerce_experiment_order_dataframe(
    self, value: ArrayLike | pd.DataFrame
) -> pd.DataFrame:
    """
    Normalize experiment order into the canonical DataFrame form.

    Parameters
    ----------
    value : ArrayLike | pd.DataFrame
        Experiment order table or array to normalize.

    Returns
    -------
    pd.DataFrame
        Experiment order as a DataFrame with channel columns.
    """
    if isinstance(value, pd.DataFrame):
        return value

    channel_list = [str(channel) for channel in self._channels_in_data]
    return pd.DataFrame(value, columns=channel_list, dtype="int64")

_collect_strict_ids(parent, prefix, width) classmethod

Collect and sort strict identifiers under a folder.

Parameters:

Name Type Description Default
parent Path

Folder containing identifier-named child directories.

required
prefix str

Required identifier prefix.

required
width int

Required number of zero-padded digits.

required

Returns:

Type Description
list[str]

Strict identifiers sorted by numeric value.

Source code in src/merfish3danalysis/qi2labDataStore.py
@classmethod
def _collect_strict_ids(cls, parent: Path, prefix: str, width: int) -> list[str]:
    """
    Collect and sort strict identifiers under a folder.

    Parameters
    ----------
    parent : Path
        Folder containing identifier-named child directories.
    prefix : str
        Required identifier prefix.
    width : int
        Required number of zero-padded digits.

    Returns
    -------
    list[str]
        Strict identifiers sorted by numeric value.
    """

    def sort_id(value: str) -> tuple[int, int, str]:
        """
        Return the strict identifier sort key.

        Parameters
        ----------
        value : str
            Identifier string.

        Returns
        -------
        tuple[int, int, str]
            Numeric and lexical sort key.
        """
        return cls._strict_id_sort_key(value, prefix, width)

    ids = [entry.name for entry in parent.iterdir() if entry.is_dir()]
    ids.sort(key=sort_id)
    return ids

_create_array_tensorstore_qi2lab(path, shape, dtype, chunks, *, shards, dimension_names, overwrite, compression) staticmethod

Create a Zarr v3 array for the yaozarrs image writer.

yaozarrs accepts a custom array creator but does not expose compression level or shuffle settings. This TensorStore adapter preserves the datastore's Blosc level 5 and bitshuffle settings; yaozarrs handles the OME group, axes, and image metadata.

Parameters:

Name Type Description Default
path Path

Destination zarr array path.

required
shape tuple[int, ...]

Array shape.

required
dtype Any

Array dtype.

required
chunks tuple[int, ...]

Chunk shape.

required
shards tuple[int, ...] | None

Optional shard shape.

required
dimension_names list[str] | None

Optional dimension names for metadata.

required
overwrite bool

Whether to replace an existing array.

required
compression str

Compression preset name.

required

Returns:

Type Description
Any

Open tensorstore array handle.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _create_array_tensorstore_qi2lab(
    path: Path,
    shape: tuple[int, ...],
    dtype: Any,
    chunks: tuple[int, ...],
    *,
    shards: tuple[int, ...] | None,
    dimension_names: list[str] | None,
    overwrite: bool,
    compression: str,
) -> Any:
    """
    Create a Zarr v3 array for the yaozarrs image writer.

    yaozarrs accepts a custom array creator but does not expose compression
    level or shuffle settings. This TensorStore adapter preserves the
    datastore's Blosc level 5 and bitshuffle settings; yaozarrs handles
    the OME group, axes, and image metadata.

    Parameters
    ----------
    path : Path
        Destination zarr array path.
    shape : tuple[int, ...]
        Array shape.
    dtype : Any
        Array dtype.
    chunks : tuple[int, ...]
        Chunk shape.
    shards : tuple[int, ...] | None
        Optional shard shape.
    dimension_names : list[str] | None
        Optional dimension names for metadata.
    overwrite : bool
        Whether to replace an existing array.
    compression : str
        Compression preset name.

    Returns
    -------
    Any
        Open tensorstore array handle.
    """
    import tensorstore as ts

    if compression == "blosc-zstd":
        chunk_codecs = [
            {
                "name": "blosc",
                "configuration": {
                    "cname": "zstd",
                    "clevel": 5,
                    "shuffle": "bitshuffle",
                },
            }
        ]
    elif compression == "blosc-lz4":
        chunk_codecs = [
            {
                "name": "blosc",
                "configuration": {
                    "cname": "lz4",
                    "clevel": 5,
                    "shuffle": "bitshuffle",
                },
            }
        ]
    elif compression == "zstd":
        chunk_codecs = [{"name": "zstd", "configuration": {"level": 3}}]
    elif compression == "none":
        chunk_codecs = []
    else:
        raise ValueError(f"Unknown compression: {compression}")

    codecs = chunk_codecs
    chunk_layout: dict[str, Any] = {"chunk": {"shape": list(chunks)}}
    if shards is not None:
        codecs = [
            {
                "name": "sharding_indexed",
                "configuration": {
                    "chunk_shape": list(chunks),
                    "codecs": chunk_codecs,
                },
            }
        ]
        chunk_layout = {"write_chunk": {"shape": list(shards)}}

    domain: dict[str, Any] = {"shape": list(shape)}
    if dimension_names:
        domain["labels"] = dimension_names

    try:
        dtype_str = dtype.name
    except AttributeError:
        dtype_str = str(dtype)

    return ts.open(
        {
            "driver": "zarr3",
            "kvstore": {"driver": "file", "path": str(path)},
            "schema": {
                "dtype": dtype_str,
                "domain": domain,
                "chunk_layout": chunk_layout,
                "codec": {"driver": "zarr3", "codecs": codecs},
            },
            "create": True,
            "delete_existing": overwrite,
        }
    ).result()

_decoded_run_root(decode_run_key=None)

Return the local decoded output root for an optional decode run.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional decoded-output run key.

None

Returns:

Type Description
Path

Decoded output root.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _decoded_run_root(self, decode_run_key: str | None = None) -> Path:
    """
    Return the local decoded output root for an optional decode run.

    Parameters
    ----------
    decode_run_key : str or None, default None
        Optional decoded-output run key.

    Returns
    -------
    pathlib.Path
        Decoded output root.
    """
    decode_run_key = self._validate_decode_run_key(decode_run_key)
    if decode_run_key is None:
        return self._decoded_root_path
    return self._decoded_root_path / Path(decode_run_key)

_default_chunks(array, spatial_chunk_zyx=(16, 512, 512)) staticmethod

Create sane default chunk sizes based on dimensionality.

Parameters:

Name Type Description Default
array ndarray

Array that will be written.

required
spatial_chunk_zyx tuple[int, int, int]

Desired Z, Y, X storage chunks for local fiducial and readout images.

(16, 512, 512)

Returns:

Type Description
list[int]

Chunk shape matched to the array dimensionality.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _default_chunks(
    array: np.ndarray,
    spatial_chunk_zyx: tuple[int, int, int] = (16, 512, 512),
) -> list[int]:
    """
    Create sane default chunk sizes based on dimensionality.

    Parameters
    ----------
    array : np.ndarray
        Array that will be written.
    spatial_chunk_zyx : tuple[int, int, int], default=(16, 512, 512)
        Desired Z, Y, X storage chunks for local fiducial and readout images.

    Returns
    -------
    list[int]
        Chunk shape matched to the array dimensionality.
    """
    z_chunk, y_chunk, x_chunk = (int(value) for value in spatial_chunk_zyx)
    if array.ndim == 2:
        return [
            min(int(array.shape[0]), y_chunk),
            min(int(array.shape[1]), x_chunk),
        ]
    if array.ndim == 3:
        return [
            min(int(array.shape[0]), z_chunk),
            min(int(array.shape[1]), y_chunk),
            min(int(array.shape[2]), x_chunk),
        ]
    if array.ndim == 4:
        return [
            1,
            min(int(array.shape[1]), z_chunk),
            min(int(array.shape[2]), y_chunk),
            min(int(array.shape[3]), x_chunk),
        ]
    if array.ndim == 5:
        return [
            1,
            1,
            min(int(array.shape[2]), z_chunk),
            min(int(array.shape[3]), y_chunk),
            min(int(array.shape[4]), x_chunk),
        ]
    return list(array.shape)

_entity_attributes_path(entity_root_path) staticmethod

Path to per-entity metadata sidecar.

Parameters:

Name Type Description Default
entity_root_path Path | str

Entity folder path.

required

Returns:

Type Description
Path

Entity metadata sidecar path.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _entity_attributes_path(entity_root_path: Path | str) -> Path:
    """
    Path to per-entity metadata sidecar.

    Parameters
    ----------
    entity_root_path : Path | str
        Entity folder path.

    Returns
    -------
    Path
        Entity metadata sidecar path.
    """
    return Path(entity_root_path) / Path("attributes.json")

_fused_image_chunks(array) staticmethod

Create chunk sizes tailored for fused image storage.

Parameters:

Name Type Description Default
array ndarray

Fused image array that will be written.

required

Returns:

Type Description
list[int]

Chunk shape for fused image storage.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _fused_image_chunks(array: np.ndarray) -> list[int]:
    """
    Create chunk sizes tailored for fused image storage.

    Parameters
    ----------
    array : np.ndarray
        Fused image array that will be written.

    Returns
    -------
    list[int]
        Chunk shape for fused image storage.
    """
    shape = [int(dim) for dim in array.shape]
    if array.ndim == 2:
        return [min(shape[0], 2048), min(shape[1], 2048)]
    if array.ndim == 3:
        return [min(shape[0], 16), min(shape[1], 512), min(shape[2], 512)]
    if array.ndim == 4:
        return [
            min(shape[0], 1),
            min(shape[1], 16),
            min(shape[2], 512),
            min(shape[3], 512),
        ]
    if array.ndim == 5:
        return [
            min(shape[0], 1),
            min(shape[1], 1),
            min(shape[2], 16),
            min(shape[3], 512),
            min(shape[4], 512),
        ]
    return list(array.shape)

_global_filtered_decoded_root(decode_run_key=None)

Return the global filtered decoded-output root for an optional decode run.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional decoded-output run key.

None

Returns:

Type Description
Path

Global filtered decoded-output root.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _global_filtered_decoded_root(
    self,
    decode_run_key: str | None = None,
) -> Path:
    """
    Return the global filtered decoded-output root for an optional decode run.

    Parameters
    ----------
    decode_run_key : str or None, default None
        Optional decoded-output run key.

    Returns
    -------
    pathlib.Path
        Global filtered decoded-output root.
    """
    root = self._datastore_path / Path("all_tiles_filtered_decoded_features")
    decode_run_key = self._validate_decode_run_key(decode_run_key)
    if decode_run_key is None:
        return root
    return root / Path(decode_run_key)

_image_store_path(image_path) staticmethod

Normalize image path to the *.ome.zarr folder naming scheme.

Parameters:

Name Type Description Default
image_path Path | str

Logical image path or OME-Zarr path.

required

Returns:

Type Description
Path

Normalized path ending in .ome.zarr.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _image_store_path(image_path: Path | str) -> Path:
    """
    Normalize image path to the *.ome.zarr folder naming scheme.

    Parameters
    ----------
    image_path : Path | str
        Logical image path or OME-Zarr path.

    Returns
    -------
    Path
        Normalized path ending in ``.ome.zarr``.
    """
    path = Path(image_path)
    if path.name.endswith(".ome.zarr"):
        return path
    if path.name.endswith(".zarr"):
        raise ValueError(
            f"Invalid image store name '{path.name}'. Expected '.ome.zarr' suffix."
        )
    if path.suffixes:
        raise ValueError(
            f"Invalid image store name '{path.name}'. Use bare logical names or '.ome.zarr'."
        )
    return path.with_name(path.name + ".ome.zarr")

_init_datastore()

Initialize datastore.

Create directory structure and initialize datastore state.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _init_datastore(self) -> None:
    """Initialize datastore.

    Create directory structure and initialize datastore state.
    """
    self._datastore_path.mkdir(parents=True)
    self._calibrations_zarr_path = self._datastore_path / Path(r"calibrations")
    self._calibrations_zarr_path.mkdir()
    self._save_to_json({}, self._calibrations_attributes_path())
    self.fiducial_folder_name = r"fiducial"
    self._fiducial_root_path = self._datastore_path / Path(
        self.fiducial_folder_name
    )
    self._fiducial_root_path.mkdir()
    self._readouts_root_path = self._datastore_path / Path(r"readouts")
    self._readouts_root_path.mkdir()
    self.feature_predictor_folder_name = r"feature_predictor"
    self._feature_predictor_localizations_root_path = self._datastore_path / Path(
        f"{self.feature_predictor_folder_name}_localizations"
    )
    self._feature_predictor_localizations_root_path.mkdir()
    self._decoded_root_path = self._datastore_path / Path(r"decoded")
    self._decoded_root_path.mkdir()
    self._fused_root_path = self._datastore_path / Path(r"fused")
    self._fused_root_path.mkdir()
    self._segmentation_root_path = self._datastore_path / Path(r"segmentation")
    self._segmentation_root_path.mkdir()

    # initialize datastore state
    self._datastore_state_json_path = self._datastore_path / Path(
        r"datastore_state.json"
    )
    self._datastore_state = {
        "Version": 0.6,
        "Initialized": True,
        "Calibrations": False,
        "Corrected": False,
        "LocalRegistered": False,
        "GlobalRegistered": False,
        "Fused": False,
        "SegmentedCells": False,
        "DecodedSpots": False,
        "FilteredSpots": False,
    }

    self._save_to_json(self._datastore_state, self._datastore_state_json_path)

_load_calibrations_attributes()

Load calibrations metadata sidecar.

Returns:

Type Description
dict[str, Any]

Calibration metadata loaded from disk.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _load_calibrations_attributes(self) -> dict[str, Any]:
    """
    Load calibrations metadata sidecar.

    Returns
    -------
    dict[str, Any]
        Calibration metadata loaded from disk.
    """
    attributes_path = self._calibrations_attributes_path()
    if not attributes_path.is_file():
        raise FileNotFoundError(
            f"Calibration attributes not found: {attributes_path}"
        )
    return self._load_from_json(attributes_path)

_load_entity_attributes(entity_root_path, image_names=None)

Load entity metadata from sidecar + image extra_attributes.

Parameters:

Name Type Description Default
entity_root_path Path | str

Entity folder path.

required
image_names Sequence[str] | None

Optional image names whose extra attributes should be merged.

None

Returns:

Type Description
dict[str, Any]

Merged entity metadata.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _load_entity_attributes(
    self,
    entity_root_path: Path | str,
    image_names: Sequence[str] | None = None,
) -> dict[str, Any]:
    """
    Load entity metadata from sidecar + image extra_attributes.

    Parameters
    ----------
    entity_root_path : Path | str
        Entity folder path.
    image_names : Sequence[str] | None
        Optional image names whose extra attributes should be merged.

    Returns
    -------
    dict[str, Any]
        Merged entity metadata.
    """
    entity_root = Path(entity_root_path)
    merged: dict[str, Any] = {}

    default_images = (
        "corrected_data",
        "decon_data",
        f"{self.feature_predictor_folder_name}_data",
        "opticalflow_xform_px",
    )
    candidate_names = image_names if image_names is not None else default_images
    for image_name in candidate_names:
        image_path = self._image_store_path(entity_root / Path(image_name))
        if not image_path.exists():
            continue
        merged.update(self.load_image_metadata(image_path))

    merged.update(self._load_from_json(self._entity_attributes_path(entity_root)))

    return merged

_load_from_json(dictionary_path) staticmethod

Load json as dictionary.

Parameters:

Name Type Description Default
dictionary_path Path or str

Path to json file.

required

Returns:

Name Type Description
dictionary dict

Dictionary from json file.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _load_from_json(dictionary_path: Path | str) -> dict:
    """Load json as dictionary.

    Parameters
    ----------
    dictionary_path : Path or str
        Path to json file.

    Returns
    -------
    dictionary : dict
        Dictionary from json file.
    """
    try:
        with open(dictionary_path) as f:
            dictionary = json.load(f)
    except FileNotFoundError:
        return {}
    if not isinstance(dictionary, dict):
        raise ValueError(f"Expected a JSON object in {dictionary_path}")
    return dictionary

_load_from_microjson(dictionary_path) staticmethod

Load cell outlines outlines microjson as dictionary.

Parameters:

Name Type Description Default
dictionary_path Path or str

Path to microjson file.

required

Returns:

Name Type Description
outlines dict

Cell outlines dictionary.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _load_from_microjson(dictionary_path: Path | str) -> dict:
    """Load cell outlines outlines microjson as dictionary.

    Parameters
    ----------
    dictionary_path : Path or str
        Path to microjson file.

    Returns
    -------
    outlines : dict
        Cell outlines dictionary.
    """
    try:
        with open(dictionary_path) as f:
            data = json.load(f)
            outlines = {}
            for feature in data["features"]:
                cell_id = feature["properties"]["cell_id"]
                coordinates = feature["geometry"]["coordinates"][0]
                outlines[cell_id] = np.array(coordinates)
    except (
        FileNotFoundError,
        json.JSONDecodeError,
        KeyError,
        TypeError,
        ValueError,
    ):
        outlines = {}
    return outlines

_load_from_parquet(parquet_path) staticmethod

Load dataframe from parquet.

Parameters:

Name Type Description Default
parquet_path Path or str

Path to parquet file.

required

Returns:

Name Type Description
df DataFrame

Dataframe from parquet file.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _load_from_parquet(parquet_path: Path | str) -> pd.DataFrame:
    """Load dataframe from parquet.

    Parameters
    ----------
    parquet_path : Path or str
        Path to parquet file.

    Returns
    -------
    df : pd.DataFrame
        Dataframe from parquet file.
    """
    return pd.read_parquet(parquet_path)

_load_from_zarr_array(image_path, return_future=True) staticmethod

Read image data via yaozarrs.

Parameters:

Name Type Description Default
image_path Path or str

Image store path.

required
return_future bool or None

Return read future (True), immediately read (False), or return the TensorStore array without issuing a read (None).

True

Returns:

Name Type Description
array Future or ndarray or TensorStore

Read future, immediate array, or lazy TensorStore handle obtained through yaozarrs.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _load_from_zarr_array(
    image_path: Path | str, return_future: bool | None = True
) -> "np.ndarray | Future | TensorStore":
    """Read image data via yaozarrs.

    Parameters
    ----------
    image_path : Path or str
        Image store path.
    return_future : bool or None
        Return read future (True), immediately read (False), or return the
        TensorStore array without issuing a read (None).

    Returns
    -------
    array : tensorstore.Future or numpy.ndarray or tensorstore.TensorStore
        Read future, immediate array, or lazy TensorStore handle obtained
        through yaozarrs.
    """
    image_path = qi2labDataStore._image_store_path(image_path)
    group = open_group(str(image_path))
    current_array = group["0"].to_tensorstore()

    if return_future is None:
        return current_array
    read_future = current_array.read()
    return read_future if return_future else read_future.result()

_normalize_stage_position_zyx_um(stage_zyx_um) staticmethod

Return ZYX stage coordinates, padding legacy YX positions with Z=0.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _normalize_stage_position_zyx_um(stage_zyx_um: ArrayLike) -> np.ndarray:
    """Return ZYX stage coordinates, padding legacy YX positions with Z=0."""
    stage = np.asarray(stage_zyx_um, dtype=np.float32)
    if stage.shape == (2,):
        return np.asarray((0.0, stage[0], stage[1]), dtype=np.float32)
    if stage.shape != (3,):
        raise ValueError(
            "Stage position must contain two (Y, X) or three (Z, Y, X) "
            f"coordinates; got shape {stage.shape}."
        )
    return stage

_normalize_transform(values, ndim, fill) staticmethod

Normalize transform vectors to match array dimensionality.

Parameters:

Name Type Description Default
values Sequence[float] | None

Optional transform vector.

required
ndim int

Target array dimensionality.

required
fill float

Fill value for missing leading dimensions.

required

Returns:

Type Description
list[float]

Transform vector with one value per array dimension.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _normalize_transform(
    values: Sequence[float] | None, ndim: int, fill: float
) -> list[float]:
    """
    Normalize transform vectors to match array dimensionality.

    Parameters
    ----------
    values : Sequence[float] | None
        Optional transform vector.
    ndim : int
        Target array dimensionality.
    fill : float
        Fill value for missing leading dimensions.

    Returns
    -------
    list[float]
        Transform vector with one value per array dimension.
    """
    if values is None:
        return [fill] * ndim
    cast = [float(v) for v in values]
    if len(cast) == ndim:
        return cast
    if len(cast) == 3:
        if ndim == 2:
            return cast[1:]
        if ndim >= 3:
            return [fill] * (ndim - 3) + cast
    raise ValueError(f"Cannot map {len(cast)} transform values onto {ndim} axes.")

_normalize_voxel_size_zyx_um(value) staticmethod

Validate three positive finite ZYX spacings at stored precision.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _normalize_voxel_size_zyx_um(value: ArrayLike) -> list[float]:
    """Validate three positive finite ZYX spacings at stored precision."""
    spacing = round_spacing_um(value)
    if (
        spacing.shape != (3,)
        or not np.all(np.isfinite(spacing))
        or np.any(spacing <= 0)
    ):
        raise ValueError(
            "voxel_size_zyx_um must contain three positive finite ZYX spacings."
        )
    return spacing.tolist()

_parse_datastore(validate=True)

Parse datastore to discover available components.

Parameters:

Name Type Description Default
validate bool

Whether to validate existing zarr arrays while parsing.

True

Returns:

Type Description
None

No return value.

Source code in src/merfish3danalysis/qi2labDataStore.py
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
2441
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
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
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
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
def _parse_datastore(self, validate: bool = True) -> None:
    """
    Parse datastore to discover available components.

    Parameters
    ----------
    validate : bool
        Whether to validate existing zarr arrays while parsing.

    Returns
    -------
    None
        No return value.
    """
    # directory structure as defined by qi2lab spec
    self._datastore_state_json_path = self._datastore_path / Path(
        r"datastore_state.json"
    )
    # read in .json in root directory that indicates what steps have been run
    with open(self._datastore_state_json_path) as json_file:
        self._datastore_state = json.load(json_file)
    if float(self._datastore_state["Version"]) != 0.6:
        raise ValueError("Only datastore version 0.6 is supported by this build.")

    self.fiducial_folder_name = "fiducial"
    self.feature_predictor_folder_name = "feature_predictor"
    self._fiducial_root_path = self._datastore_path / Path(
        self.fiducial_folder_name
    )
    self._feature_predictor_localizations_root_path = self._datastore_path / Path(
        f"{self.feature_predictor_folder_name}_localizations"
    )
    self._calibrations_zarr_path = self._datastore_path / Path(r"calibrations")
    self._readouts_root_path = self._datastore_path / Path(r"readouts")
    self._decoded_root_path = self._datastore_path / Path(r"decoded")
    self._fused_root_path = self._datastore_path / Path(r"fused")
    self._segmentation_root_path = self._datastore_path / Path(r"segmentation")

    # validate calibrations
    if self._datastore_state["Calibrations"]:
        if not (self._calibrations_zarr_path.exists()):
            raise FileNotFoundError("Calibration data directory is missing.")
        attributes = self._load_calibrations_attributes()

        keys_to_check = [
            "num_rounds",
            "num_tiles",
            "channels_in_data",
            "tile_overlap",
            "binning",
            "e_per_ADU",
            "na",
            "ri",
            "exp_order",
            "codebook",
            "num_bits",
            "microscope_type",
            "camera_model",
            "voxel_size_zyx_um",
        ]
        for key in keys_to_check:
            if key not in attributes.keys():
                raise KeyError("Calibration attributes incomplete")

        self._num_rounds = attributes["num_rounds"]
        self._num_tiles = attributes["num_tiles"]
        self._channels_in_data = attributes["channels_in_data"]
        self._tile_overlap = attributes["tile_overlap"]
        self._binning = attributes["binning"]
        self._e_per_ADU = attributes["e_per_ADU"]
        self._na = attributes["na"]
        self._ri = attributes["ri"]
        self._exp_order = attributes["exp_order"]
        self._codebook = attributes["codebook"]
        self._num_bits = attributes["num_bits"]
        self._microscope_type = attributes["microscope_type"]
        self._camera_model = attributes["camera_model"]
        self._voxel_size_zyx_um = self._normalize_voxel_size_zyx_um(
            attributes["voxel_size_zyx_um"]
        )

        if getattr(self, "_exp_order", None) is not None:
            self._experiment_order = self._coerce_experiment_order_dataframe(
                self._exp_order
            )

        if getattr(self, "_num_tiles", None) is not None:
            self._tile_ids = [
                "tile" + str(tile_idx).zfill(4)
                for tile_idx in range(self._num_tiles)
            ]
        if getattr(self, "_num_rounds", None) is not None:
            self._round_ids = [
                "round" + str(round_idx + 1).zfill(3)
                for round_idx in range(self._num_rounds)
            ]
        if getattr(self, "_num_bits", None) is not None:
            self._bit_ids = [
                "bit" + str(bit_idx + 1).zfill(3)
                for bit_idx in range(self._num_bits)
            ]

        if validate:
            psf_root_path = self._calibrations_zarr_path / Path("psf_data")
            try:
                if psf_root_path.exists():

                    def psf_sort_key(path: Path) -> int:
                        """
                        Return the numeric PSF directory index.

                        Parameters
                        ----------
                        path : Path
                            PSF directory path.

                        Returns
                        -------
                        int
                            PSF directory index.
                        """
                        return int(path.name[len("psf_") : len("psf_") + 3])

                    psf_dirs = sorted(
                        [
                            entry
                            for entry in psf_root_path.iterdir()
                            if entry.is_dir()
                            and re.fullmatch(r"psf_\d{3}\.ome\.zarr", entry.name)
                        ],
                        key=psf_sort_key,
                    )
                else:
                    psf_dirs = []

                if len(psf_dirs) > 0:
                    psf_list = []
                    for psf_dir in psf_dirs:
                        psf_array = self._load_from_zarr_array(
                            psf_dir, return_future=False
                        )
                        psf_list.append(np.asarray(psf_array, dtype=np.float32))
                    self._psfs = psf_list
            except (OSError, ValueError):
                print("Calibration psfs missing.")

    # validate fiducial and readout bits data
    if self._datastore_state["Corrected"] and validate:
        if not (self._fiducial_root_path.exists()):
            raise FileNotFoundError("fiducial directory not initialized")
        else:
            fiducial_tile_ids = self._collect_strict_ids(
                self._fiducial_root_path, prefix="tile", width=4
            )
            if len(fiducial_tile_ids) == 0:
                raise FileNotFoundError("No tile folders found under fiducial/")
            current_tile_dir_path = self._fiducial_root_path / Path(
                fiducial_tile_ids[0]
            )
            self._round_ids = self._collect_strict_ids(
                current_tile_dir_path, prefix="round", width=3
            )
        if not (self._readouts_root_path.exists()):
            raise FileNotFoundError("Readout directory not initialized")
        else:
            readout_tile_ids = self._collect_strict_ids(
                self._readouts_root_path, prefix="tile", width=4
            )
            if len(readout_tile_ids) == 0:
                raise FileNotFoundError("No tile folders found under readouts/")
            current_tile_dir_path = self._readouts_root_path / Path(
                readout_tile_ids[0]
            )
            self._bit_ids = self._collect_strict_ids(
                current_tile_dir_path, prefix="bit", width=3
            )
        assert fiducial_tile_ids == readout_tile_ids, (
            "fiducial and readout tile ids do not match. Conversion error."
        )
        self._tile_ids = fiducial_tile_ids.copy()
        del fiducial_tile_ids, readout_tile_ids

        for tile_id, round_id in product(self._tile_ids, self._round_ids):
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            attributes = self._load_entity_attributes(entity_root)

            keys_to_check = [
                "stage_zyx_um",
                "excitation_um",
                "emission_um",
                # "exposure_ms",
                "psf_idx",
            ]

            for key in keys_to_check:
                if key not in attributes.keys():
                    print(tile_id, round_id, key)
                    raise KeyError("Corrected fiducial attributes incomplete")
            if "bit_linker" not in attributes:
                print(tile_id, round_id, "bit_linker")
                raise KeyError("Corrected fiducial attributes incomplete")

            current_local_zarr_path = str(entity_root / Path("corrected_data"))

            try:
                self._check_for_zarr_array(current_local_zarr_path)
            except (OSError, ValueError):
                print(tile_id, round_id)
                print("Corrected fiducial data missing.")

        for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
            entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
            attributes = self._load_entity_attributes(entity_root)

            keys_to_check = [
                "excitation_um",
                "emission_um",
                # "exposure_ms",
                "psf_idx",
            ]
            for key in keys_to_check:
                if key not in attributes.keys():
                    raise KeyError("Corrected readout attributes incomplete")
            if "round_linker" not in attributes:
                raise KeyError("Corrected readout attributes incomplete")

            current_local_zarr_path = str(entity_root / Path("corrected_data"))

            try:
                self._check_for_zarr_array(current_local_zarr_path)
            except (OSError, ValueError):
                print(tile_id, bit_id)
                print("Corrected readout data missing.")

    # check and validate local transform and preprocessing data
    if self._datastore_state["LocalRegistered"] and validate:
        for tile_id, round_id in product(self._tile_ids, self._round_ids):
            entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
            if round_id != self._round_ids[0]:
                attributes = self._load_entity_attributes(entity_root)

                keys_to_check = ["local_round_transform_zyx_um"]

                for key in keys_to_check:
                    if key not in attributes.keys():
                        raise KeyError(
                            f"{round_id, tile_id} local round transform missing"
                        )

                current_local_zarr_path = str(
                    entity_root / Path("opticalflow_xform_px")
                )

                try:
                    self._check_for_zarr_array(current_local_zarr_path)
                except (OSError, ValueError):
                    # print(tile_id, round_id)
                    # print("Optical flow registration data missing.")
                    pass

            corrected_shape = self.image_shape(entity_root / Path("corrected_data"))
            decon_shape = self.image_shape(entity_root / Path("decon_data"))
            if (
                corrected_shape is not None
                and decon_shape is not None
                and corrected_shape != decon_shape
            ):
                raise ValueError(
                    f"{tile_id} {round_id} corrected and decon shapes differ: "
                    f"{corrected_shape} != {decon_shape}"
                )

        for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
            entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
            current_local_zarr_path = str(
                entity_root / Path(f"{self.feature_predictor_folder_name}_data")
            )

            try:
                self._check_for_zarr_array(current_local_zarr_path)
            except (OSError, ValueError):
                print(tile_id, bit_id)
                print("feature_predictor prediction missing.")
            corrected_shape = self.image_shape(entity_root / Path("corrected_data"))
            decon_shape = self.image_shape(entity_root / Path("decon_data"))
            feature_shape = self.image_shape(
                entity_root / Path(f"{self.feature_predictor_folder_name}_data")
            )
            shapes = [
                shape
                for shape in (corrected_shape, decon_shape, feature_shape)
                if shape is not None
            ]
            if len(shapes) > 1 and any(shape != shapes[0] for shape in shapes[1:]):
                raise ValueError(
                    f"{tile_id} {bit_id} corrected/decon/feature image shapes differ: "
                    f"{corrected_shape}, {decon_shape}, {feature_shape}"
                )

        for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
            current_feature_predictor_path = (
                self._feature_predictor_localizations_root_path
                / Path(tile_id)
                / Path(bit_id + ".parquet")
            )
            if not (current_feature_predictor_path.exists()):
                raise FileNotFoundError(
                    tile_id
                    + " "
                    + bit_id
                    + " feature_predictor localization missing"
                )

    # check and validate global registered data
    if self._datastore_state["GlobalRegistered"] and validate:
        for tile_id in self._tile_ids:
            entity_root = (
                self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
            )
            attributes = self._load_entity_attributes(entity_root)

            keys_to_check = ["affine_zyx_um", "origin_zyx_um", "spacing_zyx_um"]

            for key in keys_to_check:
                if key not in attributes.keys():
                    raise KeyError("Global registration missing")

    # check and validate fused
    if self._datastore_state["Fused"] and validate:
        fused_image_path = self._fused_root_path / Path(
            f"fused_{self.fiducial_folder_name}_zyx"
        )
        attributes = self.load_image_metadata(fused_image_path)

        keys_to_check = ["affine_zyx_um", "origin_zyx_um", "spacing_zyx_um"]

        for key in keys_to_check:
            if key not in attributes.keys():
                raise KeyError("Fused image metadata missing")

        current_local_zarr_path = str(fused_image_path)

        try:
            self._check_for_zarr_array(current_local_zarr_path)
        except (OSError, ValueError):
            print("Fused data missing.")

    # check and validate cellpose segmentation
    if self._datastore_state["SegmentedCells"] and validate:
        current_local_zarr_path = str(
            self._segmentation_root_path
            / Path("cellpose")
            / Path(f"masks_{self.fiducial_folder_name}_iso_zyx")
        )

        try:
            self._check_for_zarr_array(current_local_zarr_path)
        except (OSError, ValueError):
            print("Cellpose data missing.")

        cell_outlines_path = (
            self._segmentation_root_path
            / Path("cellpose")
            / Path("imagej_rois")
            / Path("global_coords_rois.zip")
        )
        if not (cell_outlines_path.exists()):
            raise FileNotFoundError("Cellpose cell outlines missing.")

    # check and validate decoded spots
    if self._datastore_state["DecodedSpots"] and validate:
        for tile_id in self._tile_ids:
            decoded_path = self._decoded_root_path / Path(
                tile_id + "_decoded_features.parquet"
            )

            if not (decoded_path.exists()):
                raise FileNotFoundError(tile_id + " decoded spots missing.")

    # check and validate filtered decoded spots
    if self._datastore_state["FilteredSpots"] and validate:
        filtered_path = self._decoded_root_path / Path(
            "all_tiles_filtered_decoded_features.parquet"
        )

        if not (filtered_path.exists()):
            raise FileNotFoundError("filtered decoded spots missing.")

_proseg_3d_root()

Return the root path for Proseg 3D outputs.

Returns:

Type Description
Path

Proseg 3D output root.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _proseg_3d_root(self) -> Path:
    """
    Return the root path for Proseg 3D outputs.

    Returns
    -------
    Path
        Proseg 3D output root.
    """
    return self._datastore_path / Path("proseg") / Path("3D")

_proseg_3d_run_root(run_name=None)

Return one Proseg 3D run root path.

Parameters:

Name Type Description Default
run_name str or None

Proseg run name. None or "default" selects proseg/3D.

None

Returns:

Type Description
Path

Proseg run root path.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _proseg_3d_run_root(self, run_name: str | None = None) -> Path:
    """
    Return one Proseg 3D run root path.

    Parameters
    ----------
    run_name : str or None, default None
        Proseg run name. ``None`` or ``"default"`` selects ``proseg/3D``.

    Returns
    -------
    Path
        Proseg run root path.
    """
    proseg_root = self._proseg_3d_root()
    if run_name is None or run_name == "default":
        return proseg_root
    return proseg_root / Path(run_name)

_resolve_original_tile_position_zyx_um(tile_id, round_id=None, bit_id=None)

Resolve original tile stage position used for OME translation.

Parameters:

Name Type Description Default
tile_id str

Tile identifier.

required
round_id str | None

Optional fiducial round identifier.

None
bit_id str | None

Optional readout bit identifier.

None

Returns:

Type Description
list[float] | None

Original stage position in Z, Y, X microns, if available.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _resolve_original_tile_position_zyx_um(
    self,
    tile_id: str,
    round_id: str | None = None,
    bit_id: str | None = None,
) -> list[float] | None:
    """
    Resolve original tile stage position used for OME translation.

    Parameters
    ----------
    tile_id : str
        Tile identifier.
    round_id : str | None
        Optional fiducial round identifier.
    bit_id : str | None
        Optional readout bit identifier.

    Returns
    -------
    list[float] | None
        Original stage position in Z, Y, X microns, if available.
    """
    if round_id is not None:
        fiducial_entity = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        attrs = self._load_entity_attributes(fiducial_entity)
        stage = attrs.get("stage_zyx_um")
        if stage is not None:
            return self._normalize_stage_position_zyx_um(stage).tolist()

    if bit_id is not None:
        round_linker = self.load_local_round_linker(tile=tile_id, bit=bit_id)
        if round_linker is not None and int(round_linker) > 0:
            linked_round_id = self._round_ids[int(round_linker) - 1]
            fiducial_entity = (
                self._fiducial_root_path / Path(tile_id) / Path(linked_round_id)
            )
            attrs = self._load_entity_attributes(fiducial_entity)
            stage = attrs.get("stage_zyx_um")
            if stage is not None:
                return self._normalize_stage_position_zyx_um(stage).tolist()

    if getattr(self, "_round_ids", None):
        fiducial_entity = (
            self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
        )
        attrs = self._load_entity_attributes(fiducial_entity)
        stage = attrs.get("stage_zyx_um")
        if stage is not None:
            return self._normalize_stage_position_zyx_um(stage).tolist()
    return None

_resolve_reference_tile_position_zyx_um(tile_id)

Resolve the first-round reference stage position for derived outputs.

Parameters:

Name Type Description Default
tile_id str

Tile identifier.

required

Returns:

Type Description
list[float] or None

First fiducial round stage position in Z, Y, X microns.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _resolve_reference_tile_position_zyx_um(
    self, tile_id: str
) -> list[float] | None:
    """
    Resolve the first-round reference stage position for derived outputs.

    Parameters
    ----------
    tile_id : str
        Tile identifier.

    Returns
    -------
    list[float] or None
        First fiducial round stage position in Z, Y, X microns.
    """
    if not getattr(self, "_round_ids", None):
        return None
    return self._resolve_original_tile_position_zyx_um(
        tile_id=tile_id, round_id=self._round_ids[0]
    )

_save_calibrations_attributes(attributes)

Persist calibrations metadata sidecar.

Parameters:

Name Type Description Default
attributes Mapping[str, Any]

Calibration metadata to write.

required

Returns:

Type Description
None

No return value.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _save_calibrations_attributes(self, attributes: Mapping[str, Any]) -> None:
    """
    Persist calibrations metadata sidecar.

    Parameters
    ----------
    attributes : Mapping[str, Any]
        Calibration metadata to write.

    Returns
    -------
    None
        No return value.
    """
    self._save_to_json(
        {str(k): self._to_json_compatible(v) for k, v in dict(attributes).items()},
        self._calibrations_attributes_path(),
    )

_save_default_decode_normalization_metadata(kind, metadata)

Save provenance for default, non-run-scoped normalization vectors.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _save_default_decode_normalization_metadata(
    self,
    kind: str,
    metadata: Mapping[str, Any] | None,
) -> None:
    """Save provenance for default, non-run-scoped normalization vectors."""
    if metadata is None:
        return
    calib_attrs = self._load_calibrations_attributes()
    all_metadata = dict(calib_attrs.get("decode_normalization_metadata", {}))
    all_metadata[kind] = dict(metadata)
    calib_attrs["decode_normalization_metadata"] = all_metadata
    self._save_calibrations_attributes(calib_attrs)

_save_entity_attributes(entity_root_path, updates)

Save metadata to the entity sidecar.

Parameters:

Name Type Description Default
entity_root_path Path | str

Entity folder path.

required
updates Mapping[str, Any]

Metadata updates to persist.

required

Returns:

Type Description
None

No return value.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _save_entity_attributes(
    self,
    entity_root_path: Path | str,
    updates: Mapping[str, Any],
) -> None:
    """
    Save metadata to the entity sidecar.

    Parameters
    ----------
    entity_root_path : Path | str
        Entity folder path.
    updates : Mapping[str, Any]
        Metadata updates to persist.

    Returns
    -------
    None
        No return value.
    """
    if not updates:
        return

    entity_root = Path(entity_root_path)
    payload = {
        str(k): self._to_json_compatible(v) for k, v in dict(updates).items()
    }

    sidecar_path = self._entity_attributes_path(entity_root)
    sidecar_attrs = self._load_from_json(sidecar_path)
    sidecar_attrs.update(payload)
    self._save_to_json(sidecar_attrs, sidecar_path)

_save_to_csv_gz(df, csv_gz_path) staticmethod

Save dataframe to gzipped CSV.

Parameters:

Name Type Description Default
df DataFrame

Dataframe to save.

required
csv_gz_path Path or str

Path to gzipped CSV file.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _save_to_csv_gz(df: pd.DataFrame, csv_gz_path: Path | str) -> None:
    """Save dataframe to gzipped CSV.

    Parameters
    ----------
    df : pd.DataFrame
        Dataframe to save.
    csv_gz_path : Path or str
        Path to gzipped CSV file.
    """
    df.to_csv(csv_gz_path, index=False, compression="gzip")

_save_to_json(dictionary, dictionary_path) staticmethod

Save dictionary to json.

Parameters:

Name Type Description Default
dictionary dict

The data to be saved.

required
dictionary_path Path or str

The path to the JSON file where the data will be saved.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _save_to_json(dictionary: dict, dictionary_path: Path | str) -> None:
    """Save dictionary to json.

    Parameters
    ----------
    dictionary : dict
        The data to be saved.
    dictionary_path : Path or str
        The path to the JSON file where the data will be saved.
    """
    serialized = json.dumps(dictionary, indent=4)
    with open(dictionary_path, "w", encoding="utf-8") as file:
        file.write(serialized)

_save_to_parquet(df, parquet_path) staticmethod

Save dataframe to parquet.

Parameters:

Name Type Description Default
df DataFrame

Dataframe to save.

required
parquet_path Path or str

Path to parquet file.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _save_to_parquet(df: pd.DataFrame, parquet_path: Path | str) -> None:
    """Save dataframe to parquet.

    Parameters
    ----------
    df : pd.DataFrame
        Dataframe to save.
    parquet_path : Path or str
        Path to parquet file.
    """
    df.to_parquet(parquet_path, engine="fastparquet", index=False)

_save_to_zarr_array(array, image_path, return_future=False, *, chunks=None, ome_scale=None, ome_translation=None, extra_attributes=None) staticmethod

Save image data as OME-Zarr v0.5 using yaozarrs tensorstore writer.

Parameters:

Name Type Description Default
array ArrayLike

Array to save.

required
image_path Path or str

Image store path.

required
chunks Sequence[int] or None

Storage chunk shape. None selects the datastore default.

None
ome_scale Sequence[float] or None

Pixel spacing in microns, in image-axis order or ZYX order.

None
ome_translation Sequence[float] or None

Image origin in microns, in image-axis order or ZYX order.

None
extra_attributes Mapping or None

Additional image metadata.

None
return_future bool or None

Return the write-completion handle (True), or wait for the write to finish and return None (False or None).

False

Returns:

Name Type Description
write_future WriteFutures or None

Pixel-write completion handle when return_future is True.

Raises:

Type Description
(OSError, ValueError)

Storage or metadata errors. Failed writes are not reported as success.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _save_to_zarr_array(
    array: ArrayLike,
    image_path: Path | str,
    return_future: bool | None = False,
    *,
    chunks: Sequence[int] | None = None,
    ome_scale: Sequence[float] | None = None,
    ome_translation: Sequence[float] | None = None,
    extra_attributes: Mapping[str, Any] | None = None,
) -> "WriteFutures | None":
    """Save image data as OME-Zarr v0.5 using yaozarrs tensorstore writer.

    Parameters
    ----------
    array : ArrayLike
        Array to save.
    image_path : Path or str
        Image store path.
    chunks : Sequence[int] or None
        Storage chunk shape. None selects the datastore default.
    ome_scale : Sequence[float] or None
        Pixel spacing in microns, in image-axis order or ZYX order.
    ome_translation : Sequence[float] or None
        Image origin in microns, in image-axis order or ZYX order.
    extra_attributes : Mapping or None
        Additional image metadata.
    return_future : bool or None
        Return the write-completion handle (True), or wait for the write
        to finish and return None (False or None).

    Returns
    -------
    write_future : tensorstore.WriteFutures or None
        Pixel-write completion handle when return_future is True.

    Raises
    ------
    OSError, ValueError
        Storage or metadata errors. Failed writes are not reported as success.
    """
    image_path = qi2labDataStore._image_store_path(image_path)
    image_path.parent.mkdir(parents=True, exist_ok=True)

    image_array = np.asarray(array)
    if image_array.dtype == np.float64:
        image_array = image_array.astype(np.float32)

    if image_array.ndim < 2 or image_array.ndim > 5:
        raise ValueError(
            f"Unsupported array ndim for image write: {image_array.ndim}"
        )

    if chunks is None:
        chunks = qi2labDataStore._default_chunks(image_array)
    scale = qi2labDataStore._normalize_transform(ome_scale, image_array.ndim, 1.0)
    translation = qi2labDataStore._normalize_transform(
        ome_translation, image_array.ndim, 0.0
    )

    axes = qi2labDataStore._build_axes(v05, image_array.ndim)
    scale[-3:] = round_spacing_um(scale[-3:]).tolist()
    transforms = [
        v05.ScaleTransformation(scale=scale),
        v05.TranslationTransformation(translation=translation),
    ]
    datasets = [v05.Dataset(path="0", coordinateTransformations=transforms)]
    multiscales = [v05.Multiscale(axes=axes, datasets=datasets)]

    image_metadata = v05.Image(multiscales=multiscales)

    chunk_spec = tuple(int(c) for c in chunks)
    write_options = {
        "extra_attributes": qi2labDataStore._to_json_compatible(extra_attributes)
        if extra_attributes
        else None,
        "writer": qi2labDataStore._create_array_tensorstore_qi2lab,
        "overwrite": True,
        "chunks": chunk_spec,
        "compression": "blosc-zstd",
    }
    if return_future:
        from yaozarrs.write.v05 import prepare_image

        # yaozarrs creates the complete OME-Zarr v3 structure. Its write_image
        # API is synchronous; writing the prepared array is necessary to
        # preserve the datastore's TensorStore write-completion handle.
        _, arrays = prepare_image(
            dest=str(image_path),
            image=image_metadata,
            datasets=(image_array.shape, image_array.dtype),
            **write_options,
        )
        return arrays["0"].write(image_array)
    write_image(
        dest=str(image_path),
        image=image_metadata,
        datasets=image_array,
        **write_options,
    )
    return None

_set_calibration_attribute(key, value)

Update one calibration metadata field.

Parameters:

Name Type Description Default
key str

Calibration metadata key.

required
value Any

Value to store after JSON conversion.

required

Returns:

Type Description
None

No return value.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _set_calibration_attribute(self, key: str, value: Any) -> None:
    """
    Update one calibration metadata field.

    Parameters
    ----------
    key : str
        Calibration metadata key.
    value : Any
        Value to store after JSON conversion.

    Returns
    -------
    None
        No return value.
    """
    attributes = self._load_calibrations_attributes()
    attributes[str(key)] = self._to_json_compatible(value)
    self._save_calibrations_attributes(attributes)

_strict_id_sort_key(name, prefix, width) staticmethod

Validate and parse strict zero-padded identifiers.

Parameters:

Name Type Description Default
name str

Identifier to validate.

required
prefix str

Required identifier prefix.

required
width int

Required number of zero-padded digits.

required

Returns:

Type Description
int

Parsed numeric identifier.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _strict_id_sort_key(name: str, prefix: str, width: int) -> int:
    """
    Validate and parse strict zero-padded identifiers.

    Parameters
    ----------
    name : str
        Identifier to validate.
    prefix : str
        Required identifier prefix.
    width : int
        Required number of zero-padded digits.

    Returns
    -------
    int
        Parsed numeric identifier.
    """
    match = re.fullmatch(rf"{re.escape(prefix)}(\d{{{width}}})", name)
    if match is None:
        raise ValueError(
            f"Invalid identifier '{name}'. Expected '{prefix}' followed by {width} digits."
        )
    return int(match.group(1))

_to_json_compatible(value) staticmethod

Convert numpy/scalar containers to JSON-compatible values.

Parameters:

Name Type Description Default
value Any

Value to convert before JSON serialization.

required

Returns:

Type Description
Any

JSON-compatible representation.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _to_json_compatible(value: Any) -> Any:
    """
    Convert numpy/scalar containers to JSON-compatible values.

    Parameters
    ----------
    value : Any
        Value to convert before JSON serialization.

    Returns
    -------
    Any
        JSON-compatible representation.
    """
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, np.generic):
        return value.item()
    if isinstance(value, Mapping):
        return {
            str(k): qi2labDataStore._to_json_compatible(v) for k, v in value.items()
        }
    if isinstance(value, tuple):
        return [qi2labDataStore._to_json_compatible(v) for v in value]
    if isinstance(value, list):
        return [qi2labDataStore._to_json_compatible(v) for v in value]
    return value

_update_image_translation_transform(image_root, stage_zyx_um)

Update an existing OME-Zarr image translation transform.

Parameters:

Name Type Description Default
image_root Path

Image root path, without or with the .ome.zarr suffix.

required
stage_zyx_um Sequence[float]

Physical Z, Y, X translation to write into the image metadata.

required

Returns:

Type Description
None

The image metadata is updated in place when it already exists.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _update_image_translation_transform(
    self,
    image_root: Path,
    stage_zyx_um: Sequence[float],
) -> None:
    """
    Update an existing OME-Zarr image translation transform.

    Parameters
    ----------
    image_root : Path
        Image root path, without or with the ``.ome.zarr`` suffix.
    stage_zyx_um : Sequence[float]
        Physical Z, Y, X translation to write into the image metadata.

    Returns
    -------
    None
        The image metadata is updated in place when it already exists.
    """
    image_path = self._image_store_path(image_root)
    metadata_path = image_path / Path("zarr.json")
    if not metadata_path.exists():
        return

    metadata = open_group(image_path).metadata.model_dump(
        mode="json", exclude_none=True
    )

    transforms = (
        metadata.get("attributes", {})
        .get("ome", {})
        .get("multiscales", [{}])[0]
        .get("datasets", [{}])[0]
        .get("coordinateTransformations", [])
    )
    for transform in transforms:
        if transform.get("type") == "translation":
            transform["translation"] = [float(v) for v in stage_zyx_um]
            self._save_to_json(metadata, metadata_path)
            return

_validate_core_image_shape(entity_root_path, image_name, image)

Enforce corrected/deconvolved/feature image shape consistency.

Parameters:

Name Type Description Default
entity_root_path Path | str

Entity folder path.

required
image_name str

Logical image name being validated.

required
image ArrayLike

Image data to validate.

required

Returns:

Type Description
None

No return value.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _validate_core_image_shape(
    self,
    entity_root_path: Path | str,
    image_name: str,
    image: ArrayLike,
) -> None:
    """
    Enforce corrected/deconvolved/feature image shape consistency.

    Parameters
    ----------
    entity_root_path : Path | str
        Entity folder path.
    image_name : str
        Logical image name being validated.
    image : ArrayLike
        Image data to validate.

    Returns
    -------
    None
        No return value.
    """
    entity_root = Path(entity_root_path)
    shape = tuple(int(v) for v in np.asarray(image).shape)
    required_names = {
        "corrected_data",
        "decon_data",
        f"{self.feature_predictor_folder_name}_data",
    }
    for candidate_name in required_names:
        if candidate_name == image_name:
            continue
        candidate_shape = self.image_shape(entity_root / Path(candidate_name))
        if candidate_shape is None:
            continue
        if tuple(candidate_shape) != shape:
            raise ValueError(
                f"Image shape mismatch in {entity_root.name}: "
                f"{image_name}={shape} but {candidate_name}={candidate_shape}. "
                "corrected_data, optional decon_data, and "
                "feature_predictor_data must match."
            )

_validate_decode_run_key(decode_run_key) staticmethod

Validate an optional decoded-output run key.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional subfolder name under decoded-output roots.

required

Returns:

Type Description
str or None

Validated run key.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _validate_decode_run_key(decode_run_key: str | None) -> str | None:
    """
    Validate an optional decoded-output run key.

    Parameters
    ----------
    decode_run_key : str or None
        Optional subfolder name under decoded-output roots.

    Returns
    -------
    str or None
        Validated run key.
    """
    if decode_run_key is None:
        return None
    decode_run_key = str(decode_run_key)
    if not re.fullmatch(r"[A-Za-z0-9_.-]+", decode_run_key):
        raise ValueError(
            "decode_run_key may only contain letters, numbers, '.', '_', and '-'."
        )
    return decode_run_key

baysor_3d_available()

Return whether Baysor 3D molecules and cell boundaries are present.

Source code in src/merfish3danalysis/qi2labDataStore.py
def baysor_3d_available(self) -> bool:
    """Return whether Baysor 3D molecules and cell boundaries are present."""
    baysor_root = self._segmentation_root_path / Path("baysor") / Path("3D")
    return (baysor_root / Path("molecules.parquet")).exists() and (
        baysor_root / Path("cell_boundaries_3d.parquet")
    ).exists()

decoded_temporary_dir(decode_run_key=None, iteration=None)

Return the temporary decoded-output directory for a decode run.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional decoded-output run key.

None
iteration int or None

Optional optimization iteration index.

None

Returns:

Type Description
Path

Temporary decoded-output directory.

Source code in src/merfish3danalysis/qi2labDataStore.py
def decoded_temporary_dir(
    self,
    decode_run_key: str | None = None,
    iteration: int | None = None,
) -> Path:
    """
    Return the temporary decoded-output directory for a decode run.

    Parameters
    ----------
    decode_run_key : str or None, default None
        Optional decoded-output run key.
    iteration : int or None, default None
        Optional optimization iteration index.

    Returns
    -------
    pathlib.Path
        Temporary decoded-output directory.
    """
    root = self._decoded_run_root(decode_run_key) / Path("temporary")
    if iteration is not None:
        root = root / Path(f"iteration_{int(iteration):03d}")
    return root

fused_image_path(image_name=None)

Return the OME-Zarr path for a fused image.

Parameters:

Name Type Description Default
image_name str or None

Logical image name. None selects the fused fiducial volume.

None

Returns:

Type Description
Path

Fused image directory, without opening or creating it.

Source code in src/merfish3danalysis/qi2labDataStore.py
def fused_image_path(self, image_name: str | None = None) -> Path:
    """Return the OME-Zarr path for a fused image.

    Parameters
    ----------
    image_name : str or None
        Logical image name. None selects the fused fiducial volume.

    Returns
    -------
    Path
        Fused image directory, without opening or creating it.
    """
    if image_name is None:
        image_name = f"fused_{self.fiducial_folder_name}_zyx"
    return self._image_store_path(self._fused_root_path / image_name)

image_shape(image_path) staticmethod

Read image shape without loading all pixels.

Parameters:

Name Type Description Default
image_path Path | str

Image store path.

required

Returns:

Type Description
tuple[int, ...] | None

Image array shape, or None when the image is unavailable.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def image_shape(image_path: Path | str) -> tuple[int, ...] | None:
    """
    Read image shape without loading all pixels.

    Parameters
    ----------
    image_path : Path | str
        Image store path.

    Returns
    -------
    tuple[int, ...] | None
        Image array shape, or ``None`` when the image is unavailable.
    """
    path = qi2labDataStore._image_store_path(image_path)
    if not path.exists():
        return None

    try:
        group = open_group(str(path))
        array_0 = group["0"]
        shape = array_0.metadata.shape
        return tuple(int(dim) for dim in shape)
    except (FileNotFoundError, KeyError):
        return None

initialize_tile(tile)

Initialize directory structure for a tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def initialize_tile(
    self,
    tile: int | str,
) -> None:
    """Initialize directory structure for a tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    """
    if getattr(self, "_experiment_order", None) is None:
        print("Assign experimental order before creating tiles.")
        return None

    if getattr(self, "_num_tiles", None) is None:
        print("Assign number of tiles before creating tiles.")
        return None

    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tile id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    try:
        fiducial_tile_path = self._fiducial_root_path / Path(tile_id)
        fiducial_tile_path.mkdir()
        for round_idx, round_id in enumerate(self._round_ids):
            fiducial_round_path = fiducial_tile_path / Path(round_id)
            fiducial_round_path.mkdir()
            fiducial_round_attrs_path = self._entity_attributes_path(
                fiducial_round_path
            )
            round_attrs = {
                "bit_linker": self._experiment_order.to_numpy()[round_idx, 1:]
                .astype(int)
                .tolist(),
            }
            self._save_to_json(round_attrs, fiducial_round_attrs_path)
    except FileExistsError:
        print("Error creating fiducial tile. Does it exist already?")

    try:
        readout_tile_path = self._readouts_root_path / Path(tile_id)
        readout_tile_path.mkdir()
        for bit_idx, bit_id in enumerate(self._bit_ids):
            readout_bit_path = readout_tile_path / Path(bit_id)
            readout_bit_path.mkdir()
            readout_bit_attrs_path = self._entity_attributes_path(readout_bit_path)
            fiducial_channel = str(self._channels_in_data[0])
            readout_one_channel = str(self._channels_in_data[1])

            if len(self._channels_in_data) == 3:
                readout_two_channel = str(self._channels_in_data[2])
                condition_one = self._experiment_order[readout_one_channel] == (
                    bit_idx + 1
                )
                condition_two = self._experiment_order[readout_two_channel] == (
                    bit_idx + 1
                )
                combined_condition = condition_one | condition_two

            else:
                combined_condition = self._experiment_order[
                    readout_one_channel
                ] == (bit_idx + 1)
            matching_rows = self._experiment_order.loc[combined_condition]

            bit_attrs = {
                "round_linker": int(matching_rows[fiducial_channel].values[0])
            }
            self._save_to_json(bit_attrs, readout_bit_attrs_path)
    except FileExistsError:
        print("Error creating readout tile. Does it exist already?")

list_proseg_3d_runs()

List available Proseg 3D output runs.

Returns:

Name Type Description
proseg_runs list[str]

Available Proseg 3D run names. The direct proseg/3D output is named "default".

Source code in src/merfish3danalysis/qi2labDataStore.py
def list_proseg_3d_runs(self) -> list[str]:
    """List available Proseg 3D output runs.

    Returns
    -------
    proseg_runs : list[str]
        Available Proseg 3D run names. The direct ``proseg/3D`` output is
        named ``"default"``.
    """
    proseg_root = self._proseg_3d_root()
    if not proseg_root.exists():
        return []

    run_names: list[str] = []
    candidate_roots = [proseg_root]
    candidate_roots.extend(
        path for path in sorted(proseg_root.iterdir()) if path.is_dir()
    )
    for root in candidate_roots:
        transcript_path = root / Path("transcript_metadata_3D.csv.gz")
        polygon_path = root / Path("cell_polygons_3D.geojson.gz")
        if transcript_path.exists() and polygon_path.exists():
            run_names.append("default" if root == proseg_root else root.name)
    return sorted(run_names)

load_baysor_cell_boundaries_3d()

Load Baysor 3D cell boundary polygons.

Returns:

Type Description
DataFrame or None

Baysor cell boundary table, if present.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_baysor_cell_boundaries_3d(self) -> pd.DataFrame | None:
    """
    Load Baysor 3D cell boundary polygons.

    Returns
    -------
    pandas.DataFrame or None
        Baysor cell boundary table, if present.
    """
    boundaries_path = (
        self._segmentation_root_path
        / Path("baysor")
        / Path("3D")
        / Path("cell_boundaries_3d.parquet")
    )
    if not boundaries_path.exists():
        print("Baysor cell boundaries not found.")
        return None
    try:
        return self._load_from_parquet(boundaries_path)
    except (OSError, ValueError) as exc:
        print(exc)
        print("Error loading Baysor cell boundaries.")
        return None

load_baysor_molecules_3d()

Load Baysor 3D molecule assignments.

Returns:

Type Description
DataFrame or None

Baysor molecule table, if present.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_baysor_molecules_3d(self) -> pd.DataFrame | None:
    """
    Load Baysor 3D molecule assignments.

    Returns
    -------
    pandas.DataFrame or None
        Baysor molecule table, if present.
    """
    molecules_path = (
        self._segmentation_root_path
        / Path("baysor")
        / Path("3D")
        / Path("molecules.parquet")
    )
    if not molecules_path.exists():
        print("Baysor molecules not found.")
        return None
    try:
        return self._load_from_parquet(molecules_path)
    except (OSError, ValueError) as exc:
        print(exc)
        print("Error loading Baysor molecules.")
        return None

load_chromatic_affine_transform_zyx_um(channel_name=None, channel_index=None, wavelength_um=None)

Load one chromatic affine transform with identity fallback.

Parameters:

Name Type Description Default
channel_name str or None

Channel name from the calibration metadata.

None
channel_index int or None

Channel index from the calibration metadata.

None
wavelength_um float or None

Channel wavelength in microns. Used only when channel name/index do not find a match.

None

Returns:

Type Description
ndarray

4x4 affine matrix in physical Z, Y, X microns. Identity is returned if the calibration or requested channel is absent.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_chromatic_affine_transform_zyx_um(
    self,
    channel_name: str | None = None,
    channel_index: int | None = None,
    wavelength_um: float | None = None,
) -> np.ndarray:
    """
    Load one chromatic affine transform with identity fallback.

    Parameters
    ----------
    channel_name : str or None, default=None
        Channel name from the calibration metadata.
    channel_index : int or None, default=None
        Channel index from the calibration metadata.
    wavelength_um : float or None, default=None
        Channel wavelength in microns. Used only when channel name/index do
        not find a match.

    Returns
    -------
    numpy.ndarray
        4x4 affine matrix in physical Z, Y, X microns. Identity is returned
        if the calibration or requested channel is absent.
    """
    calibration = self.load_chromatic_affine_transforms_zyx_um()
    channels = calibration.get("channels", {})
    if not isinstance(channels, Mapping):
        return np.eye(4, dtype=np.float32)

    candidates = []
    if channel_name is not None:
        channel = channels.get(str(channel_name))
        if isinstance(channel, Mapping):
            candidates.append(channel)
    if channel_index is not None:
        for channel in channels.values():
            if isinstance(channel, Mapping) and int(
                channel.get("channel_index", -1)
            ) == int(channel_index):
                candidates.append(channel)
    if wavelength_um is not None:
        wavelength = float(wavelength_um)
        for channel in channels.values():
            if not isinstance(channel, Mapping):
                continue
            stored = channel.get("wavelength_um")
            if stored is not None and np.isclose(float(stored), wavelength):
                candidates.append(channel)

    for channel in candidates:
        affine = channel.get("affine_zyx_um")
        if affine is not None:
            return np.asarray(affine, dtype=np.float32)
    return np.eye(4, dtype=np.float32)

load_chromatic_affine_transforms_zyx_um()

Load chromatic affine calibration metadata.

Returns:

Type Description
dict[str, Any]

Stored calibration metadata. Returns an empty dictionary when no chromatic calibration is present.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_chromatic_affine_transforms_zyx_um(self) -> dict[str, Any]:
    """
    Load chromatic affine calibration metadata.

    Returns
    -------
    dict[str, Any]
        Stored calibration metadata. Returns an empty dictionary when no
        chromatic calibration is present.
    """
    try:
        attributes = self._load_calibrations_attributes()
    except (FileNotFoundError, json.JSONDecodeError, ValueError):
        return {}
    calibration = attributes.get("chromatic_affine_transforms_zyx_um", {})
    if isinstance(calibration, dict):
        if "voxel_size_zyx_um" in calibration:
            calibration["voxel_size_zyx_um"] = round_spacing_um(
                calibration["voxel_size_zyx_um"]
            ).tolist()
        return calibration
    return {}

load_codebook_parsed()

Load and split codebook into gene_ids and codebook matrix.

Returns:

Name Type Description
gene_ids Collection[str]

Gene IDs.

codebook_matrix ArrayLike

Codebook matrix.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_codebook_parsed(
    self,
) -> tuple[Collection[str], ArrayLike] | None:
    """Load and split codebook into gene_ids and codebook matrix.

    Returns
    -------
    gene_ids : Collection[str]
        Gene IDs.
    codebook_matrix : ArrayLike
        Codebook matrix.
    """
    try:
        data = getattr(self, "_codebook", None)

        if data is None:
            return None
        num_columns = len(data[0]) if data else 0
        columns = ["gene_id"] + [f"bit{i:02d}" for i in range(1, num_columns)]
        codebook_df = pd.DataFrame(data, columns=columns)

        gene_ids = codebook_df.iloc[:, 0].tolist()
        codebook_matrix = codebook_df.iloc[:, 1:].to_numpy().astype(int)
        del data, codebook_df
        return gene_ids, codebook_matrix
    except (KeyError, ValueError, TypeError):
        print("Error parsing codebook.")
        return None

load_coord_of_xform_px(tile, round, return_future=True)

Local fiducial optical flow matrix for one round and tile.

Parameters:

Name Type Description Default
tile int or str or None

Tile index or tile id.

required
round int or str or None

Round index or round id.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Name Type Description
of_xform_px ndarray or Future or TensorStore

Local fiducial optical flow matrix for one round and tile.

block_size ndarray

Block size used for the pixel warp.

block_stride ndarray

Block stride used for the pixel warp.

Returns None when the image or required metadata is unavailable.
Source code in src/merfish3danalysis/qi2labDataStore.py
def load_coord_of_xform_px(
    self,
    tile: int | str | None,
    round: int | str | None,
    return_future: bool | None = True,
) -> "tuple[np.ndarray | Future | TensorStore, np.ndarray, np.ndarray] | None":
    """Local fiducial optical flow matrix for one round and tile.

    Parameters
    ----------
    tile : int or str or None
        Tile index or tile id.
    round : int or str or None
        Round index or round id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    of_xform_px : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore
        Local fiducial optical flow matrix for one round and tile.
    block_size : numpy.ndarray
        Block size used for the pixel warp.
    block_stride : numpy.ndarray
        Block stride used for the pixel warp.

    Returns None when the image or required metadata is unavailable.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
    current_local_zarr_path = entity_root / Path("opticalflow_xform_px")

    image_path = self._image_store_path(current_local_zarr_path)
    if not image_path.exists():
        print("Optical flow transform mapping back to first round not found.")
        return None

    try:
        of_xform_px = self._load_from_zarr_array(image_path, return_future)
        attributes = self._load_entity_attributes(
            entity_root, image_names=("opticalflow_xform_px",)
        )
        block_size = np.asarray(attributes["block_size"], dtype=np.float32)
        block_stride = np.asarray(attributes["block_stride"], dtype=np.float32)

        return (of_xform_px, block_size, block_stride)
    except (OSError, ValueError, KeyError) as e:
        print(e)
        print("Error loading optical flow transform.")
        return None

load_decode_normalization_metadata(decode_run_key, kind)

Load provenance for default or run-scoped normalization vectors.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_decode_normalization_metadata(
    self,
    decode_run_key: str | None,
    kind: str,
) -> dict[str, Any] | None:
    """Load provenance for default or run-scoped normalization vectors."""
    if kind not in {"global", "iterative"}:
        raise ValueError("kind must be one of 'global' or 'iterative'.")
    calib_attrs = self._load_calibrations_attributes()
    if decode_run_key is None:
        metadata = calib_attrs.get("decode_normalization_metadata", {}).get(kind)
    else:
        decode_run_key = self._validate_decode_run_key(decode_run_key)
        metadata = (
            calib_attrs.get("decode_normalization_runs", {})
            .get(decode_run_key, {})
            .get(f"{kind}_metadata")
        )
    return dict(metadata) if isinstance(metadata, Mapping) else None

load_decode_normalization_vectors(decode_run_key, kind)

Load run-scoped normalization and background vectors.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional decoded-output run key. None reads the default vectors.

required
kind ('global', iterative)

Normalization vector kind.

'global'

Returns:

Type Description
tuple[ndarray or None, ndarray or None]

Normalization and background vectors.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_decode_normalization_vectors(
    self,
    decode_run_key: str | None,
    kind: str,
) -> tuple[np.ndarray | None, np.ndarray | None]:
    """
    Load run-scoped normalization and background vectors.

    Parameters
    ----------
    decode_run_key : str or None
        Optional decoded-output run key. None reads the default vectors.
    kind : {'global', 'iterative'}
        Normalization vector kind.

    Returns
    -------
    tuple[numpy.ndarray or None, numpy.ndarray or None]
        Normalization and background vectors.
    """
    if kind == "global":
        if decode_run_key is None:
            return self.global_normalization_vector, self.global_background_vector
        norm_key = "global_normalization_vector"
        background_key = "global_background_vector"
    elif kind == "iterative":
        if decode_run_key is None:
            return (
                self.iterative_normalization_vector,
                self.iterative_background_vector,
            )
        norm_key = "iterative_normalization_vector"
        background_key = "iterative_background_vector"
    else:
        raise ValueError("kind must be one of 'global' or 'iterative'.")

    decode_run_key = self._validate_decode_run_key(decode_run_key)
    calib_attrs = self._load_calibrations_attributes()
    run_attrs = calib_attrs.get("decode_normalization_runs", {}).get(
        decode_run_key, {}
    )
    normalization_vector = run_attrs.get(norm_key)
    background_vector = run_attrs.get(background_key)
    if normalization_vector is None or background_vector is None:
        return None, None
    return (
        np.asarray(normalization_vector, dtype=np.float32),
        np.asarray(background_vector, dtype=np.float32),
    )

load_global_cellpose_outlines()

Load Cellpose max projection cell outlines.

Returns:

Name Type Description
cellpose_outlines dict or None

Cellpose cell mask outlines.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_cellpose_outlines(
    self,
) -> dict | None:
    """Load Cellpose max projection cell outlines.

    Returns
    -------
    cellpose_outlines : dict or None
        Cellpose cell mask outlines.
    """
    current_cellpose_outlines_path = (
        self._segmentation_root_path / Path("cellpose") / Path("cell_outlines.json")
    )

    if not current_cellpose_outlines_path.exists():
        print("Cellpose cell mask outlines not found.")
        return None
    else:
        cellpose_outlines = self._load_from_microjson(
            current_cellpose_outlines_path
        )
        return cellpose_outlines

load_global_cellpose_roi_zip()

Load global Cellpose outlines from an ImageJ ROI zip.

Returns:

Name Type Description
cellpose_outlines dict[int, ArrayLike] or None

Cellpose ROI outlines with global X, Y coordinates.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_cellpose_roi_zip(
    self,
) -> dict[int, ArrayLike] | None:
    """Load global Cellpose outlines from an ImageJ ROI zip.

    Returns
    -------
    cellpose_outlines : dict[int, ArrayLike] or None
        Cellpose ROI outlines with global X, Y coordinates.
    """
    roi_path = (
        self._segmentation_root_path
        / Path("cellpose")
        / Path("imagej_rois")
        / Path("global_coords_rois.zip")
    )
    if not roi_path.exists():
        print("Cellpose global ROI zip not found.")
        return None

    try:
        from roifile import roiread
    except ImportError:
        print("roifile is required to load Cellpose ROI zip.")
        return None

    outlines: dict[int, ArrayLike] = {}
    try:
        for idx, roi in enumerate(roiread(roi_path)):
            coordinates = getattr(roi, "subpixel_coordinates", None)
            if coordinates is None:
                coordinates = roi.coordinates()
            if coordinates is not None:
                outlines[idx + 1] = np.asarray(coordinates, dtype=float)
        return outlines
    except (OSError, ValueError) as exc:
        print(exc)
        print("Error loading Cellpose ROI zip.")
        return None

load_global_cellpose_segmentation_image(return_future=True)

Load Cellpose max projection, downsampled segmentation image.

Parameters:

Name Type Description Default
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Name Type Description
fused_image ndarray or Future or TensorStore or None

Cellpose max projection, downsampled segmentation image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_cellpose_segmentation_image(
    self,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load Cellpose max projection, downsampled segmentation image.

    Parameters
    ----------
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    fused_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Cellpose max projection, downsampled segmentation image.
    """
    current_local_zarr_path = (
        self._segmentation_root_path
        / Path("cellpose")
        / Path(f"masks_{self.fiducial_folder_name}_iso_zyx")
    )

    image_path = self._image_store_path(current_local_zarr_path)
    if not image_path.exists():
        print("Cellpose prediction on global fused image not found.")
        return None

    try:
        fused_image = self._load_from_zarr_array(image_path, return_future)
        return fused_image
    except (OSError, ValueError):
        print("Error loading Cellpose image.")
        return None

load_global_coord_xforms_um(tile)

Load global registration transform for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required

Returns:

Name Type Description
affine_zyx_um ArrayLike or None

Global affine registration transform for one tile.

origin_zyx_um ArrayLike or None

Global origin registration transform for one tile.

spacing_zyx_um ArrayLike or None

Global spacing registration transform for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_coord_xforms_um(
    self,
    tile: int | str,
) -> tuple[ArrayLike | None, ArrayLike | None, ArrayLike | None] | None:
    """Load global registration transform for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.

    Returns
    -------
    affine_zyx_um : ArrayLike or None
        Global affine registration transform for one tile.
    origin_zyx_um : ArrayLike or None
        Global origin registration transform for one tile.
    spacing_zyx_um : ArrayLike or None
        Global spacing registration transform for one tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None, None, None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None, None, None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    try:
        entity_root = (
            self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
        )
        attributes = self._load_entity_attributes(entity_root)
        affine_zyx_um = np.asarray(attributes["affine_zyx_um"], dtype=np.float32)
        origin_zyx_um = np.asarray(attributes["origin_zyx_um"], dtype=np.float32)
        spacing_zyx_um = round_spacing_um(attributes["spacing_zyx_um"])
        return (affine_zyx_um, origin_zyx_um, spacing_zyx_um)
    except (FileNotFoundError, json.JSONDecodeError, KeyError):
        print(tile_id, self._round_ids[0])
        print("Global coordinate transforms not found")
        return None, None, None

load_global_fiducial_image(return_future=True)

Load downsampled, fused fiducial image.

Parameters:

Name Type Description Default
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Name Type Description
fused_image ndarray or Future or TensorStore or None

Downsampled, fused fiducial image.

affine_zyx_um ArrayLike or None

Global affine registration transform for fused image.

origin_zyx_um ArrayLike or None

Global origin registration transform for fused image.

spacing_zyx_um ArrayLike or None

Global spacing registration transform for fused image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_fiducial_image(
    self,
    return_future: bool | None = True,
) -> "tuple[np.ndarray | Future | TensorStore, ArrayLike, ArrayLike, ArrayLike] | None":
    """Load downsampled, fused fiducial image.

    Parameters
    ----------
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    fused_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Downsampled, fused fiducial image.
    affine_zyx_um : ArrayLike or None
        Global affine registration transform for fused image.
    origin_zyx_um : ArrayLike or None
        Global origin registration transform for fused image.
    spacing_zyx_um : ArrayLike or None
        Global spacing registration transform for fused image.
    """
    current_local_zarr_path = self._fused_root_path / Path(
        f"fused_{self.fiducial_folder_name}_zyx"
    )

    image_path = self._image_store_path(current_local_zarr_path)
    if not image_path.exists():
        print("Globally registered, fused image not found.")
        return None

    try:
        fused_image = self._load_from_zarr_array(image_path, return_future)
        attributes = self.load_image_metadata(image_path)
        affine_zyx_um = np.asarray(attributes["affine_zyx_um"], dtype=np.float32)
        origin_zyx_um = np.asarray(attributes["origin_zyx_um"], dtype=np.float32)
        spacing_zyx_um = round_spacing_um(attributes["spacing_zyx_um"])
        return fused_image, affine_zyx_um, origin_zyx_um, spacing_zyx_um
    except (OSError, ValueError, KeyError):
        print("Error loading globally registered, fused image.")
        return None

load_global_filtered_decoded_spots(decode_run_key=None, gene_ids=None, columns=None)

Load all decoded and filtered spots.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional decoded-output run key.

None
gene_ids Collection[str] or None

Optional gene ids to load.

None
columns Collection[str] or None

Optional columns to load.

None

Returns:

Name Type Description
all_tiles_filtered DataFrame or None

All decoded and filtered spots.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_filtered_decoded_spots(
    self,
    decode_run_key: str | None = None,
    gene_ids: Collection[str] | None = None,
    columns: Collection[str] | None = None,
) -> pd.DataFrame | None:
    """Load all decoded and filtered spots.

    Parameters
    ----------
    decode_run_key : str or None, default None
        Optional decoded-output run key.
    gene_ids : Collection[str] or None, default None
        Optional gene ids to load.
    columns : Collection[str] or None, default None
        Optional columns to load.

    Returns
    -------
    all_tiles_filtered : pandas.DataFrame or None
        All decoded and filtered spots.
    """
    current_global_filtered_decoded_dir_path = self._global_filtered_decoded_root(
        decode_run_key
    )
    current_global_filtered_decoded_path = (
        current_global_filtered_decoded_dir_path / Path("decoded_features.parquet")
    )

    if not current_global_filtered_decoded_path.exists():
        print("Global, filtered, decoded spots not found.")
        return None
    elif gene_ids is not None or columns is not None:
        selected_gene_ids = (
            [str(gene_id) for gene_id in gene_ids] if gene_ids is not None else []
        )
        filters = (
            [("gene_id", "in", selected_gene_ids)] if gene_ids is not None else None
        )
        all_tiles_filtered = pd.read_parquet(
            current_global_filtered_decoded_path,
            columns=None if columns is None else list(columns),
            filters=filters,
        )
        if gene_ids is not None and "gene_id" in all_tiles_filtered.columns:
            all_tiles_filtered = all_tiles_filtered[
                all_tiles_filtered["gene_id"].astype(str).isin(selected_gene_ids)
            ]
        return all_tiles_filtered
    else:
        all_tiles_filtered = self._load_from_parquet(
            current_global_filtered_decoded_path
        )
        return all_tiles_filtered

load_image_metadata(image_path) staticmethod

Load extra attributes through yaozarrs.

Parameters:

Name Type Description Default
image_path Path | str

Image store path.

required

Returns:

Type Description
dict[str, Any]

Extra attributes stored on the image root.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def load_image_metadata(image_path: Path | str) -> dict[str, Any]:
    """
    Load extra attributes through yaozarrs.

    Parameters
    ----------
    image_path : Path | str
        Image store path.

    Returns
    -------
    dict[str, Any]
        Extra attributes stored on the image root.
    """
    image_root = qi2labDataStore._image_store_path(image_path)
    attrs = dict(open_group(str(image_root)).attrs)
    attrs.pop("ome", None)
    for key in ("spacing_zyx_um", "voxel_size_zyx_um"):
        if key in attrs:
            attrs[key] = round_spacing_um(attrs[key]).tolist()
    return attrs

load_local_bit_linker(tile, round)

Load readout bits linked to fiducial round for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required

Returns:

Name Type Description
bit_linker Sequence[int] or None

Readout bits linked to fiducial round for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_bit_linker(
    self,
    tile: int | str,
    round: int | str,
) -> Sequence[int] | None:
    """Load readout bits linked to fiducial round for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.

    Returns
    -------
    bit_linker : Sequence[int] or None
        Readout bits linked to fiducial round for one tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id.")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        attributes = self._load_entity_attributes(entity_root)
        bit_linker = attributes.get("bit_linker")
        if bit_linker is None:
            print(tile_id, round_id)
            print("Bit linker attribute not found.")
            return None
        return [int(v) for v in list(bit_linker)]
    except (TypeError, ValueError):
        print(tile_id, round_id)
        print("Bit linker attribute not found.")
        return None

load_local_corrected_image(tile, round=None, bit=None, return_future=True)

Load gain and offset corrected image for fiducial OR readout bit for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str or None

Round index or round id.

None
bit int or str or None

Bit index or bit id.

None
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Name Type Description
corrected_image ndarray or Future or TensorStore or None

Gain and offset corrected image for fiducial OR readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_corrected_image(
    self,
    tile: int | str,
    round: int | str | None = None,
    bit: int | str | None = None,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load gain and offset corrected image for fiducial OR readout bit for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str or None
        Round index or round id.
    bit : int or str or None
        Bit index or bit id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    corrected_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Gain and offset corrected image for fiducial OR readout bit for one tile.
    """
    if (round is None and bit is None) or (round is not None and bit is not None):
        print("Provide either 'round' or 'bit', but not both")
        return None

    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if bit is not None:
        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                local_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                local_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None
        current_local_zarr_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(local_id)
            / Path("corrected_data")
        )
    else:
        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                local_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                local_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        current_local_zarr_path = str(
            self._fiducial_root_path
            / Path(tile_id)
            / Path(local_id)
            / Path("corrected_data")
        )

    image_path = self._image_store_path(current_local_zarr_path)
    if not image_path.exists():
        print("Corrected image not found.")
        return None

    try:
        corrected_image = self._load_from_zarr_array(image_path, return_future)
        return corrected_image
    except (OSError, ValueError):
        print("Error loading corrected image.")
        return None

load_local_decoded_spots(tile, decode_run_key=None)

Load decoded spots and features for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
decode_run_key str or None

Optional decoded-output run key.

None

Returns:

Name Type Description
tile_features DataFrame or None

Decoded spots and features for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_decoded_spots(
    self,
    tile: int | str,
    decode_run_key: str | None = None,
) -> pd.DataFrame | None:
    """Load decoded spots and features for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    decode_run_key : str or None, default None
        Optional decoded-output run key.

    Returns
    -------
    tile_features : pandas.DataFrame or None
        Decoded spots and features for one tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    current_tile_features_path = self._decoded_run_root(decode_run_key) / Path(
        tile_id + "_decoded_features.parquet"
    )

    if not current_tile_features_path.exists():
        print("Decoded spots not found.")
        return None
    else:
        tile_features = self._load_from_parquet(current_tile_features_path)
        return tile_features

load_local_deconvolved_fiducial_image(tile, round, return_future=True)

Load a native-frame deconvolved fiducial image.

Deconvolved fiducials are loaded from decon_data in their native, unwarped tile frame. This image exists only when fiducial deconvolution was run during preprocessing.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Type Description
ndarray or Future or TensorStore or None

Native-frame deconvolved fiducial image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_deconvolved_fiducial_image(
    self,
    tile: int | str,
    round: int | str,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load a native-frame deconvolved fiducial image.

    Deconvolved fiducials are loaded from ``decon_data`` in their native,
    unwarped tile frame. This image exists only when fiducial deconvolution
    was run during preprocessing.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Native-frame deconvolved fiducial image.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    decon_path = self._fiducial_root_path / tile_id / round_id / Path("decon_data")
    image_path = self._image_store_path(decon_path)
    if not image_path.exists():
        return None

    try:
        return self._load_from_zarr_array(image_path, return_future)
    except (OSError, ValueError) as e:
        print(e)
        print("Error loading local deconvolved fiducial image.")
        return None

load_local_deconvolved_readout_image(tile, bit, return_future=True)

Load a native-frame deconvolved readout bit image.

Deconvolved readout bits are loaded from decon_data in their native, unwarped tile frame. This image exists only when readout deconvolution was run during preprocessing.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Type Description
ndarray or Future or TensorStore or None

Native-frame deconvolved readout image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_deconvolved_readout_image(
    self,
    tile: int | str,
    bit: int | str,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load a native-frame deconvolved readout bit image.

    Deconvolved readout bits are loaded from ``decon_data`` in their
    native, unwarped tile frame. This image exists only when readout
    deconvolution was run during preprocessing.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Native-frame deconvolved readout image.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id")
            return None
        bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    readout_path = (
        self._readouts_root_path / Path(tile_id) / Path(bit_id) / Path("decon_data")
    )
    image_path = self._image_store_path(readout_path)
    if not image_path.exists():
        return None

    try:
        return self._load_from_zarr_array(image_path, return_future)
    except (OSError, ValueError) as e:
        print(e)
        print("Error loading local deconvolved readout image.")
        return None

load_local_feature_predictor_image(tile, bit, return_future=True)

Load readout bit feature_predictor prediction image for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Name Type Description
feature_predictor_image ndarray or Future or TensorStore or None

feature_predictor prediction image for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_feature_predictor_image(
    self,
    tile: int | str,
    bit: int | str,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load readout bit feature_predictor prediction image for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    feature_predictor_image : numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        feature_predictor prediction image for one tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        else:
            bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id")
            return None
        else:
            bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    current_local_zarr_path = str(
        self._readouts_root_path
        / Path(tile_id)
        / Path(bit_id)
        / Path(f"{self.feature_predictor_folder_name}_data")
    )

    image_path = self._image_store_path(current_local_zarr_path)
    if not image_path.exists():
        print("feature_predictor prediction image not found.")
        return None

    try:
        feature_predictor_image = self._load_from_zarr_array(
            image_path, return_future
        )
        return feature_predictor_image
    except (OSError, ValueError) as e:
        print(e)
        print("Error loading feature_predictor image.")
        return None

load_local_feature_predictor_spots(tile, bit)

Load feature_predictor spot localizations and features for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required

Returns:

Name Type Description
feature_predictor_localizations DataFrame or None

feature_predictor localizations and features for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_feature_predictor_spots(
    self,
    tile: int | str,
    bit: int | str,
) -> pd.DataFrame | None:
    """Load feature_predictor spot localizations and features for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.

    Returns
    -------
    feature_predictor_localizations : pandas.DataFrame or None
        feature_predictor localizations and features for one tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        else:
            bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id")
            return None
        else:
            bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    current_feature_predictor_localizations_path = (
        self._feature_predictor_localizations_root_path
        / Path(tile_id)
        / Path(bit_id + ".parquet")
    )

    if not current_feature_predictor_localizations_path.exists():
        print("feature_predictor localizations not found.")
        return None
    else:
        feature_predictor_localizations = self._load_from_parquet(
            current_feature_predictor_localizations_path
        )
        return feature_predictor_localizations

load_local_fiducial_image(tile, round, return_future=True)

Load the best available native-frame fiducial image.

Deconvolved fiducial data are returned when decon_data exists; otherwise corrected fiducial data are returned.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Type Description
ndarray or Future or TensorStore or None

Deconvolved fiducial image if available, otherwise corrected image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_fiducial_image(
    self,
    tile: int | str,
    round: int | str,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load the best available native-frame fiducial image.

    Deconvolved fiducial data are returned when ``decon_data`` exists;
    otherwise corrected fiducial data are returned.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Deconvolved fiducial image if available, otherwise corrected image.
    """
    image = self.load_local_deconvolved_fiducial_image(
        tile=tile,
        round=round,
        return_future=return_future,
    )
    if image is not None:
        return image
    return self.load_local_corrected_image(
        tile=tile,
        round=round,
        return_future=return_future,
    )

load_local_image_metadata(tile, *, round=None, bit=None, image_names=None)

Load image and sidecar metadata for one fiducial round or readout bit.

Parameters:

Name Type Description Default
tile int or str

Tile index or identifier.

required
round int or str or None

Fiducial round index or identifier; excludes bit.

None
bit int or str or None

Readout bit index or identifier; excludes round.

None
image_names Sequence[str] or None

Image names to inspect, in metadata precedence order.

None

Returns:

Type Description
dict[str, Any]

Merged image metadata, with sidecar values taking precedence.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_image_metadata(
    self,
    tile: int | str,
    *,
    round: int | str | None = None,
    bit: int | str | None = None,
    image_names: Sequence[str] | None = None,
) -> dict[str, Any]:
    """Load image and sidecar metadata for one fiducial round or readout bit.

    Parameters
    ----------
    tile : int or str
        Tile index or identifier.
    round : int or str or None
        Fiducial round index or identifier; excludes bit.
    bit : int or str or None
        Readout bit index or identifier; excludes round.

    image_names : Sequence[str] or None
        Image names to inspect, in metadata precedence order.

    Returns
    -------
    dict[str, Any]
        Merged image metadata, with sidecar values taking precedence.
    """
    path = self.local_image_path(tile, "corrected_data", round=round, bit=bit)
    return self._load_entity_attributes(path.parent, image_names=image_names)

load_local_readout_image(tile, bit, return_future=True)

Load the best available native-frame readout bit image.

Deconvolved readout data are returned when decon_data exists; otherwise corrected readout data are returned.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Type Description
ndarray or Future or TensorStore or None

Deconvolved readout image if available, otherwise corrected image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_readout_image(
    self,
    tile: int | str,
    bit: int | str,
    return_future: bool | None = True,
) -> "np.ndarray | Future | TensorStore | None":
    """Load the best available native-frame readout bit image.

    Deconvolved readout data are returned when ``decon_data`` exists;
    otherwise corrected readout data are returned.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    return_future : bool or None
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    numpy.ndarray or tensorstore.Future or tensorstore.TensorStore or None
        Deconvolved readout image if available, otherwise corrected image.
    """
    image = self.load_local_deconvolved_readout_image(
        tile=tile,
        bit=bit,
        return_future=return_future,
    )
    if image is not None:
        return image
    return self.load_local_corrected_image(
        tile=tile,
        bit=bit,
        return_future=return_future,
    )

load_local_rigid_xform_xyz_px(tile, round)

Load calculated rigid registration transform for one round and tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required

Returns:

Name Type Description
rigid_xform_xyz_px ArrayLike or None

Local rigid registration transform for one round and tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_rigid_xform_xyz_px(
    self,
    tile: int | str,
    round: int | str,
) -> ArrayLike | None:
    """Load calculated rigid registration transform for one round and tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.

    Returns
    -------
    rigid_xform_xyz_px : ArrayLike or None
        Local rigid registration transform for one round and tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None
    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        attributes = self._load_entity_attributes(entity_root)
        rigid_xform_xyz_px = np.asarray(
            attributes["rigid_xform_xyz_px"], dtype=np.float32
        )
        return rigid_xform_xyz_px
    except (FileNotFoundError, json.JSONDecodeError, KeyError):
        print(tile_id, round_id)
        print("Rigid transform mapping back to first round not found.")
        return None

load_local_round_linker(tile, bit)

Load fiducial round linked to readout bit for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required

Returns:

Name Type Description
round_linker Sequence[int] or None

Fiducial round linked to readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_round_linker(
    self,
    tile: int | str,
    bit: int | str,
) -> Sequence[int] | None:
    """Load fiducial round linked to readout bit for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.

    Returns
    -------
    round_linker : Sequence[int] or None
        Fiducial round linked to readout bit for one tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        else:
            bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id.")
            return None
        else:
            bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    try:
        entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
        attributes = self._load_entity_attributes(entity_root)
        round_linker = attributes.get("round_linker")
        if round_linker is None:
            print(tile_id, bit_id)
            print("Round linker attribute not found.")
            return None
        return int(round_linker)
    except (TypeError, ValueError):
        print(tile_id, bit_id)
        print("Round linker attribute not found.")
        return None

load_local_round_transform_zyx_um(tile, round)

Load the local fiducial round transform for one tile.

Parameters:

Name Type Description Default
tile int | str

Tile index or tile identifier.

required
round int | str

Fiducial round index or round identifier.

required

Returns:

Type Description
ArrayLike or None

Homogeneous 4x4 affine transform in physical Z, Y, X microns. The transform maps first-round reference coordinates to coordinates in the requested moving round. Returns None when the transform is not present.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_round_transform_zyx_um(
    self,
    tile: int | str,
    round: int | str,
) -> ArrayLike | None:
    """
    Load the local fiducial round transform for one tile.

    Parameters
    ----------
    tile : int | str
        Tile index or tile identifier.
    round : int | str
        Fiducial round index or round identifier.

    Returns
    -------
    ArrayLike or None
        Homogeneous 4x4 affine transform in physical Z, Y, X microns. The
        transform maps first-round reference coordinates to coordinates in
        the requested moving round. Returns None when the transform is not
        present.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None
    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        attributes = self._load_entity_attributes(entity_root)
        return np.asarray(
            attributes["local_round_transform_zyx_um"], dtype=np.float32
        )
    except (FileNotFoundError, json.JSONDecodeError, KeyError):
        print(tile_id, round_id)
        print("Local round transform mapping back to first round not found.")
        return None

load_local_sofima_flow_field(*, tile, round, return_future=True)

Load the SOFIMA flow field for one local fiducial round.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile identifier.

required
round int or str

Moving fiducial round index or identifier.

required
return_future bool or None

True returns a read future, False returns a NumPy array, and None returns a sliceable TensorStore handle opened through yaozarrs.

True

Returns:

Type Description
tuple[ndarray or Future or TensorStore, dict] or None

SOFIMA flow field and metadata attributes. The map channels are X, Y, Z and spatial axes are Z, Y, X. map_stride_zyx_px is stored in Z, Y, X order. map_box_start_xyz_px is stored in X, Y, Z order and gives the reference-grid coordinate of the first flow sample. For fields produced by SOFIMA this is the patch center coordinate, not the image corner.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_sofima_flow_field(
    self,
    *,
    tile: int | str,
    round: int | str,
    return_future: bool | None = True,
) -> "tuple[np.ndarray | Future | TensorStore, dict] | None":
    """
    Load the SOFIMA flow field for one local fiducial round.

    Parameters
    ----------
    tile : int or str
        Tile index or tile identifier.
    round : int or str
        Moving fiducial round index or identifier.
    return_future : bool or None, default=True
        True returns a read future, False returns a NumPy array, and None
        returns a sliceable TensorStore handle opened through yaozarrs.

    Returns
    -------
    tuple[numpy.ndarray or tensorstore.Future or tensorstore.TensorStore, dict] or None
        SOFIMA flow field and metadata attributes. The map channels are X,
        Y, Z and spatial axes are Z, Y, X. ``map_stride_zyx_px`` is stored
        in Z, Y, X order. ``map_box_start_xyz_px`` is stored in X, Y, Z
        order and gives the reference-grid coordinate of the first flow
        sample. For fields produced by SOFIMA this is the patch center
        coordinate, not the image corner.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    image_name = "local_sofima_flow_field"
    entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
    current_local_zarr_path = entity_root / Path(image_name)
    image_path = self._image_store_path(current_local_zarr_path)
    if not image_path.exists():
        print("SOFIMA flow field not found.")
        return None

    try:
        sofima_flow_field = self._load_from_zarr_array(image_path, return_future)
        attributes = self._load_entity_attributes(
            entity_root,
            image_names=(image_name,),
        )
        return sofima_flow_field, attributes
    except (OSError, ValueError, KeyError) as e:
        print(e)
        print("Error loading SOFIMA flow field.")
        return None

load_local_stage_position_zyx_um(tile, round)

Load tile stage position for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required

Returns:

Name Type Description
stage_zyx_um ArrayLike or None

Tile stage position in Z, Y, X microns. Legacy two-coordinate Y, X metadata is returned with Z=0 without modifying the stored data.

affine_zyx_um ArrayLike or None

Affine transformation between stage and camera

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_stage_position_zyx_um(
    self,
    tile: int | str,
    round: int | str,
) -> tuple[np.ndarray, np.ndarray] | None:
    """Load tile stage position for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.

    Returns
    -------
    stage_zyx_um : ArrayLike or None
        Tile stage position in Z, Y, X microns. Legacy two-coordinate Y, X
        metadata is returned with Z=0 without modifying the stored data.
    affine_zyx_um: ArrayLike or None
        Affine transformation between stage and camera
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id.")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        attributes = self._load_entity_attributes(entity_root)
        stage_zyx_um = attributes.get("stage_zyx_um")
        affine_zyx_px = attributes.get("affine_zyx_px")
        if stage_zyx_um is None or affine_zyx_px is None:
            print(tile_id, round_id)
            print("Stage position attribute not found.")
            return None
        return self._normalize_stage_position_zyx_um(stage_zyx_um), np.asarray(
            affine_zyx_px, dtype=np.float32
        )
    except (TypeError, ValueError):
        print(tile_id, round_id)
        print("Stage position attribute not found.")
        return None

load_local_wavelengths_um(tile, round=None, bit=None)

Load wavelengths for fiducial OR readout bit for one tile.

Parameters:

Name Type Description Default
tile int or str

Tile index or tile id.

required
round int or str or None

Round index or round id.

None
bit int or str or None

Bit index or bit id.

None

Returns:

Name Type Description
wavelengths_um tuple[float, float] or None

Wavelengths for fiducial OR readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_wavelengths_um(
    self,
    tile: int | str,
    round: int | str | None = None,
    bit: int | str | None = None,
) -> tuple[float, float] | None:
    """Load wavelengths for fiducial OR readout bit for one tile.

    Parameters
    ----------
    tile : int or str
        Tile index or tile id.
    round : int or str or None
        Round index or round id.
    bit : int or str or None
        Bit index or bit id.

    Returns
    -------
    wavelengths_um : tuple[float, float] or None
        Wavelengths for fiducial OR readout bit for one tile.
    """
    if (round is None and bit is None) or (round is not None and bit is not None):
        print("Provide either 'round' or 'bit', but not both")
        return None

    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if bit is not None:
        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                local_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                local_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None
        entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
    else:
        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                local_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                local_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)

    try:
        attributes = self._load_entity_attributes(entity_root)
        ex_wavelength_um = attributes["excitation_um"]
        em_wavelength_um = attributes["emission_um"]
        return (ex_wavelength_um, em_wavelength_um)
    except KeyError:
        print("Wavelength attributes not found.")
        return None

load_proseg_cell_polygons_3d(run_name=None)

Load Proseg 3D refined cell polygons.

Parameters:

Name Type Description Default
run_name str or None

Proseg run name. None or "default" selects proseg/3D.

None

Returns:

Name Type Description
polygons dict[Any, ArrayLike] or None

Cell identifiers mapped to polygon vertices in X, Y order.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_proseg_cell_polygons_3d(
    self,
    run_name: str | None = None,
) -> dict[Any, ArrayLike] | None:
    """Load Proseg 3D refined cell polygons.

    Parameters
    ----------
    run_name : str or None, default None
        Proseg run name. ``None`` or ``"default"`` selects ``proseg/3D``.

    Returns
    -------
    polygons : dict[Any, ArrayLike] or None
        Cell identifiers mapped to polygon vertices in X, Y order.
    """
    polygon_path = self._proseg_3d_run_root(run_name) / Path(
        "cell_polygons_3D.geojson.gz"
    )
    if not polygon_path.exists():
        print("Proseg cell polygons not found.")
        return None

    try:
        with gzip.open(polygon_path, "rt", encoding="utf-8") as file:
            geojson = json.load(file)
    except (OSError, json.JSONDecodeError) as exc:
        print(exc)
        print("Error loading Proseg cell polygons.")
        return None

    polygons: dict[Any, ArrayLike] = {}
    for idx, feature in enumerate(geojson.get("features", [])):
        properties = feature.get("properties", {})
        cell_id = properties.get("cell", idx)
        geometry = feature.get("geometry", {})
        coordinates = geometry.get("coordinates", [])
        rings: list[np.ndarray] = []
        if geometry.get("type") == "Polygon":
            rings.extend(np.asarray(ring, dtype=float) for ring in coordinates)
        elif geometry.get("type") == "MultiPolygon":
            for polygon in coordinates:
                rings.extend(np.asarray(ring, dtype=float) for ring in polygon)
        if rings:
            polygons[cell_id] = max(rings, key=len)

    return polygons

load_proseg_transcripts_3d(run_name=None)

Load Proseg 3D transcript metadata.

Parameters:

Name Type Description Default
run_name str or None

Proseg run name. None or "default" selects proseg/3D.

None

Returns:

Name Type Description
transcripts DataFrame or None

Proseg transcript metadata.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_proseg_transcripts_3d(
    self,
    run_name: str | None = None,
) -> pd.DataFrame | None:
    """Load Proseg 3D transcript metadata.

    Parameters
    ----------
    run_name : str or None, default None
        Proseg run name. ``None`` or ``"default"`` selects ``proseg/3D``.

    Returns
    -------
    transcripts : pandas.DataFrame or None
        Proseg transcript metadata.
    """
    transcript_path = self._proseg_3d_run_root(run_name) / Path(
        "transcript_metadata_3D.csv.gz"
    )
    if not transcript_path.exists():
        print("Proseg transcript metadata not found.")
        return None
    try:
        return pd.read_csv(transcript_path, compression="gzip")
    except (OSError, ValueError) as exc:
        print(exc)
        print("Error loading Proseg transcript metadata.")
        return None

local_feature_predictor_spots_path(tile, bit)

Return the localization table path for a tile and readout identifier.

Source code in src/merfish3danalysis/qi2labDataStore.py
def local_feature_predictor_spots_path(self, tile: str, bit: str) -> Path:
    """Return the localization table path for a tile and readout identifier."""
    if tile not in self._tile_ids or bit not in self._bit_ids:
        raise ValueError(f"Invalid tile or bit: {tile}, {bit}")
    return (
        self._feature_predictor_localizations_root_path / tile / (bit + ".parquet")
    )

local_image_path(tile, image_name, *, round=None, bit=None)

Return a native fiducial or readout OME-Zarr image path.

Parameters:

Name Type Description Default
tile int or str

Zero-based tile index or stored tile identifier.

required
image_name str

Logical image name such as corrected_data or decon_data.

required
round int or str or None

Zero-based fiducial round index or identifier; excludes bit.

None
bit int or str or None

Zero-based readout bit index or identifier; excludes round.

None

Returns:

Type Description
Path

Image path without loading pixels or creating directories.

Source code in src/merfish3danalysis/qi2labDataStore.py
def local_image_path(
    self,
    tile: int | str,
    image_name: str,
    *,
    round: int | str | None = None,
    bit: int | str | None = None,
) -> Path:
    """Return a native fiducial or readout OME-Zarr image path.

    Parameters
    ----------
    tile : int or str
        Zero-based tile index or stored tile identifier.
    image_name : str
        Logical image name such as corrected_data or decon_data.
    round : int or str or None
        Zero-based fiducial round index or identifier; excludes bit.
    bit : int or str or None
        Zero-based readout bit index or identifier; excludes round.

    Returns
    -------
    Path
        Image path without loading pixels or creating directories.
    """
    if (round is None) == (bit is None):
        raise ValueError("Provide exactly one of round or bit.")
    if isinstance(tile, int) and not 0 <= tile < len(self._tile_ids):
        raise ValueError(f"Invalid tile: {tile}")
    tile_id = self._tile_ids[tile] if isinstance(tile, int) else tile
    if tile_id not in self._tile_ids:
        raise ValueError(f"Invalid tile: {tile}")
    ids = self._round_ids if round is not None else self._bit_ids
    selection = round if round is not None else bit
    if isinstance(selection, int) and not 0 <= selection < len(ids):
        raise ValueError(f"Invalid round or bit: {selection}")
    entity_id = ids[selection] if isinstance(selection, int) else selection
    if entity_id not in ids:
        raise ValueError(f"Invalid round or bit: {selection}")
    root = (
        self._fiducial_root_path if round is not None else self._readouts_root_path
    )
    return self._image_store_path(root / tile_id / entity_id / image_name)

save_chromatic_affine_transforms_zyx_um(calibration)

Save chromatic affine calibration metadata.

Parameters:

Name Type Description Default
calibration Mapping[str, Any]

Calibration metadata containing one 4x4 affine_zyx_um matrix per channel. Each affine maps that channel's physical Z, Y, X coordinates onto the lowest-wavelength reference channel.

required

Returns:

Type Description
None

Metadata are written to calibrations/attributes.json.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_chromatic_affine_transforms_zyx_um(
    self,
    calibration: Mapping[str, Any],
) -> None:
    """
    Save chromatic affine calibration metadata.

    Parameters
    ----------
    calibration : Mapping[str, Any]
        Calibration metadata containing one 4x4 ``affine_zyx_um`` matrix
        per channel. Each affine maps that channel's physical Z, Y, X
        coordinates onto the lowest-wavelength reference channel.

    Returns
    -------
    None
        Metadata are written to ``calibrations/attributes.json``.
    """
    calibration = dict(calibration)
    if "voxel_size_zyx_um" in calibration:
        calibration["voxel_size_zyx_um"] = round_spacing_um(
            calibration["voxel_size_zyx_um"]
        ).tolist()
    self._set_calibration_attribute(
        "chromatic_affine_transforms_zyx_um",
        calibration,
    )

save_coord_of_xform_px(of_xform_px, tile, block_size, block_stride, round, return_future=False)

Save fiducial optical flow matrix for one round and tile.

Parameters:

Name Type Description Default
of_xform_px ArrayLike

Local fiducial optical flow matrix for one round and tile.

required
tile int or str

Tile index or tile id.

required
block_size Sequence[float]

Block size for pixel warp

required
block_stride Sequence[float]

Block stride for pixel warp

required
round int or str

Round index or round id.

required
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None. Invalid tile/round/bit selections also return None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_coord_of_xform_px(
    self,
    of_xform_px: ArrayLike,
    tile: int | str,
    block_size: Sequence[float],
    block_stride: Sequence[float],
    round: int | str,
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """Save fiducial optical flow matrix for one round and tile.

    Parameters
    ----------
    of_xform_px : ArrayLike
        Local fiducial optical flow matrix for one round and tile.
    tile : int or str
        Tile index or tile id.
    block_size : Sequence[float]
        Block size for pixel warp
    block_stride: Sequence[float]
        Block stride for pixel warp
    round : int or str
        Round index or round id.
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None. Invalid tile/round/bit selections also return None.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            local_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        else:
            local_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None
    entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)
    current_local_zarr_path = entity_root / Path("opticalflow_xform_px")

    try:
        opticalflow_attrs = {
            "block_size": np.asarray(block_size, dtype=np.float32).tolist(),
            "block_stride": np.asarray(block_stride, dtype=np.float32).tolist(),
        }
        # Optical flow is a dense pixel-space field, so we do not encode
        # physical voxel scale or stage translation transforms here.
        write_future = self._save_to_zarr_array(
            of_xform_px,
            current_local_zarr_path,
            return_future,
            extra_attributes=opticalflow_attrs,
        )
        if write_future is not None:
            write_future.result()
        self._save_entity_attributes(
            entity_root_path=entity_root, updates=opticalflow_attrs
        )
        return write_future
    except (OSError, TimeoutError):
        print("Error saving optical flow transform.")
        raise

save_decode_normalization_vectors(decode_run_key, kind, normalization_vector, background_vector, decode_mode=None, metadata=None)

Save default or run-scoped normalization and background vectors.

Parameters:

Name Type Description Default
decode_run_key str or None

Optional decoded-output run key. None writes the default vectors.

required
kind ('global', iterative)

Normalization vector kind.

'global'
normalization_vector ArrayLike

Foreground normalization vector.

required
background_vector ArrayLike

Background vector.

required
decode_mode str or None

Decode mode metadata.

None
metadata Mapping[str, Any] or None

Additional provenance for these normalization vectors.

None
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_decode_normalization_vectors(
    self,
    decode_run_key: str | None,
    kind: str,
    normalization_vector: ArrayLike,
    background_vector: ArrayLike,
    decode_mode: str | None = None,
    metadata: Mapping[str, Any] | None = None,
) -> None:
    """
    Save default or run-scoped normalization and background vectors.

    Parameters
    ----------
    decode_run_key : str or None
        Optional decoded-output run key. None writes the default vectors.
    kind : {'global', 'iterative'}
        Normalization vector kind.
    normalization_vector : ArrayLike
        Foreground normalization vector.
    background_vector : ArrayLike
        Background vector.
    decode_mode : str or None, default None
        Decode mode metadata.
    metadata : Mapping[str, Any] or None, default None
        Additional provenance for these normalization vectors.
    """
    if kind == "global":
        if decode_run_key is None:
            self.global_normalization_vector = normalization_vector
            self.global_background_vector = background_vector
            self._save_default_decode_normalization_metadata(kind, metadata)
            return
        norm_key = "global_normalization_vector"
        background_key = "global_background_vector"
    elif kind == "iterative":
        if decode_run_key is None:
            self.iterative_normalization_vector = normalization_vector
            self.iterative_background_vector = background_vector
            self._save_default_decode_normalization_metadata(kind, metadata)
            return
        norm_key = "iterative_normalization_vector"
        background_key = "iterative_background_vector"
    else:
        raise ValueError("kind must be one of 'global' or 'iterative'.")

    decode_run_key = self._validate_decode_run_key(decode_run_key)
    calib_attrs = self._load_calibrations_attributes()
    runs = dict(calib_attrs.get("decode_normalization_runs", {}))
    run_attrs = dict(runs.get(decode_run_key, {}))
    if decode_mode is not None:
        run_attrs["decode_mode"] = str(decode_mode)
    if metadata is not None:
        run_attrs[f"{kind}_metadata"] = dict(metadata)
    run_attrs[norm_key] = np.asarray(normalization_vector, dtype=np.float32)
    run_attrs[background_key] = np.asarray(background_vector, dtype=np.float32)
    runs[decode_run_key] = run_attrs
    calib_attrs["decode_normalization_runs"] = runs
    self._save_calibrations_attributes(calib_attrs)

save_global_cellpose_segmentation_image(cellpose_image, downsampling, return_future=False)

Save Cellpose max projection, downsampled segmentation image.

The caller runs segmentation and selects its image grid. This method stores the supplied labels unchanged and derives their physical scale from the native voxel calibration and supplied downsampling factors.

Parameters:

Name Type Description Default
cellpose_image ArrayLike

Cellpose max projection, downsampled segmentation image.

required
downsampling Sequence[float]

Caller-selected Z, Y, X factors: segmentation spacing divided by native voxel spacing. Two-dimensional masks use the resulting YX physical scale while retaining all three factors in metadata.

required
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_cellpose_segmentation_image(
    self,
    cellpose_image: ArrayLike,
    downsampling: Sequence[float],
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """Save Cellpose max projection, downsampled segmentation image.

    The caller runs segmentation and selects its image grid. This method
    stores the supplied labels unchanged and derives their physical scale
    from the native voxel calibration and supplied downsampling factors.

    Parameters
    ----------
    cellpose_image : ArrayLike
        Cellpose max projection, downsampled segmentation image.
    downsampling : Sequence[float]
        Caller-selected Z, Y, X factors: segmentation spacing divided by
        native voxel spacing. Two-dimensional masks use the resulting YX
        physical scale while retaining all three factors in metadata.
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None.
    """
    current_local_zarr_path = (
        self._segmentation_root_path
        / Path("cellpose")
        / Path(f"masks_{self.fiducial_folder_name}_iso_zyx")
    )

    downsampling = np.asarray(downsampling, dtype=np.float64)
    if (
        downsampling.shape != (3,)
        or not np.all(np.isfinite(downsampling))
        or np.any(downsampling <= 0)
    ):
        raise ValueError(
            "Downsampling must contain three positive finite Z, Y, X factors."
        )
    spacing = round_spacing_um(self.voxel_size_zyx_um) * downsampling
    attributes = {"downsampling": downsampling.tolist()}

    try:
        write_future = self._save_to_zarr_array(
            cellpose_image,
            current_local_zarr_path,
            return_future,
            ome_scale=round_spacing_um(spacing).tolist(),
            extra_attributes=attributes,
        )
        if write_future is not None:
            write_future.result()
        return write_future
    except (OSError, TimeoutError):
        print("Error saving Cellpose image.")
        raise

save_global_coord_xforms_um(affine_zyx_um, origin_zyx_um, spacing_zyx_um, tile)

Save global registration transform for one tile.

Parameters:

Name Type Description Default
affine_zyx_um ArrayLike

Final 4x4 registration correction in physical Z, Y, X coordinates, applied after the separately stored camera-to-stage transform.

required
origin_zyx_um ArrayLike

Native image origin in Z, Y, X micrometers, before camera mapping.

required
spacing_zyx_um ArrayLike

Native Z, Y, X voxel spacing in micrometers.

required
tile int or str

Tile index or tile id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_coord_xforms_um(
    self,
    affine_zyx_um: ArrayLike,
    origin_zyx_um: ArrayLike,
    spacing_zyx_um: ArrayLike,
    tile: int | str,
) -> None:
    """Save global registration transform for one tile.

    Parameters
    ----------
    affine_zyx_um : ArrayLike
        Final 4x4 registration correction in physical Z, Y, X coordinates,
        applied after the separately stored camera-to-stage transform.
    origin_zyx_um : ArrayLike
        Native image origin in Z, Y, X micrometers, before camera mapping.
    spacing_zyx_um : ArrayLike
        Native Z, Y, X voxel spacing in micrometers.
    tile : int or str
        Tile index or tile id.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    try:
        entity_root = (
            self._fiducial_root_path / Path(tile_id) / Path(self._round_ids[0])
        )
        self._save_entity_attributes(
            entity_root_path=entity_root,
            updates={
                "affine_zyx_um": np.asarray(
                    affine_zyx_um, dtype=np.float32
                ).tolist(),
                "origin_zyx_um": np.asarray(
                    origin_zyx_um, dtype=np.float32
                ).tolist(),
                "spacing_zyx_um": round_spacing_um(spacing_zyx_um).tolist(),
            },
        )
    except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError) as e:
        print(e)
        print("Could not save global coordinate transforms.")

save_global_fiducial_image(fused_image, affine_zyx_um, origin_zyx_um, spacing_zyx_um, fusion_type='fiducial', return_future=False)

Save downsampled, fused fiducial image.

The caller selects the fusion grid. This method stores the supplied image and spacing without choosing a dataset-specific downsampling.

Parameters:

Name Type Description Default
fused_image ArrayLike

Downsampled, fused fiducial image.

required
affine_zyx_um ArrayLike

Global affine registration transform for fused image.

required
origin_zyx_um ArrayLike

Global origin registration transform for fused image.

required
spacing_zyx_um ArrayLike

Caller-selected fused voxel spacing in Z, Y, X microns.

required
fusion_type str

Type of fusion (fiducial or all_channels).

'fiducial'
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_fiducial_image(
    self,
    fused_image: ArrayLike,
    affine_zyx_um: ArrayLike,
    origin_zyx_um: ArrayLike,
    spacing_zyx_um: ArrayLike,
    fusion_type: str = "fiducial",
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """Save downsampled, fused fiducial image.

    The caller selects the fusion grid. This method stores the supplied
    image and spacing without choosing a dataset-specific downsampling.

    Parameters
    ----------
    fused_image : ArrayLike
        Downsampled, fused fiducial image.
    affine_zyx_um : ArrayLike
        Global affine registration transform for fused image.
    origin_zyx_um : ArrayLike
        Global origin registration transform for fused image.
    spacing_zyx_um : ArrayLike
        Caller-selected fused voxel spacing in Z, Y, X microns.
    fusion_type : str
        Type of fusion (fiducial or all_channels).
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None.
    """
    if fusion_type == "fiducial":
        filename = f"fused_{self.fiducial_folder_name}_zyx"
    else:
        filename = "fused_all_channels_zyx"
    current_local_zarr_path = self._fused_root_path / Path(filename)

    metadata_attrs = {
        "affine_zyx_um": np.asarray(affine_zyx_um, dtype=np.float32).tolist(),
        "origin_zyx_um": np.asarray(origin_zyx_um, dtype=np.float32).tolist(),
        "spacing_zyx_um": round_spacing_um(spacing_zyx_um).tolist(),
    }
    fused_array = np.asarray(fused_image)
    try:
        write_future = self._save_to_zarr_array(
            fused_array.astype(np.uint16),
            current_local_zarr_path,
            return_future,
            ome_scale=metadata_attrs["spacing_zyx_um"],
            extra_attributes=metadata_attrs,
            chunks=self._fused_image_chunks(fused_array),
        )
        if write_future is not None:
            write_future.result()
        return write_future
    except (OSError, TimeoutError):
        print("Error saving fused image.")
        raise

save_global_filtered_decoded_spots(filtered_decoded_df, decode_run_key=None)

Save all decoded and filtered spots.

Parameters:

Name Type Description Default
filtered_decoded_df DataFrame

All decoded and filtered spots.

required
decode_run_key str or None

Optional decoded-output run key.

None
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_filtered_decoded_spots(
    self,
    filtered_decoded_df: pd.DataFrame,
    decode_run_key: str | None = None,
) -> None:
    """Save all decoded and filtered spots.

    Parameters
    ----------
    filtered_decoded_df : pd.DataFrame
        All decoded and filtered spots.
    decode_run_key : str or None, default None
        Optional decoded-output run key.
    """
    current_global_filtered_decoded_dir_path = self._global_filtered_decoded_root(
        decode_run_key
    )

    if not current_global_filtered_decoded_dir_path.exists():
        current_global_filtered_decoded_dir_path.mkdir(parents=True)

    current_global_filtered_decoded_path = (
        current_global_filtered_decoded_dir_path / Path("decoded_features.parquet")
    )
    current_global_filtered_decoded_csv_gz_path = (
        current_global_filtered_decoded_dir_path / Path("decoded_features.csv.gz")
    )

    self._save_to_parquet(filtered_decoded_df, current_global_filtered_decoded_path)
    self._save_to_csv_gz(
        filtered_decoded_df, current_global_filtered_decoded_csv_gz_path
    )

save_image_metadata(image_path, extra_attributes, merge=True) staticmethod

Write image-level extra attributes for externally-created OME-Zarr stores.

Parameters:

Name Type Description Default
image_path Path | str

Image group path. Both the directory path and the corresponding OME-Zarr store path are accepted.

required
extra_attributes Mapping[str, Any]

Attribute updates to write at the image root.

required
merge bool

If True, merge updates into existing attributes. If False, replace the existing image-level attributes with extra_attributes.

True

Returns:

Type Description
None

Attributes are written to the Zarr v3 zarr.json. The OME metadata is preserved when replacing extra attributes.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def save_image_metadata(
    image_path: Path | str,
    extra_attributes: Mapping[str, Any],
    merge: bool = True,
) -> None:
    """
    Write image-level extra attributes for externally-created OME-Zarr stores.

    Parameters
    ----------
    image_path : Path | str
        Image group path. Both the directory path and the corresponding
        OME-Zarr store path are accepted.
    extra_attributes : Mapping[str, Any]
        Attribute updates to write at the image root.
    merge : bool, default=True
        If True, merge updates into existing attributes. If False, replace
        the existing image-level attributes with ``extra_attributes``.

    Returns
    -------
    None
        Attributes are written to the Zarr v3 ``zarr.json``. The OME
        metadata is preserved when replacing extra attributes.
    """
    image_root = qi2labDataStore._image_store_path(image_path)
    payload = {
        str(k): qi2labDataStore._to_json_compatible(v)
        for k, v in dict(extra_attributes).items()
    }

    for key in ("spacing_zyx_um", "voxel_size_zyx_um"):
        if key in payload:
            payload[key] = round_spacing_um(payload[key]).tolist()

    group = open_group(image_root)
    metadata = group.metadata.model_dump(mode="json", exclude_none=True)
    if metadata["zarr_format"] != 3:
        raise ValueError("Datastore images must use OME-Zarr on Zarr v3.")
    existing = dict(group.attrs)
    attributes = existing if merge else {"ome": existing["ome"]}
    attributes.update(payload)
    round_ome_spatial_scales(attributes)
    metadata["attributes"] = attributes
    # yaozarrs exposes attributes read-only. Updating metadata for an
    # externally fused image requires replacing the local Zarr v3 JSON.
    qi2labDataStore._save_to_json(metadata, image_root / "zarr.json")

save_local_bit_linker(bit_linker, tile, round)

Save readout bits linked to fiducial round for one tile.

Parameters:

Name Type Description Default
bit_linker Sequence[int]

Readout bits linked to fiducial round for one tile.

required
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_bit_linker(
    self,
    bit_linker: Sequence[int],
    tile: int | str,
    round: int | str,
) -> None:
    """Save readout bits linked to fiducial round for one tile.

    Parameters
    ----------
    bit_linker : Sequence[int]
        Readout bits linked to fiducial round for one tile.
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id.")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        values = [int(v) for v in list(bit_linker)]
        self._save_entity_attributes(
            entity_root_path=entity_root, updates={"bit_linker": values}
        )
    except (TypeError, ValueError):
        print(tile_id, round_id)
        print("Error writing bit linker attribute.")
        return None

save_local_corrected_image(image, tile, gain_correction=True, hotpixel_correction=True, shading_correction=False, psf_idx=0, round=None, bit=None, return_future=False)

Save gain and offset corrected image.

Parameters:

Name Type Description Default
image ArrayLike

Local corrected image.

required
tile int or str

Tile index or tile id.

required
gain_correction bool

Gain correction applied (True) or not (False).

True
hotpixel_correction bool

Hotpixel correction applied (True) or not (False).

True
shading_correction bool

Shading correction applied (True) or not (False).

False
psf_idx int

PSF index.

0
round int or str or None

Round index or round id.

None
bit int or str or None

Bit index or bit id.

None
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None. Invalid tile/round/bit selections also return None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_corrected_image(
    self,
    image: ArrayLike,
    tile: int | str,
    gain_correction: bool = True,
    hotpixel_correction: bool = True,
    shading_correction: bool = False,
    psf_idx: int = 0,
    round: int | str | None = None,
    bit: int | str | None = None,
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """Save gain and offset corrected image.

    Parameters
    ----------
    image : ArrayLike
        Local corrected image.
    tile : int or str
        Tile index or tile id.
    gain_correction : bool
        Gain correction applied (True) or not (False).
    hotpixel_correction : bool
        Hotpixel correction applied (True) or not (False).
    shading_correction : bool
        Shading correction applied (True) or not (False).
    psf_idx : int
        PSF index.
    round : int or str or None
        Round index or round id.
    bit : int or str or None
        Bit index or bit id.
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None. Invalid tile/round/bit selections also return None.
    """
    if (round is None and bit is None) or (round is not None and bit is not None):
        print("Provide either 'round' or 'bit', but not both")
        return None

    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if bit is not None:
        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                local_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                local_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None
        entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
        current_local_zarr_path = entity_root / Path("corrected_data")
        stage_position = self._resolve_original_tile_position_zyx_um(
            tile_id=tile_id, bit_id=local_id
        )
    else:
        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                local_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                local_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)
        current_local_zarr_path = entity_root / Path("corrected_data")
        stage_position = self._resolve_original_tile_position_zyx_um(
            tile_id=tile_id, round_id=local_id
        )

    try:
        self._validate_core_image_shape(
            entity_root_path=entity_root, image_name="corrected_data", image=image
        )
        attributes = self._load_entity_attributes(entity_root)
        attributes.update(
            {
                "gain_correction": bool(gain_correction),
                "hotpixel_correction": bool(hotpixel_correction),
                "shading_correction": bool(shading_correction),
                "psf_idx": int(psf_idx),
            }
        )
        write_future = self._save_to_zarr_array(
            image,
            current_local_zarr_path,
            return_future,
            ome_scale=self.voxel_size_zyx_um,
            ome_translation=stage_position,
            extra_attributes=attributes,
        )
        if write_future is not None:
            write_future.result()
        self._save_entity_attributes(
            entity_root_path=entity_root, updates=attributes
        )
        return write_future
    except (OSError, TimeoutError, ValueError) as e:
        print(e)
        print("Error saving corrected image.")
        raise

save_local_decoded_spots(features_df, tile, decode_run_key=None)

Save decoded spots and features for one tile.

Parameters:

Name Type Description Default
features_df DataFrame

Decoded spots and features for one tile.

required
tile int or str

Tile index or tile id.

required
decode_run_key str or None

Optional decoded-output run key.

None
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_decoded_spots(
    self,
    features_df: pd.DataFrame,
    tile: int | str,
    decode_run_key: str | None = None,
) -> None:
    """Save decoded spots and features for one tile.

    Parameters
    ----------
    features_df : pd.DataFrame
        Decoded spots and features for one tile.
    tile : int or str
        Tile index or tile id.
    decode_run_key : str or None, default None
        Optional decoded-output run key.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    decoded_root_path = self._decoded_run_root(decode_run_key)
    decoded_root_path.mkdir(parents=True, exist_ok=True)
    current_tile_features_path = decoded_root_path / Path(
        tile_id + "_decoded_features.parquet"
    )

    self._save_to_parquet(features_df, current_tile_features_path)

save_local_deconvolved_fiducial_image(image, tile, round, return_future=False)

Save a native-frame deconvolved fiducial image.

Deconvolved fiducials are saved under decon_data in their native, unwarped tile frame.

Parameters:

Name Type Description Default
image ArrayLike

Image to save.

required
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None. Invalid tile/round/bit selections also return None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_deconvolved_fiducial_image(
    self,
    image: ArrayLike,
    tile: int | str,
    round: int | str,
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """
    Save a native-frame deconvolved fiducial image.

    Deconvolved fiducials are saved under ``decon_data`` in their native,
    unwarped tile frame.

    Parameters
    ----------
    image : ArrayLike
        Image to save.
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None. Invalid tile/round/bit selections also return None.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    entity_root = self._fiducial_root_path / tile_id / round_id
    decon_path = entity_root / Path("decon_data")
    stage_position = self._resolve_reference_tile_position_zyx_um(tile_id)

    try:
        self._validate_core_image_shape(
            entity_root_path=entity_root,
            image_name="decon_data",
            image=image,
        )
        attributes = self._load_entity_attributes(entity_root)
        attributes["deconvolution"] = True
        write_future = self._save_to_zarr_array(
            image,
            decon_path,
            return_future,
            ome_scale=self.voxel_size_zyx_um,
            ome_translation=stage_position,
            extra_attributes=attributes,
        )
        if write_future is not None:
            write_future.result()
        self._save_entity_attributes(
            entity_root_path=entity_root, updates=attributes
        )
        return write_future
    except (OSError, TimeoutError, ValueError):
        print("Error saving local deconvolved fiducial image.")
        raise

save_local_deconvolved_readout_image(image, tile, bit, return_future=False)

Save a native-frame deconvolved readout bit image.

Deconvolved readout bits are saved under decon_data in their native, unwarped tile frame.

Parameters:

Name Type Description Default
image ArrayLike

Image to save.

required
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None. Invalid tile/round/bit selections also return None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_deconvolved_readout_image(
    self,
    image: ArrayLike,
    tile: int | str,
    bit: int | str,
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """
    Save a native-frame deconvolved readout bit image.

    Deconvolved readout bits are saved under ``decon_data`` in their
    native, unwarped tile frame.

    Parameters
    ----------
    image : ArrayLike
        Image to save.
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None. Invalid tile/round/bit selections also return None.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id")
            return None
        bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
    readout_path = entity_root / Path("decon_data")
    stage_position = self._resolve_original_tile_position_zyx_um(
        tile_id=tile_id,
        bit_id=bit_id,
    )

    try:
        self._validate_core_image_shape(
            entity_root_path=entity_root,
            image_name="decon_data",
            image=image,
        )
        attributes = self._load_entity_attributes(entity_root)
        attributes["deconvolution"] = True
        write_future = self._save_to_zarr_array(
            image,
            readout_path,
            return_future,
            ome_scale=self.voxel_size_zyx_um,
            ome_translation=stage_position,
            extra_attributes=attributes,
        )
        if write_future is not None:
            write_future.result()
        self._save_entity_attributes(
            entity_root_path=entity_root, updates=attributes
        )
        return write_future
    except (OSError, TimeoutError, ValueError):
        print("Error saving local deconvolved readout image.")
        raise

save_local_feature_predictor_image(feature_predictor_image, tile, bit, return_future=False)

Save feature_predictor prediction image.

Parameters:

Name Type Description Default
feature_predictor_image ArrayLike

feature_predictor prediction image.

required
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None. Invalid tile/round/bit selections also return None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_feature_predictor_image(
    self,
    feature_predictor_image: ArrayLike,
    tile: int | str,
    bit: int | str,
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """Save feature_predictor prediction image.

    Parameters
    ----------
    feature_predictor_image : ArrayLike
        feature_predictor prediction image.
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    return_future : bool or None
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None. Invalid tile/round/bit selections also return None.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        else:
            local_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id")
            return None
        else:
            local_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None
    entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
    current_local_zarr_path = entity_root / Path(
        f"{self.feature_predictor_folder_name}_data"
    )

    try:
        self._validate_core_image_shape(
            entity_root_path=entity_root,
            image_name=f"{self.feature_predictor_folder_name}_data",
            image=feature_predictor_image,
        )
        stage_position = self._resolve_original_tile_position_zyx_um(
            tile_id=tile_id, bit_id=local_id
        )
        attributes = self._load_entity_attributes(entity_root)
        write_future = self._save_to_zarr_array(
            feature_predictor_image,
            current_local_zarr_path,
            return_future,
            ome_scale=self.voxel_size_zyx_um,
            ome_translation=stage_position,
            extra_attributes=attributes,
        )
        if write_future is not None:
            write_future.result()
        self._save_entity_attributes(
            entity_root_path=entity_root, updates=attributes
        )
        return write_future
    except (OSError, ValueError) as e:
        print(e)
        print("Error saving feature_predictor image.")
        raise

save_local_feature_predictor_spots(spot_df, tile, bit)

Save feature_predictor localizations and features.

Parameters:

Name Type Description Default
spot_df DataFrame

feature_predictor localizations and features.

required
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_feature_predictor_spots(
    self,
    spot_df: pd.DataFrame,
    tile: int | str,
    bit: int | str,
) -> None:
    """Save feature_predictor localizations and features.

    Parameters
    ----------
    spot_df : pd.DataFrame
        feature_predictor localizations and features.
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        else:
            bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id")
            return None
        else:
            bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    tile_localizations_path = (
        self._feature_predictor_localizations_root_path / Path(tile_id)
    )
    tile_localizations_path.mkdir(parents=True, exist_ok=True)

    current_feature_predictor_localizations_path = tile_localizations_path / Path(
        bit_id + ".parquet"
    )

    try:
        self._save_to_parquet(spot_df, current_feature_predictor_localizations_path)
    except OSError as e:
        print(e)
        print("Error saving feature_predictor localizations.")
        return None

save_local_rigid_xform_xyz_px(rigid_xform_xyz_px, tile, round)

Save calculated rigid registration transform for one round and tile.

Parameters:

Name Type Description Default
rigid_xform_xyz_px ArrayLike

Local rigid registration transform for one round and tile.

required
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required

Returns:

Name Type Description
rigid_xform_xyz_px ArrayLike or None

Local rigid registration transform for one round and tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_rigid_xform_xyz_px(
    self,
    rigid_xform_xyz_px: ArrayLike,
    tile: int | str,
    round: int | str,
) -> ArrayLike | None:
    """Save calculated rigid registration transform for one round and tile.

    Parameters
    ----------
    rigid_xform_xyz_px : ArrayLike
        Local rigid registration transform for one round and tile.
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.

    Returns
    -------
    rigid_xform_xyz_px : ArrayLike or None
        Local rigid registration transform for one round and tile.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None
    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        self._save_entity_attributes(
            entity_root_path=entity_root,
            updates={
                "rigid_xform_xyz_px": np.asarray(
                    rigid_xform_xyz_px, dtype=np.float32
                ).tolist()
            },
        )
    except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
        print("Error writing rigid transform attribute.")
        return None

save_local_round_linker(round_linker, tile, bit)

Save fiducial round linker attribute to readout bit for one tile.

Parameters:

Name Type Description Default
round_linker int

Fiducial round linked to readout bit for one tile.

required
tile int or str

Tile index or tile id.

required
bit int or str

Bit index or bit id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_round_linker(
    self,
    round_linker: int,
    tile: int | str,
    bit: int | str,
) -> None:
    """Save fiducial round linker attribute to readout bit for one tile.

    Parameters
    ----------
    round_linker : int
        Fiducial round linked to readout bit for one tile.
    tile : int or str
        Tile index or tile id.
    bit : int or str
        Bit index or bit id.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(bit, int):
        if bit < 0 or bit >= len(self._bit_ids):
            print("Set bit index >=0 and <" + str(len(self._bit_ids)))
            return None
        else:
            bit_id = self._bit_ids[bit]
    elif isinstance(bit, str):
        if bit not in self._bit_ids:
            print("Set valid bit id.")
            return None
        else:
            bit_id = bit
    else:
        print("'bit' must be integer index or string identifier")
        return None

    try:
        entity_root = self._readouts_root_path / Path(tile_id) / Path(bit_id)
        self._save_entity_attributes(
            entity_root_path=entity_root,
            updates={"round_linker": int(round_linker)},
        )
    except (TypeError, ValueError):
        print(tile_id, bit_id)
        print("Error writing round linker attribute.")
        return None

save_local_round_transform_zyx_um(transform_zyx_um, tile, round)

Save the local fiducial round transform for one tile.

Parameters:

Name Type Description Default
transform_zyx_um ArrayLike

Homogeneous 4x4 affine transform in physical Z, Y, X microns. The transform maps first-round reference coordinates to coordinates in the requested moving round.

required
tile int | str

Tile index or tile identifier.

required
round int | str

Fiducial round index or round identifier.

required

Returns:

Type Description
None

The transform is stored in the entity attributes for the requested fiducial tile and round.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_round_transform_zyx_um(
    self,
    transform_zyx_um: ArrayLike,
    tile: int | str,
    round: int | str,
) -> None:
    """
    Save the local fiducial round transform for one tile.

    Parameters
    ----------
    transform_zyx_um : ArrayLike
        Homogeneous 4x4 affine transform in physical Z, Y, X microns. The
        transform maps first-round reference coordinates to coordinates in
        the requested moving round.
    tile : int | str
        Tile index or tile identifier.
    round : int | str
        Fiducial round index or round identifier.

    Returns
    -------
    None
        The transform is stored in the entity attributes for the requested
        fiducial tile and round.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None
    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        self._save_entity_attributes(
            entity_root_path=entity_root,
            updates={
                "local_round_transform_zyx_um": np.asarray(
                    transform_zyx_um, dtype=np.float32
                ).tolist()
            },
        )
    except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
        print("Error writing local round transform attribute.")
        return None

save_local_sofima_flow_field(sofima_flow_field_xyz_px, *, tile, round, reference_round, map_stride_zyx_px, map_box_start_xyz_px, map_box_size_xyz_px, reference_shape_zyx_px, moving_shape_zyx_px, sofima_status='ok', valid_flow_vectors=None, return_future=False)

Save the SOFIMA flow field for one local fiducial round.

The saved OME-Zarr image stores the raw float32 SOFIMA map exactly as used in memory. The package convention is channel-first (3, z, y, x) with channels X, Y, Z and spatial axes Z, Y, X. Flow values are relative displacements in reference-image pixels from a reference coordinate to the affine-initialized moving coordinate. map_box_start_xyz_px is the reference coordinate of the first flow sample in X, Y, Z order. SOFIMA patch-correlation vectors are patch-centered, so this is normally half the patch size.

Parameters:

Name Type Description Default
sofima_flow_field_xyz_px ArrayLike

Relative SOFIMA flow field with channels X, Y, Z and spatial axes Z, Y, X.

required
tile int or str

Tile index or tile identifier.

required
round int or str

Moving fiducial round index or identifier.

required
reference_round int or str

Reference fiducial round index or identifier.

required
map_stride_zyx_px Sequence[float]

Flow-field stride in reference pixels in Z, Y, X order.

required
map_box_start_xyz_px Sequence[float]

Reference pixel coordinate of the first flow sample in X, Y, Z order.

required
map_box_size_xyz_px Sequence[float]

Flow-field sample-lattice extent in X, Y, Z order, measured from map_box_start_xyz_px through the last stored map sample.

required
reference_shape_zyx_px Sequence[int]

Reference image shape in Z, Y, X order.

required
moving_shape_zyx_px Sequence[int]

Moving native image shape in Z, Y, X order.

required
sofima_status str

Status reported by the SOFIMA estimator.

"ok"
valid_flow_vectors int or None

Number of valid local vectors before missing-vector fill.

None
return_future bool or None

Return the completed TensorStore write handle when True. Writes finish before associated metadata is reported as saved.

False

Returns:

Type Description
WriteFutures or None

Completed pixel-write handle when return_future is True; otherwise None. Invalid tile or round selections also return None.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_sofima_flow_field(
    self,
    sofima_flow_field_xyz_px: ArrayLike,
    *,
    tile: int | str,
    round: int | str,
    reference_round: int | str,
    map_stride_zyx_px: Sequence[float],
    map_box_start_xyz_px: Sequence[float],
    map_box_size_xyz_px: Sequence[float],
    reference_shape_zyx_px: Sequence[int],
    moving_shape_zyx_px: Sequence[int],
    sofima_status: str = "ok",
    valid_flow_vectors: int | None = None,
    return_future: bool | None = False,
) -> "WriteFutures | None":
    """
    Save the SOFIMA flow field for one local fiducial round.

    The saved OME-Zarr image stores the raw float32 SOFIMA map exactly as
    used in memory. The package convention is channel-first ``(3, z, y,
    x)`` with channels ``X, Y, Z`` and spatial axes ``Z, Y, X``. Flow
    values are relative displacements in reference-image pixels from a
    reference coordinate to the affine-initialized moving coordinate.
    ``map_box_start_xyz_px`` is the reference coordinate of the first flow
    sample in ``X, Y, Z`` order. SOFIMA patch-correlation vectors are
    patch-centered, so this is normally half the patch size.

    Parameters
    ----------
    sofima_flow_field_xyz_px : ArrayLike
        Relative SOFIMA flow field with channels X, Y, Z and spatial axes
        Z, Y, X.
    tile : int or str
        Tile index or tile identifier.
    round : int or str
        Moving fiducial round index or identifier.
    reference_round : int or str
        Reference fiducial round index or identifier.
    map_stride_zyx_px : Sequence[float]
        Flow-field stride in reference pixels in Z, Y, X order.
    map_box_start_xyz_px : Sequence[float]
        Reference pixel coordinate of the first flow sample in X, Y, Z
        order.
    map_box_size_xyz_px : Sequence[float]
        Flow-field sample-lattice extent in X, Y, Z order, measured from
        ``map_box_start_xyz_px`` through the last stored map sample.
    reference_shape_zyx_px : Sequence[int]
        Reference image shape in Z, Y, X order.
    moving_shape_zyx_px : Sequence[int]
        Moving native image shape in Z, Y, X order.
    sofima_status : str, default="ok"
        Status reported by the SOFIMA estimator.
    valid_flow_vectors : int or None, default=None
        Number of valid local vectors before missing-vector fill.
    return_future : bool or None, default=False
        Return the completed TensorStore write handle when True. Writes
        finish before associated metadata is reported as saved.

    Returns
    -------
    tensorstore.WriteFutures or None
        Completed pixel-write handle when return_future is True; otherwise
        None. Invalid tile or round selections also return None.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id")
            return None
        round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    if isinstance(reference_round, int):
        if reference_round < 0 or reference_round >= len(self._round_ids):
            print("Set reference round index >=0 and <" + str(len(self._round_ids)))
            return None
        reference_round_id = self._round_ids[reference_round]
    elif isinstance(reference_round, str):
        if reference_round not in self._round_ids:
            print("Set valid reference round id")
            return None
        reference_round_id = reference_round
    else:
        print("'reference_round' must be integer index or string identifier")
        return None

    image_name = "local_sofima_flow_field"
    entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
    current_local_zarr_path = entity_root / Path(image_name)
    attributes = {
        "registration_backend": "sofima",
        "initial_registration_source": "stored_local_affine_transform",
        "flow_field_name": image_name,
        "flow_direction": (
            f"{reference_round_id}_reference_xyz_px_to_affine_initialized_"
            f"{round_id}_xyz_px"
        ),
        "final_render_direction": (
            f"{reference_round_id}_reference_xyz_px_to_moving_native_xyz_px"
        ),
        "flow_representation": "sofima_relative_coordinate_map",
        "flow_channel_order": "xyz",
        "flow_spatial_order": "zyx",
        "map_stride_zyx_px": np.asarray(
            map_stride_zyx_px, dtype=np.float32
        ).tolist(),
        "map_box_start_xyz_px": np.asarray(
            map_box_start_xyz_px, dtype=np.float32
        ).tolist(),
        "map_box_size_xyz_px": np.asarray(
            map_box_size_xyz_px, dtype=np.float32
        ).tolist(),
        "reference_shape_zyx_px": np.asarray(
            reference_shape_zyx_px, dtype=np.int64
        ).tolist(),
        "moving_shape_zyx_px": np.asarray(
            moving_shape_zyx_px, dtype=np.int64
        ).tolist(),
        "sofima_status": str(sofima_status),
        "interpolation_count_final_image": 1,
    }
    if valid_flow_vectors is not None:
        attributes["valid_flow_vectors"] = int(valid_flow_vectors)

    try:
        write_future = self._save_to_zarr_array(
            np.asarray(sofima_flow_field_xyz_px, dtype=np.float32),
            current_local_zarr_path,
            return_future,
            ome_scale=self.voxel_size_zyx_um,
            extra_attributes=attributes,
        )
        if write_future is not None:
            write_future.result()
        self._save_entity_attributes(
            entity_root_path=entity_root, updates=attributes
        )
        return write_future
    except (OSError, TimeoutError):
        print("Error saving SOFIMA flow field.")
        raise

save_local_stage_position_zyx_um(stage_zyx_um, affine_zyx_px, tile, round)

Save tile stage position for one tile.

Parameters:

Name Type Description Default
stage_zyx_um ArrayLike

Tile stage position in Z, Y, X microns. Two-coordinate Y, X input is accepted and stored as Z, Y, X with Z=0.

required
affine_zyx_px ArrayLike

4x4 homogeneous affine matrix for stage transformation

required
tile int or str

Tile index or tile id.

required
round int or str

Round index or round id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_stage_position_zyx_um(
    self,
    stage_zyx_um: ArrayLike,
    affine_zyx_px: ArrayLike,
    tile: int | str,
    round: int | str,
) -> None:
    """Save tile stage position for one tile.

    Parameters
    ----------
    stage_zyx_um : ArrayLike
        Tile stage position in Z, Y, X microns. Two-coordinate Y, X input
        is accepted and stored as Z, Y, X with Z=0.
    affine_zyx_px: ArrayLike
        4x4 homogeneous affine matrix for stage transformation
    tile : int or str
        Tile index or tile id.
    round : int or str
        Round index or round id.
    """
    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id.")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if isinstance(round, int):
        if round < 0 or round >= len(self._round_ids):
            print("Set round index >=0 and <" + str(self._num_rounds))
            return None
        else:
            round_id = self._round_ids[round]
    elif isinstance(round, str):
        if round not in self._round_ids:
            print("Set valid round id.")
            return None
        else:
            round_id = round
    else:
        print("'round' must be integer index or string identifier")
        return None

    try:
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(round_id)
        stage_zyx_um = self._normalize_stage_position_zyx_um(stage_zyx_um)
        self._save_entity_attributes(
            entity_root_path=entity_root,
            updates={
                "stage_zyx_um": stage_zyx_um.tolist(),
                "affine_zyx_px": np.asarray(
                    affine_zyx_px, dtype=np.float32
                ).tolist(),
            },
        )
        self._update_image_translation_transform(
            entity_root / Path("corrected_data"), stage_zyx_um
        )
    except (TypeError, ValueError):
        print(tile_id, round_id)
        print("Error writing stage position attribute.")
        return None

save_local_wavelengths_um(wavelengths_um, tile, round=None, bit=None)

Save wavelengths for fiducial OR readout bit for one tile.

Parameters:

Name Type Description Default
wavelengths_um tuple[float, float]

Wavelengths for fiducial OR readout bit for one tile.

required
tile int or str

Tile index or tile id.

required
round int or str or None

Round index or round id.

None
bit int or str or None

Bit index or bit id.

None

Returns:

Name Type Description
wavelengths_um tuple[float, float] or None

Wavelengths for fiducial OR readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_wavelengths_um(
    self,
    wavelengths_um: tuple[float, float],
    tile: int | str,
    round: int | str | None = None,
    bit: int | str | None = None,
) -> tuple[float, float] | None:
    """Save wavelengths for fiducial OR readout bit for one tile.

    Parameters
    ----------
    wavelengths_um : tuple[float, float]
        Wavelengths for fiducial OR readout bit for one tile.
    tile : int or str
        Tile index or tile id.
    round : int or str or None
        Round index or round id.
    bit : int or str or None
        Bit index or bit id.

    Returns
    -------
    wavelengths_um : tuple[float, float] or None
        Wavelengths for fiducial OR readout bit for one tile.
    """
    if (round is None and bit is None) or (round is not None and bit is not None):
        print("Provide either 'round' or 'bit', but not both")
        return None

    if isinstance(tile, int):
        if tile < 0 or tile >= self._num_tiles:
            print("Set tile index >=0 and <" + str(self._num_tiles))
            return None
        else:
            tile_id = self._tile_ids[tile]
    elif isinstance(tile, str):
        if tile not in self._tile_ids:
            print("set valid tiled id")
            return None
        else:
            tile_id = tile
    else:
        print("'tile' must be integer index or string identifier")
        return None

    if bit is not None:
        if isinstance(bit, int):
            if bit < 0 or bit >= len(self._bit_ids):
                print("Set bit index >=0 and <" + str(len(self._bit_ids)))
                return None
            else:
                local_id = self._bit_ids[bit]
        elif isinstance(bit, str):
            if bit not in self._bit_ids:
                print("Set valid bit id")
                return None
            else:
                local_id = bit
        else:
            print("'bit' must be integer index or string identifier")
            return None
        entity_root = self._readouts_root_path / Path(tile_id) / Path(local_id)
    else:
        if isinstance(round, int):
            if round < 0 or round >= len(self._round_ids):
                print("Set round index >=0 and <" + str(self._num_rounds))
                return None
            else:
                local_id = self._round_ids[round]
        elif isinstance(round, str):
            if round not in self._round_ids:
                print("Set valid round id")
                return None
            else:
                local_id = round
        else:
            print("'round' must be integer index or string identifier")
            return None
        entity_root = self._fiducial_root_path / Path(tile_id) / Path(local_id)

    try:
        self._save_entity_attributes(
            entity_root_path=entity_root,
            updates={
                "excitation_um": float(wavelengths_um[0]),
                "emission_um": float(wavelengths_um[1]),
            },
        )
    except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
        print("Error writing wavelength attributes.")
        return None