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 Union[str, Path]

Path to qi2lab MERFISH store

required

Methods:

Name Description
initialize_tile

Initialize directory structure for a tile.

load_codebook_parsed

Load and split codebook into gene_ids and codebook matrix.

load_coord_of_xform_px

Local fidicual optical flow matrix for one round and tile.

load_global_baysor_filtered_spots

Load Baysor re-assigned decoded RNA.

load_global_baysor_outlines

Load Baysor cell outlines.

load_global_cellpose_outlines

Load Cellpose max projection cell outlines.

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_fidicual_image

Load downsampled, fused fidicual image.

load_global_filtered_decoded_spots

Load all decoded and filtered spots.

load_local_bit_linker

Load readout bits linked to fidicual 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_registered_image

Local registered, deconvolved image for fidiculial OR readout bit for one tile.

load_local_rigid_xform_xyz_px

Load calculated rigid registration transform for one round and tile.

load_local_round_linker

Load fidicual round linked to readout bit for one tile.

load_local_stage_position_zyx_um

Load tile stage position for one tile.

load_local_ufish_image

Load readout bit U-FISH prediction image for one tile.

load_local_ufish_spots

Load U-FISH spot localizations and features for one tile.

load_local_wavelengths_um

Load wavelengths for fidicual OR readout bit for one tile.

reformat_baysor_3D_oultines

Reformat baysor 3D json file into ImageJ ROIs.

reprocess_and_save_filtered_spots_with_baysor_outlines

Reprocess filtered spots using baysor cell outlines, then save.

run_baysor

Run Baysor"

save_coord_of_xform_px

Save fidicual optical flow matrix for one round and tile.

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_fidicual_image

Save downsampled, fused fidicual image.

save_global_filtered_decoded_spots

Save all decoded and filtered spots.

save_local_bit_linker

Save readout bits linked to fidicual 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_registered_image

Save registered, deconvolved image.

save_local_rigid_xform_xyz_px

Save calculated rigid registration transform for one round and tile.

save_local_round_linker

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

save_local_stage_position_zyx_um

Save tile stage position for one tile.

save_local_ufish_image

Save U-FISH prediction image.

save_local_ufish_spots

Save U-FISH localizations and features.

save_local_wavelengths_um

Save wavelengths for fidicual OR readout bit for one tile.

save_mtx

Save mtx file for downstream analysis. Assumes Baysor has been run.

save_spots_prepped_for_baysor

Save spots prepped for Baysor.

Attributes:

Name Type Description
baysor_options Union[Path, str]

Baysor options

baysor_path Union[Path, str]

Baysor path

binning Optional[int]

Camera binning.

bit_ids Optional[Collection[str]]

Bit IDs.

camera_model Optional[str]

Camera model.

channel_psfs Optional[ArrayLike]

Channel point spread functions (PSF).

channel_shading_maps Optional[ArrayLike]

Channel shaiding images.

channels_in_data Optional[Collection[int]]

Channel indices.

codebook Optional[DataFrame]

Codebook.

datastore_state Optional[dict]

Datastore state.

e_per_ADU Optional[float]

Electrons per camera ADU.

experiment_order Optional[DataFrame]

Round and bit order.

global_background_vector Optional[ArrayLike]

Global background vector.

global_normalization_vector Optional[ArrayLike]

Global normalization vector.

iterative_background_vector Optional[ArrayLike]

Iterative background vector.

iterative_normalization_vector Optional[ArrayLike]

Iterative normalization vector.

julia_threads int

Julia thread number

microscope_type Optional[str]

Microscope type.

na Optional[float]

Detection objective numerical aperture (NA).

noise_map Optional[ArrayLike]

Camera noise image.

num_bits int

Number of bits.

num_rounds Optional[int]

Number of rounds.

num_tiles Optional[int]

Number of tiles.

ri Optional[float]

Detection objective refractive index (RI).

round_ids Optional[Collection[str]]

Round IDs.

tile_ids Optional[Collection[str]]

Tile IDs.

tile_overlap Optional[float]

XY tile overlap.

voxel_size_zyx_um Optional[ArrayLike]

Voxel size, zyx order (microns).

Source code in src/merfish3danalysis/qi2labDataStore.py
  33
  34
  35
  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
class qi2labDataStore:
    """API to qi2lab MERFISH store.

    Parameters
    ----------
    datastore_path : Union[str, Path]
        Path to qi2lab MERFISH store

    """

    def __init__(self, datastore_path: Union[str, Path]):
        compressor = {
            "id": "blosc",
            "cname": "zstd",
            "clevel": 5,
            "shuffle": 2,
        }
        self._zarrv2_spec = {
            "driver": "zarr",
            "kvstore": None,
            "metadata": {"compressor": compressor},
            "open": True,
            "assume_metadata": False,
            "create": True,
            "delete_existing": False,
        }

        self._datastore_path = Path(datastore_path)
        if self._datastore_path.exists():
            self._parse_datastore()
        else:
            self._init_datastore()

    @property
    def datastore_state(self) -> Optional[dict]:
        """Datastore state.

        Returns
        -------
        datastore_state : Optional[dict]
            Datastore state.
        """

        return getattr(self, "_datastore_state", None)

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

        Parameters
        ----------
        value : dict
            New datastore state.
        """

        if not hasattr(self, "_datastore_state") or self._datastore_state is None:
            self._datastore_state = value
        else:
            self._datastore_state.update(value)
        self._save_to_json(self._datastore_state, self._datastore_state_json_path)

    @property
    def microscope_type(self) -> Optional[str]:
        """Microscope type.

        Returns
        -------
        microscope_type : Optional[str]
            Microscope type.
        """

        return getattr(self, "_microscope_type", None)

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

        Parameters
        ----------
        value : str
            New microscope type.
        """

        self._microscope_type = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["microscope_type"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def camera_model(self) -> Optional[str]:
        """Camera model.

        Returns
        -------
        camera_model : Optional[str]
            Camera model.
        """

        return getattr(self, "_camera_model", None)

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

        Parameters
        ----------
        value : str
            New camera model.
        """
        self._camera_model = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["camera_model"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def num_rounds(self) -> Optional[int]:
        """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):
        """Set the number of rounds.

        Parameters
        ----------
        value : int
            New number of rounds.
        """

        self._num_rounds = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["num_rounds"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

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

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

    @property
    def num_tiles(self) -> Optional[int]:
        """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):
        """Set the number of tiles.

        Parameters
        ----------
        value : int
            New number of tiles.
        """

        self._num_tiles = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["num_tiles"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

        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) -> Optional[Collection[int]]:
        """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]):
        """Set the channels in the data.

        Parameters
        ----------
        value : Collection[int]
            New channels in data (int values starting from zero).
        """

        self._channels_in_data = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["channels_in_data"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def tile_overlap(self) -> Optional[float]:
        """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):
        """Set the tile overlap.

        Parameters
        ----------
        value : float
            New tile overlap.
        """

        self._tile_overlap = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["tile_overlap"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def binning(self) -> Optional[int]:
        """Camera binning.

        Returns
        -------
        binning : int
            Camera binning.
        """

        return getattr(self, "_binning", None)

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

        Parameters
        ----------
        value : int
            New camera binning.
        """

        self._binning = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["binning"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def e_per_ADU(self) -> Optional[float]:
        """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):
        """Set the camera conversion (e- per ADU).

        Parameters
        ----------
        value : float
            New camera conversion (e- per ADU).
        """

        self._e_per_ADU = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["e_per_ADU"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def na(self) -> Optional[float]:
        """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):
        """Set detection objective numerical aperture (NA).

        Parameters
        ----------
        value: float
            New detection objective numerical aperture (NA)
        """

        self._na = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["na"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def ri(self) -> Optional[float]:
        """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):
        """Set detection objective refractive index (RI).

        Parameters
        ----------
        value: float
            New detection objective refractive index (RI)
        """

        self._ri = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["ri"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def noise_map(self) -> Optional[ArrayLike]:
        """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):
        """Set the camera noise image.

        Parameters
        ----------
        value : ArrayLike
            New camera noise image.
        """

        self._noise_map = value
        current_local_zarr_path = str(self._calibrations_zarr_path / Path("noise_map"))

        try:
            self._save_to_zarr_array(
                value,
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec,
                return_future=False,
            )
        except (IOError, OSError, ZarrError):
            print(r"Could not access calibrations.zarr/noise_map")

    @property
    def channel_shading_maps(self) -> Optional[ArrayLike]:
        """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):
        """Set the channel shading images.

        Parameters
        ----------
        value : ArrayLike
            New channel shading images.
        """

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

        try:
            self._save_to_zarr_array(
                value,
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec,
                return_future=False,
            )
        except (IOError, OSError, ZarrError):
            print(r"Could not access calibrations.zarr/shading_maps")

    @property
    def channel_psfs(self) -> Optional[ArrayLike]:
        """Channel point spread functions (PSF).

        Return
        ------
        channel_psfs : ArrayLike
            Channel point spread functions (PSF).
        """

        return getattr(self, "_psfs", None)

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

        Parameters
        ----------
        value : ArrayLike
            New channel point spread functions (PSF).
        """

        self._psfs = value
        current_local_zarr_path = str(self._calibrations_zarr_path / Path("psf_data"))

        try:
            self._save_to_zarr_array(
                value,
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
                return_future=False,
            )
        except (IOError, ValueError):
            print(r"Could not access calibrations.zarr/psf_data")

    @property
    def experiment_order(self) -> Optional[pd.DataFrame]:
        """Round and bit order.

        Returns
        -------
        experiment_order : pd.DataFrame
            Round and bit order.
        """

        return getattr(self, "_experiment_order", None)

    @experiment_order.setter
    def experiment_order(self, value: Union[ArrayLike, pd.DataFrame]):
        """Set the round and bit order.

        Parameters
        ----------
        value : Union[ArrayLike, pd.DataFrame]
            New round and bit order.
        """

        if isinstance(value, pd.DataFrame):
            self._experiment_order = value
        else:
            channel_list = []
            for idx in range(len(self._channels_in_data)):
                channel_list.append(str(self._channels_in_data[idx]))
            self._experiment_order = pd.DataFrame(
                value, columns=channel_list, dtype="int64"
            )

        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["exp_order"] = self._experiment_order.values.tolist()
        self._save_to_json(calib_zattrs, zattrs_path)

        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."
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["num_round"] = self.num_rounds
        self._save_to_json(calib_zattrs, zattrs_path)

        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."
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["num_bits"] = self.num_bits
        self._save_to_json(calib_zattrs, zattrs_path)

        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) -> Optional[pd.DataFrame]:
        """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):
        """Set the codebook.

        Parameters
        ----------
        value : pd.DataFrame
            New codebook.
        """

        self._codebook = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["codebook"] = self._codebook.values.tolist()
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def voxel_size_zyx_um(self) -> Optional[ArrayLike]:
        """Voxel size, zyx order (microns).

        Returns
        -------
        voxel_size_zyx_um : ArrayLike
            Voxel size, zyx order (microns).
        """

        return getattr(self, "_voxel_size_zyx_um", None)

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

        Parameters
        ----------
        value : ArrayLike
            New voxel size, zyx order (microns).
        """

        self._voxel_size_zyx_um = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["voxel_size_zyx_um"] = value
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def baysor_path(self) -> Union[Path,str]:
        """Baysor path

        Returns
        -------
        baysor_path : Union[Path,str]
            Baysor path.
        """

        return getattr(self,"_baysor_path",None)

    @baysor_path.setter
    def baysor_path(self, value: Union[Path,str]):
        """Set the baysor path.

        Parameters
        ----------
        value : Union[Path,str]
            New baysor path.
        """

        if value is None:
            self._baysor_path = None
            self._datastore_state["BaysorPath"] = None
        else:
            self._baysor_path = Path(value)
            self._datastore_state["BaysorPath"] = str(self._baysor_path)
        self._save_to_json(self._datastore_state, self._datastore_state_json_path)

    @property
    def baysor_options(self) -> Union[Path,str]:
        """Baysor options

        Returns
        -------
        baysor_options : Union[Path,str]
            Baysor options.
        """
        return getattr(self,"_baysor_options",None)

    @baysor_options.setter
    def baysor_options(self, value: Union[Path,str]):
        """Set the baysor options.

        Parameters
        ----------
        value : Union[Path,str]
            New baysor options.
        """

        if value is None:
            self._baysor_path = None
            self._datastore_state["BaysorPath"] = None
        else:
            self._baysor_options = Path(value)
            self._datastore_state["BaysorOptions"] = str(self._baysor_options)
        self._save_to_json(self._datastore_state, self._datastore_state_json_path)

    @property
    def julia_threads(self) -> int:
        """Julia thread number

        Returns
        -------
        julia_threads : int
            Julia thread number.
        """

        return getattr(self,"_julia_threads",None)

    @julia_threads.setter
    def julia_threads(self, value: int):
        """Set the julia thread number.

        Parameters
        ----------
        value : int
            New julia thread number.
        """

        self._julia_threads = value
        self._datastore_state["JuliaThreads"] = str(self._julia_threads)
        self._save_to_json(self._datastore_state, self._datastore_state_json_path)

    @property
    def global_normalization_vector(self) -> Optional[ArrayLike]:
        """Global normalization vector.

        Returns
        -------
        global_normalization_vector : ArrayLike
            Global normalization vector.
        """

        value = getattr(self, "_global_normalization_vector", None)
        if value is None:
            zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
            calib_zattrs = self._load_from_json(zattrs_path)

            try:
                value = np.asarray(
                    calib_zattrs["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):
        """Set the global normalization vector.

        Parameters
        ----------
        value : ArrayLike
            New global normalization vector.
        """

        self._global_normalization_vector = np.asarray(value, dtype=np.float32)
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["global_normalization_vector"] = (
            self._global_normalization_vector.tolist()
        )
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def global_background_vector(self) -> Optional[ArrayLike]:
        """Global background vector.

        Returns
        -------
        global_background_vector : ArrayLike
            Global background vector.
        """

        value = getattr(self, "_global_background_vector", None)
        if value is None:
            zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
            calib_zattrs = self._load_from_json(zattrs_path)
            try:
                value = np.asarray(
                    calib_zattrs["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):
        """Set the global background vector.

        Parameters
        ----------
        value : ArrayLike
            New global background vector.
        """

        self._global_background_vector = np.asarray(value, dtype=np.float32)
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["global_background_vector"] = (
            self._global_background_vector.tolist()
        )
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def iterative_normalization_vector(self) -> Optional[ArrayLike]:
        """Iterative normalization vector.

        Returns
        -------
        iterative_normalization_vector : ArrayLike
            Iterative normalization vector.
        """

        value = getattr(self, "_iterative_normalization_vector", None)
        if value is None:
            zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
            calib_zattrs = self._load_from_json(zattrs_path)
            try:
                value = np.asarray(
                    calib_zattrs["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):
        """Set the iterative normalization vector.

        Parameters
        ----------
        value : ArrayLike
            New iterative normalization vector.
        """

        self._iterative_normalization_vector = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["iterative_normalization_vector"] = (
            self._iterative_normalization_vector.tolist()
        )
        self._save_to_json(calib_zattrs, zattrs_path)

    @property
    def iterative_background_vector(self) -> Optional[ArrayLike]:
        """Iterative background vector.

        Returns
        -------
        iterative_background_vector : ArrayLike
            Iterative background vector.
        """

        value = getattr(self, "_iterative_background_vector", None)
        if value is None:
            zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
            calib_zattrs = self._load_from_json(zattrs_path)
            try:
                value = np.asarray(
                    calib_zattrs["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):
        """Set the iterative background vector.

        Parameters
        ----------
        value : ArrayLike
            New iterative background vector.
        """

        self._iterative_background_vector = value
        zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
        calib_zattrs = self._load_from_json(zattrs_path)
        calib_zattrs["iterative_background_vector"] = (
            self._iterative_background_vector.tolist()
        )
        self._save_to_json(calib_zattrs, zattrs_path)

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

        Returns
        -------
        tile_ids : Collection[str]
            Tile IDs.
        """

        return getattr(self, "_tile_ids", None)

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

        Returns
        -------
        round_ids : Collection[str]
            Round IDs.
        """

        return getattr(self, "_round_ids", None)

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

        Returns
        -------
        bit_ids : Collection[str]
            Bit IDs.
        """

        return getattr(self, "_bit_ids", None)

    def _init_datastore(self):
        """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.zarr")
        self._calibrations_zarr_path.mkdir()
        calibrations_zattrs_path = self._calibrations_zarr_path / Path(r".zattrs")
        empty_zattrs = {}
        self._save_to_json(empty_zattrs, calibrations_zattrs_path)
        self._polyDT_root_path = self._datastore_path / Path(r"polyDT")
        self._polyDT_root_path.mkdir()
        self._readouts_root_path = self._datastore_path / Path(r"readouts")
        self._readouts_root_path.mkdir()
        self._ufish_localizations_root_path = self._datastore_path / Path(
            r"ufish_localizations"
        )
        self._ufish_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()
        self._mtx_output_root_path = self._datastore_path / Path(r"mtx_output")
        self._mtx_output_root_path.mkdir()
        self._baysor_path = r""
        self._baysor_options = r""
        self._julia_threads = 0

        # initialize datastore state
        self._datastore_state_json_path = self._datastore_path / Path(
            r"datastore_state.json"
        )
        self._datastore_state = {
            "Version": 0.3,
            "Initialized": True,
            "Calibrations": False,
            "Corrected": False,
            "LocalRegistered": False,
            "GlobalRegistered": False,
            "Fused": False,
            "SegmentedCells": False,
            "DecodedSpots": False,
            "FilteredSpots": False,
            "RefinedSpots": False,
            "mtxOutput": False,
            "BaysorPath": str(self._baysor_path),
            "BaysorOptions": str(self._baysor_options),
            "JuliaThreads": str(self._julia_threads)
        }

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

    @staticmethod
    def _get_kvstore_key(path: Union[Path, str]) -> dict:
        """Convert datastore location to tensorstore kvstore key.

        Parameters
        ----------
        path : Union[Path, str]
            Datastore location.

        Returns
        -------
        kvstore_key : dict
            Tensorstore kvstore key.
        """

        path_str = str(path)
        if path_str.startswith("s3://") or "s3.amazonaws.com" in path_str:
            return {"driver": "s3", "path": path_str}
        elif path_str.startswith("gs://") or "storage.googleapis.com" in path_str:
            return {"driver": "gcs", "path": path_str}
        elif path_str.startswith("azure://") or "blob.core.windows.net" in path_str:
            return {"driver": "azure", "path": path_str}
        elif path_str.startswith("http://") or path_str.startswith("https://"):
            raise ValueError("Unsupported cloud storage provider in URL")
        else:
            return {"driver": "file", "path": path_str}

    @staticmethod
    def _load_from_json(dictionary_path: Union[Path, str]) -> dict:
        """Load json as dictionary.

        Parameters
        ----------
        dictionary_path : Union[Path, str]
            Path to json file.

        Returns
        -------
        dictionary : dict
            Dictionary from json file.
        """

        try:
            with open(dictionary_path, "r") as f:
                dictionary = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            dictionary = {}
        return dictionary

    @staticmethod
    def _save_to_json(dictionary: dict, dictionary_path: Union[Path, str]):
        """Save dictionary to json.

        Parameters
        ----------
        dictionary : dict
            The data to be saved.
        dictionary_path : Union[Path,str]
            The path to the JSON file where the data will be saved.
        """

        with open(dictionary_path, "w") as file:
            json.dump(dictionary, file, indent=4)

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

        Parameters
        ----------
        dictionary_path : Union[Path, str]
            Path to microjson file.

        Returns
        -------
        outlines : dict
            Cell outlines dictionary.
        """

        try:
            with open(dictionary_path, "r") 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(kvstore: Union[Path, str], spec: dict):
        """Check if zarr array exists using Tensortore.

        Parameters
        ----------
        kvstore : Union[Path, str]
            Datastore location.
        spec : dict
            Zarr specification.
        """

        current_zarr = ts.open(
            {
                **spec,
                "kvstore": kvstore,
            }
        ).result()

        del current_zarr

    @staticmethod
    def _load_from_zarr_array(
        kvstore: dict, spec: dict, return_future=True
    ) -> ArrayLike:
        """Return tensorstore array from zarr

        Defaults to returning future result.

        Parameters
        ----------
        kvstore : dict
            Tensorstore kvstore specification.
        spec : dict
            Tensorstore zarr specification.
        return_future : bool
            Return future (True) or immediately read (False).

        Returns
        -------
        array : ArrayLike
            Delayed (future) or immediate array.
        """

        current_zarr = ts.open(
            {
                **spec,
                "kvstore": kvstore,
            }
        ).result()

        read_future = current_zarr.read()

        if return_future:
            return read_future
        else:
            return read_future.result()

    @staticmethod
    def _save_to_zarr_array(
        array: ArrayLike,
        kvstore: dict,
        spec: dict,
        return_future: Optional[bool] = False,
    ) -> Optional[ArrayLike]:
        """Save array to zarr using tensorstore.

        Defaults to returning future result.

        Parameters
        ----------
        array : ArrayLike
            Array to save.
        kvstore : dict
            Tensorstore kvstore specification.
        spec : dict
            Tensorstore zarr specification.
        return_future : Optional[bool]
            Return future (True) or immediately write (False).

        Returns
        -------
        write_future : Optional[ArrayLike]
            Delayed (future) if return_future is True.
        """

        # check datatype
        if str(array.dtype) == "uint8":
            array_dtype = "<u1"
        elif str(array.dtype) == "uint16":
            array_dtype = "<u2"
        elif str(array.dtype) == "float16":
            array_dtype = "<f2"
        elif str(array.dtype) == "float32":
            array_dtype = "<f4"
        else:
            print("Unsupported data type: " + str(array.dtype))
            return None

        # check array dimension
        spec["metadata"]["shape"] = array.shape
        if len(array.shape) == 2:
            spec["metadata"]["chunks"] = [array.shape[0], array.shape[1]]
        elif len(array.shape) == 3:
            spec["metadata"]["chunks"] = [1, array.shape[1], array.shape[2]]
        elif len(array.shape) == 4:
            spec["metadata"]["chunks"] = [1, 1, array.shape[1], array.shape[2]]
        spec["metadata"]["dtype"] = array_dtype

        try:
            current_zarr = ts.open(
                {
                    **spec,
                    "kvstore": kvstore,
                }
            ).result()

            write_future = current_zarr.write(array)

            if return_future:
                return write_future
            else:
                write_future.result()
                return None
        except (IOError, OSError, TimeoutError):
            print("Error writing zarr array.")

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

        Parameters
        ----------
        parquet_path : Union[Path, 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: Union[Path, str]):
        """Save dataframe to parquet.

        Parameters
        ----------
        df : pd.DataFrame
            Dataframe to save.
        parquet_path : Union[Path, str]
            Path to parquet file.
        """

        df.to_parquet(parquet_path)

    def _parse_datastore(self):
        """Parse datastore to discover available components."""

        # directory structure as defined by qi2lab spec
        self._calibrations_zarr_path = self._datastore_path / Path(r"calibrations.zarr")
        self._polyDT_root_path = self._datastore_path / Path(r"polyDT")
        self._readouts_root_path = self._datastore_path / Path(r"readouts")
        self._ufish_localizations_root_path = self._datastore_path / Path(
            r"ufish_localizations"
        )
        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")
        self._mtx_output_root_path = self._datastore_path / Path(r"mtx_output")
        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, "r") as json_file:
            self._datastore_state = json.load(json_file)

        # validate calibrations.zarr
        if self._datastore_state["Calibrations"]:
            if not (self._calibrations_zarr_path.exists()):
                print("Calibration data error.")
            try:
                zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
                attributes = self._load_from_json(zattrs_path)
            except (FileNotFoundError, json.JSONDecodeError):
                print("Calibration attributes not found")

            keys_to_check = [
                "num_rounds",
                "num_tiles",
                "channels_in_data",
                "tile_overlap",
                "binning",
                "e_per_ADU",
                "na",
                "ri",
                "exp_order",
                "codebook",
                "num_bits"
            ]
            if self._datastore_state["Version"] == 0.3:
                keys_to_check.append("microscope_type")
                keys_to_check.append("camera_model")
                keys_to_check.append("voxel_size_zyx_um")
            for key in keys_to_check:
                if key not in attributes.keys():
                    raise KeyError("Calibration attributes incomplete")
                else:
                    setattr(self, "_" + key, attributes[key])

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

            try:
                self._psfs = (
                    self._load_from_zarr_array(
                        kvstore=self._get_kvstore_key(current_local_zarr_path),
                        spec=self._zarrv2_spec.copy(),
                    )
                ).result()
            except (IOError, OSError, ZarrError):
                print("Calibration psfs missing.")

            del current_local_zarr_path

            # current_local_zarr_path = str(
            #     self._calibrations_zarr_path / Path("noise_map")
            # )

            # try:
            #     self._noise_map = (
            #         self._load_from_zarr_array(
            #             kvstore=self._get_kvstore_key(current_local_zarr_path),
            #             spec=self._zarrv2_spec,
            #         )
            #     ).result()
            # except Exception:
            #     print("Calibration noise map missing.")

        # validate polyDT and readout bits data
        if self._datastore_state["Corrected"]:
            if not (self._polyDT_root_path.exists()):
                raise FileNotFoundError("PolyDT directory not initialized")
            else:
                polyDT_tile_ids = sorted(
                    [
                        entry.name
                        for entry in self._polyDT_root_path.iterdir()
                        if entry.is_dir()
                    ],
                    key=lambda x: int(x.split("tile")[1].split(".zarr")[0]),
                )
                current_tile_dir_path = self._polyDT_root_path / Path(
                    polyDT_tile_ids[0]
                )
                self._round_ids = sorted(
                    [
                        entry.name.split(".")[0]
                        for entry in current_tile_dir_path.iterdir()
                        if entry.is_dir()
                    ],
                    key=lambda x: int(x.split("round")[1].split(".zarr")[0]),
                )
            if not (self._readouts_root_path.exists()):
                raise FileNotFoundError("Readout directory not initialized")
            else:
                readout_tile_ids = sorted(
                    [
                        entry.name
                        for entry in self._readouts_root_path.iterdir()
                        if entry.is_dir()
                    ],
                    key=lambda x: int(x.split("tile")[1].split(".zarr")[0]),
                )
                current_tile_dir_path = self._readouts_root_path / Path(
                    readout_tile_ids[0]
                )
                self._bit_ids = sorted(
                    [
                        entry.name.split(".")[0]
                        for entry in current_tile_dir_path.iterdir()
                        if entry.is_dir()
                    ],
                    key=lambda x: int(x.split("bit")[1].split(".zarr")[0]),
                )
            assert (
                polyDT_tile_ids == readout_tile_ids
            ), "polyDT and readout tile ids do not match. Conversion error."
            self._tile_ids = polyDT_tile_ids.copy()
            del polyDT_tile_ids, readout_tile_ids

            for tile_id, round_id in product(self._tile_ids, self._round_ids):
                try:
                    zattrs_path = str(
                        self._polyDT_root_path
                        / Path(tile_id)
                        / Path(round_id + ".zarr")
                        / Path(".zattrs")
                    )
                    attributes = self._load_from_json(zattrs_path)
                except (FileNotFoundError, json.JSONDecodeError):
                    print("polyDT tile attributes not found")

                keys_to_check = [
                    "stage_zyx_um",
                    "excitation_um",
                    "emission_um",
                    "bit_linker",
                    # "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 polyDT attributes incomplete")

                current_local_zarr_path = str(
                    self._polyDT_root_path
                    / Path(tile_id)
                    / Path(round_id + ".zarr")
                    / Path("corrected_data")
                )

                try:
                    self._check_for_zarr_array(
                        self._get_kvstore_key(current_local_zarr_path),
                        self._zarrv2_spec.copy(),
                    )
                except (IOError, OSError, ZarrError):
                    print(tile_id, round_id)
                    print("Corrected polyDT data missing.")

            for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
                try:
                    zattrs_path = str(
                        self._readouts_root_path
                        / Path(tile_id)
                        / Path(bit_id + ".zarr")
                        / Path(".zattrs")
                    )
                    attributes = self._load_from_json(zattrs_path)
                except (FileNotFoundError, json.JSONDecodeError):
                    print("Readout tile attributes not found")

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

                current_local_zarr_path = str(
                    self._readouts_root_path
                    / Path(tile_id)
                    / Path(bit_id + ".zarr")
                    / Path("corrected_data")
                )

                try:
                    self._check_for_zarr_array(
                        self._get_kvstore_key(current_local_zarr_path),
                        self._zarrv2_spec.copy(),
                    )
                except (IOError, OSError, ZarrError):
                    print(tile_id, bit_id)
                    print("Corrected readout data missing.")

        # check and validate local registered data
        if self._datastore_state["LocalRegistered"]:
            for tile_id, round_id in product(self._tile_ids, self._round_ids):
                if round_id is not self._round_ids[0]:
                    try:
                        zattrs_path = str(
                            self._polyDT_root_path
                            / Path(tile_id)
                            / Path(round_id + ".zarr")
                            / Path(".zattrs")
                        )
                        with open(zattrs_path, "r") as f:
                            attributes = json.load(f)
                    except (FileNotFoundError, json.JSONDecodeError):
                        print("polyDT tile attributes not found")

                    keys_to_check = ["rigid_xform_xyz_px"]

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

                    current_local_zarr_path = str(
                        self._polyDT_root_path
                        / Path(tile_id)
                        / Path(round_id + ".zarr")
                        / Path("of_xform_px")
                    )

                    try:
                        self._check_for_zarr_array(
                            self._get_kvstore_key(current_local_zarr_path),
                            self._zarrv2_spec.copy(),
                        )
                    except (IOError, OSError, ZarrError):
                        print(tile_id, round_id)
                        print("Optical flow registration data missing.")

                current_local_zarr_path = str(
                    self._polyDT_root_path
                    / Path(tile_id)
                    / Path(round_id + ".zarr")
                    / Path("registered_decon_data")
                )
                if round_id is self._round_ids[0]:
                    try:
                        self._check_for_zarr_array(
                            self._get_kvstore_key(current_local_zarr_path),
                            self._zarrv2_spec.copy(),
                        )
                    except (IOError, OSError, ZarrError):
                        print(tile_id, round_id)
                        print("Registered polyDT data missing.")

            for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
                current_local_zarr_path = str(
                    self._readouts_root_path
                    / Path(tile_id)
                    / Path(bit_id + ".zarr")
                    / Path("registered_decon_data")
                )

                try:
                    self._check_for_zarr_array(
                        self._get_kvstore_key(current_local_zarr_path),
                        self._zarrv2_spec.copy(),
                    )
                except (IOError, OSError, ZarrError):
                    print(tile_id, round_id)
                    print("Registered readout data missing.")

                current_local_zarr_path = str(
                    self._readouts_root_path
                    / Path(tile_id)
                    / Path(bit_id + ".zarr")
                    / Path("registered_ufish_data")
                )

                try:
                    self._check_for_zarr_array(
                        self._get_kvstore_key(current_local_zarr_path),
                        self._zarrv2_spec.copy(),
                    )
                except (IOError, OSError, ZarrError):
                    print(tile_id, round_id)
                    print("Registered ufish prediction missing.")

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

        # check and validate global registered data
        if self._datastore_state["GlobalRegistered"]:
            for tile_id in self._tile_ids:
                try:
                    zattrs_path = str(
                        self._polyDT_root_path
                        / Path(tile_id)
                        / Path(self._round_ids[0] + ".zarr")
                        / Path(".zattrs")
                    )
                    with open(zattrs_path, "r") as f:
                        attributes = json.load(f)
                except (FileNotFoundError, json.JSONDecodeError):
                    print("polyDT tile attributes not found")

                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"]:
            try:
                zattrs_path = str(
                    self._fused_root_path
                    / Path("fused.zarr")
                    / Path("fused_polyDT_iso_zyx")
                    / Path(".zattrs")
                )
                with open(zattrs_path, "r") as f:
                    attributes = json.load(f)
            except (FileNotFoundError, json.JSONDecodeError):
                print("Fused image attributes not found")

            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(
                self._fused_root_path
                / Path("fused.zarr")
                / Path("fused_polyDT_iso_zyx")
            )

            try:
                self._check_for_zarr_array(
                    self._get_kvstore_key(current_local_zarr_path),
                    self._zarrv2_spec.copy(),
                )
            except (IOError, OSError, ZarrError):
                print("Fused data missing.")

        # check and validate cellpose segmentation
        if self._datastore_state["SegmentedCells"]:
            current_local_zarr_path = str(
                self._segmentation_root_path
                / Path("cellpose")
                / Path("cellpose.zarr")
                / Path("masks_polyDT_iso_zyx")
            )

            try:
                self._check_for_zarr_array(
                    self._get_kvstore_key(current_local_zarr_path),
                    self._zarrv2_spec.copy(),
                )
            except (IOError, OSError, ZarrError):
                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"]:
            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"]:
            filtered_path = self._decoded_root_path / Path(
                "all_tiles_filtered_decoded_features.parquet"
            )

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

        if self._datastore_state["RefinedSpots"]:
            baysor_spots_path = (
                self._segmentation_root_path
                / Path("baysor")
                / Path("segmentation.csv")
            )

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

        # check and validate mtx
        if self._datastore_state["mtxOutput"]:
            mtx_barcodes_path = self._mtx_output_root_path / Path("barcodes.tsv.gz")
            mtx_features_path = self._mtx_output_root_path / Path("features.tsv.gz")
            mtx_matrix_path = self._mtx_output_root_path / Path("matrix.tsv.gz")

            if (
                not (mtx_barcodes_path.exists())
                or not (mtx_features_path.exists())
                or not (mtx_matrix_path.exists())
            ):
                raise FileNotFoundError("mtx output missing.")

        try:
            self._baysor_path = Path(str(self._datastore_state["BaysorPath"]))
            self._baysor_options = Path(str(self._datastore_state["BaysorOptions"]))
            self._julia_threads = int(self._datastore_state["JuliaThreads"])
        except KeyError:
            self._baysor_path = r""
            self._baysor_options = r""
            self._julia_threads = 1

    def load_codebook_parsed(
        self,
    ) -> Optional[tuple[Collection[str], ArrayLike]]:
        """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: Union[int, str],
    ):
        """Initialize directory structure for a tile.

        Parameters
        ----------
        tile : Union[int, 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:
            polyDT_tile_path = self._polyDT_root_path / Path(tile_id)
            polyDT_tile_path.mkdir()
            for round_idx, round_id in enumerate(self._round_ids):
                polyDT_round_path = polyDT_tile_path / Path(round_id + ".zarr")
                polyDT_round_path.mkdir()
                polydt_round_attrs_path = polyDT_round_path / Path(".zattrs")
                round_attrs = {
                    "bit_linker": self._experiment_order.to_numpy()[round_idx, 1:]
                    .astype(int)
                    .tolist(),
                }
                self._save_to_json(round_attrs, polydt_round_attrs_path)
        except FileExistsError:
            print("Error creating polyDT 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 + ".zarr")
                readout_bit_path.mkdir()
                readout_bit_attrs_path = readout_bit_path / Path(".zattrs")
                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: Union[int, str],
        round: Union[int, str],
    ) -> Optional[Sequence[int]]:
        """Load readout bits linked to fidicual round for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        round : Union[int, str]
            Round index or round id.

        Returns
        -------
        bit_linker : Optional[Sequence[int]]
            Readout bits linked to fidicual 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:
                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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            return attributes["bits"][1:]
        except (FileNotFoundError, json.JSONDecodeError):
            print(tile_id, round_id)
            print("Bit linker attribute not found.")
            return None

    def save_local_bit_linker(
        self,
        bit_linker: Sequence[int],
        tile: Union[int, str],
        round: Union[int, str],
    ):
        """Save readout bits linked to fidicual round for one tile.

        Parameters
        ----------
        bit_linker : Sequence[int]
            Readout bits linked to fidicual round for one tile.
        tile : Union[int, str]
            Tile index or tile id.
        round : Union[int, 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:
                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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            attributes["bits"] = bit_linker
            self._save_to_json(attributes, zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError):
            print(tile_id, round_id)
            print("Error writing bit linker attribute.")
            return None

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

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        bit : Union[int, str]
            Bit index or bit id.

        Returns
        -------
        round_linker : Optional[Sequence[int]]
            Fidicual 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:
            zattrs_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(bit_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            return int(attributes["round_linker"])
        except FileNotFoundError:
            print(tile_id, bit_id)
            print("Round linker attribute not found.")
            return None

    def save_local_round_linker(
        self,
        round_linker: int,
        tile: Union[int, str],
        bit: Union[int, str],
    ):
        """Save fidicual round linker attribute to readout bit for one tile.

        Parameters
        ----------
        round_linker : int
            Fidicual round linked to readout bit for one tile.
        tile : Union[int, str]
            Tile index or tile id.
        bit : Union[int, 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:
            zattrs_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(bit_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            attributes["round"] = int(round_linker)
            self._save_to_json(attributes, zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError):
            print(tile_id, bit_id)
            print("Error writing round linker attribute.")
            return None

    def load_local_stage_position_zyx_um(
        self,
        tile: Union[int, str],
        round: Union[int, str],
    ) -> Optional[ArrayLike]:
        """Load tile stage position for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        round : Union[int, str]
            Round index or round id.

        Returns
        -------
        stage_zyx_um : Optional[ArrayLike]
            Tile stage position 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:
                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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            return np.asarray(attributes["stage_zyx_um"], dtype=np.float32)
        except FileNotFoundError:
            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,
        tile: Union[int, str],
        round: Union[int, str],
    ):
        """Save tile stage position for one tile.

        Parameters
        ----------
        stage_zyx_um : ArrayLike
            Tile stage position for one tile.
        tile : Union[int, str]
            Tile index or tile id.
        round : Union[int, str]
            Round index or round id.

        Returns
        -------
        stage_zyx_um : Optional[ArrayLike]
            Tile stage position 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:
                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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            attributes["stage_zyx_um"] = stage_zyx_um.tolist()
            self._save_to_json(attributes, zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError):
            print(tile_id, round_id)
            print("Error writing stage position attribute.")
            return None

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

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        round : Optional[Union[int, str]]   
            Round index or round id.
        bit : Optional[Union[int, str]]
            Bit index or bit id.

        Returns
        -------
        wavelengths_um : Optional[tuple[float, float]]
            Wavelengths for fidicual 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
            zattrs_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )
        else:
            if isinstance(round, int):
                if round < 0:
                    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
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )

        try:
            attributes = self._load_from_json(zattrs_path)
            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: Union[int, str],
        round: Optional[Union[int, str]] = None,
        bit: Optional[Union[int, str]] = None,
    ) -> Optional[tuple[float, float]]:
        """Save wavelengths for fidicual OR readout bit for one tile.

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

        Returns
        -------
        wavelengths_um : Optional[tuple[float, float]]
            Wavelengths for fidicual 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
            zattrs_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )
        else:
            if isinstance(round, int):
                if round < 0:
                    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
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )

        try:
            attributes = self._load_from_json(zattrs_path)
            attributes["excitation_um"] = float(wavelengths_um[0])
            attributes["emission_um"] = float(wavelengths_um[1])
            self._save_to_json(attributes, zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError):
            print("Error writing wavelength attributes.")
            return None

    def load_local_corrected_image(
        self,
        tile: Union[int, str],
        round: Optional[Union[int, str]] = None,
        bit: Optional[Union[int, str]] = None,
        return_future: Optional[bool] = True,
    ) -> Optional[ArrayLike]:
        """Load gain and offset corrected image for fiducial OR readout bit for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        round : Optional[Union[int, str]]
            Round index or round id.
        bit : Optional[Union[int, str]]
            Bit index or bit id.
        return_future : Optional[bool]
            Return future array.

        Returns
        -------
        corrected_image : Optional[ArrayLike]
            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 + ".zarr")
                / Path("corrected_data")
            )
        else:
            if isinstance(round, int):
                if round < 0:
                    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._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path("corrected_data")
            )

        if not Path(current_local_zarr_path).exists():
            print("Corrected image not found.")
            return None

        try:
            spec = self._zarrv2_spec.copy()
            spec["metadata"]["dtype"] = "<u2"
            corrected_image = self._load_from_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                spec,
                return_future,
            )
            return corrected_image
        except (IOError, OSError, ZarrError):
            print("Error loading corrected image.")
            return None

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

        Parameters
        ----------
        image : ArrayLike
            Local corrected image.
        tile : Union[int, 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 : Optional[Union[int, str]]
            Round index or round id.
        bit : Optional[Union[int, str]]
            Bit index or bit id.
        return_future : Optional[bool]
            Return future array.
   """

        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 + ".zarr")
                / Path("corrected_data")
            )
            current_local_zattrs_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )
        else:
            if isinstance(round, int):
                if round < 0:
                    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._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path("corrected_data")
            )
            current_local_zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )

        try:
            self._save_to_zarr_array(
                image,
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec,
                return_future,
            )
            attributes = self._load_from_json(current_local_zattrs_path)
            attributes["gain_correction"] = (gain_correction,)
            attributes["hotpixel_correction"] = (hotpixel_correction,)
            attributes["shading_correction"] = (shading_correction,)
            attributes["psf_idx"] = psf_idx
            self._save_to_json(attributes, current_local_zattrs_path)
        except (IOError, OSError, TimeoutError) as e:
            print(e)
            print("Error saving corrected image.")
            return None

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

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        round : Union[int, str]
            Round index or round id.

        Returns
        -------
        rigid_xform_xyz_px : Optional[ArrayLike]
            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:
                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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            rigid_xform_xyz_px = np.asarray(
                attributes["rigid_xform_xyz_px"], dtype=np.float32
            )
            return rigid_xform_xyz_px
        except (FileNotFoundError, json.JSONDecodeError):
            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: Union[int, str],
        round: Union[int, str],
    ) -> Optional[ArrayLike]:
        """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 : Union[int, str]
            Tile index or tile id.
        round : Union[int, str]
            Round index or round id.

        Returns
        -------
        rigid_xform_xyz_px : Optional[ArrayLike]
            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:
                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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            attributes["rigid_xform_xyz_px"] = rigid_xform_xyz_px.tolist()
            self._save_to_json(attributes, zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError):
            print("Error writing rigid transform attribute.")
            return None

    def load_coord_of_xform_px(
        self,
        tile: Optional[Union[int, str]],
        round: Optional[Union[int, str]],
        return_future: Optional[bool] = True,
    ) -> Optional[tuple[ArrayLike, ArrayLike]]:
        """Local fidicual optical flow matrix for one round and tile.

        Parameters
        ----------
        tile : Optional[Union[int, str]]
            Tile index or tile id.
        round : Optional[Union[int, str]]
            Round index or round id.
        return_future : Optional[bool]
            Return future array.

        Returns
        -------
        of_xform_px : Optional[ArrayLike]
            Local fidicual optical flow matrix for one round and tile.
        downsampling : Optional[ArrayLike]
            Downsampling factor.
        """

        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:
                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

        current_local_zarr_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path("of_xform_px")
        )
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )

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

        try:
            compressor = {
                "id": "blosc",
                "cname": "zstd",
                "clevel": 5,
                "shuffle": 2,
            }
            spec_of = {
                "driver": "zarr",
                "kvstore": None,
                "metadata": {"compressor": compressor},
                "open": True,
                "assume_metadata": False,
                "create": True,
                "delete_existing": False,
            }
            spec_of["metadata"]["dtype"] = "<f4"
            of_xform_px = self._load_from_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                spec_of.copy(),
                return_future,
            )
            attributes = self._load_from_json(zattrs_path)
            downsampling = np.asarray(
                attributes["opticalflow_downsampling"], dtype=np.float32
            )

            return of_xform_px, downsampling
        except (IOError, OSError, ZarrError) as e:
            print(e)
            print("Error loading optical flow transform.")
            return None

    def save_coord_of_xform_px(
        self,
        of_xform_px: ArrayLike,
        tile: Union[int, str],
        downsampling: Sequence[float],
        round: Union[int, str],
        return_future: Optional[bool] = False,
    ):
        """Save fidicual optical flow matrix for one round and tile.

        Parameters
        ----------
        of_xform_px : ArrayLike
            Local fidicual optical flow matrix for one round and tile.
        tile : Union[int, str]
            Tile index or tile id.
        downsampling : Sequence[float]
            Downsampling factor.
        round : Union[int, str] 
            Round index or round id.
        return_future : Optional[bool]
            Return future array.
        """

        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:
                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._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path("of_xform_px")
        )
        current_local_zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )

        try:
            compressor = {
                "id": "blosc",
                "cname": "zstd",
                "clevel": 5,
                "shuffle": 2,
            }
            spec_of = {
                "driver": "zarr",
                "kvstore": None,
                "metadata": {"compressor": compressor},
                "open": True,
                "assume_metadata": False,
                "create": True,
                "delete_existing": False,
            }
            self._save_to_zarr_array(
                of_xform_px,
                self._get_kvstore_key(current_local_zarr_path),
                spec_of.copy(),
                return_future,
            )
            attributes = self._load_from_json(current_local_zattrs_path)
            attributes["opticalflow_downsampling"] = downsampling
            self._save_to_json(attributes, current_local_zattrs_path)
        except (IOError, OSError, TimeoutError):
            print("Error saving optical flow transform.")
            return None

    def load_local_registered_image(
        self,
        tile: Union[int, str],
        round: Optional[Union[int, str]] = None,
        bit: Optional[Union[int, str]] = None,
        return_future: Optional[bool] = True,
    ) -> Optional[ArrayLike]:
        """Local registered, deconvolved image for fidiculial OR readout bit for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        round : Optional[Union[int, str]]
            Round index or round id.
        bit : Optional[Union[int, str]]
            Bit index or bit id.
        return_future : Optional[bool]
            Return future array.

        Returns
        -------
        registered_decon_image : Optional[ArrayLike]
            Registered, deconvolved image for fidiculial 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 + ".zarr")
                / Path("registered_decon_data")
            )
        else:
            if isinstance(round, int):
                if round < 0:
                    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._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path("registered_decon_data")
            )

        if not Path(current_local_zarr_path).exists():
            print("Registered deconvolved image not found.")
            return None

        try:
            spec = self._zarrv2_spec.copy()
            spec["metadata"]["dtype"] = "<u2"
            registered_decon_image = self._load_from_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                spec,
                return_future,
            )
            return registered_decon_image
        except (IOError, OSError, ZarrError) as e:
            print(e)
            print("Error loading registered deconvolved image.")
            return None

    def save_local_registered_image(
        self,
        registered_image: ArrayLike,
        tile: Union[int, str],
        deconvolution: bool = True,
        round: Optional[Union[int, str]] = None,
        bit: Optional[Union[int, str]] = None,
        return_future: Optional[bool] = False,
    ):
        """Save registered, deconvolved image.

        Parameters
        ----------
        registered_image : ArrayLike
            Registered, deconvolved image.
        tile : Union[int, str]
            Tile index or tile id.
        deconvolution : bool
            Deconvolution applied (True) or not (False).
        round : Optional[Union[int, str]]
            Round index or round id.
        bit : Optional[Union[int, str]]
            Bit index or bit id.
        return_future : Optional[bool]
            Return future array.
        """

        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 + ".zarr")
                / Path("registered_decon_data")
            )
            current_local_zattrs_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )
        else:
            if isinstance(round, int):
                if round < 0:
                    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._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path("registered_decon_data")
            )
            current_local_zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(local_id + ".zarr")
                / Path(".zattrs")
            )

        try:
            spec = self._zarrv2_spec.copy()
            spec["metadata"]["dtype"] = "<u2"
            self._save_to_zarr_array(
                registered_image,
                self._get_kvstore_key(current_local_zarr_path),
                spec,
                return_future,
            )
            attributes = self._load_from_json(current_local_zattrs_path)
            attributes["deconvolution"] = deconvolution
            self._save_to_json(attributes, current_local_zattrs_path)
        except (IOError, OSError, TimeoutError):
            print("Error saving corrected image.")
            return None

    def load_local_ufish_image(
        self,
        tile: Union[int, str],
        bit: Union[int, str],
        return_future: Optional[bool] = True,
    ) -> Optional[ArrayLike]:
        """Load readout bit U-FISH prediction image for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        bit : Union[int, str]
            Bit index or bit id.
        return_future : Optional[bool]

        Returns
        -------
        registered_ufish_image : Optional[ArrayLike]
            U-FISH 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 + ".zarr")
            / Path("registered_ufish_data")
        )

        if not Path(current_local_zarr_path).exists():
            print("U-FISH prediction image not found.")
            return None

        try:
            spec = self._zarrv2_spec.copy()
            spec["metadata"]["dtype"] = "<f4"
            registered_ufish_image = self._load_from_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                spec,
                return_future,
            )
            return registered_ufish_image
        except (IOError, OSError, ZarrError) as e:
            print(e)
            print("Error loading U-FISH image.")
            return None

    def save_local_ufish_image(
        self,
        ufish_image: ArrayLike,
        tile: Union[int, str],
        bit: Union[int, str],
        return_future: Optional[bool] = False,
    ):
        """Save U-FISH prediction image.

        Parameters
        ----------
        ufish_image : ArrayLike
            U-FISH prediction image.
        tile : Union[int, str]
            Tile index or tile id.
        bit : Union[int, str]
            Bit index or bit id.
        return_future : Optional[bool]
            Return future array.
        """

        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 + ".zarr")
                / Path("registered_ufish_data")
            )

        try:
            self._save_to_zarr_array(
                ufish_image,
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
                return_future,
            )
        except (IOError, OSError, ZarrError) as e:
            print(e)
            print("Error saving U-Fish image.")
            return None

    def load_local_ufish_spots(
        self,
        tile: Union[int, str],
        bit: Union[int, str],
    ) -> Optional[pd.DataFrame]:
        """Load U-FISH spot localizations and features for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.
        bit : Union[int, str]
            Bit index or bit id.

        Returns
        -------
        ufish_localizations : Optional[pd.DataFrame]
            U-FISH 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_ufish_localizations_path = (
            self._ufish_localizations_root_path
            / Path(tile_id)
            / Path(bit_id + ".parquet")
        )

        if not current_ufish_localizations_path.exists():
            print("U-FISH localizations not found.")
            return None
        else:
            ufish_localizations = self._load_from_parquet(
                current_ufish_localizations_path
            )
            return ufish_localizations

    def save_local_ufish_spots(
        self,
        spot_df: pd.DataFrame,
        tile: Union[int, str],
        bit: Union[int, str],
    ):
        """Save U-FISH localizations and features.

        Parameters
        ----------
        spot_df : pd.DataFrame
            U-FISH localizations and features.
        tile : Union[int, str]
            Tile index or tile id.
        bit : Union[int, 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

        if not (self._ufish_localizations_root_path / Path(tile_id)).exists():
            (self._ufish_localizations_root_path / Path(tile_id)).mkdir()

        current_ufish_localizations_path = (
            self._ufish_localizations_root_path
            / Path(tile_id)
            / Path(bit_id + ".parquet")
        )

        try:
            self._save_to_parquet(spot_df, current_ufish_localizations_path)
        except (IOError, OSError) as e:
            print(e)
            print("Error saving U-FISH localizations.")
            return None

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

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.

        Returns
        -------
        affine_zyx_um : Optional[ArrayLike]
            Global affine registration transform for one tile.
        origin_zyx_um : Optional[ArrayLike]
            Global origin registration transform for one tile.
        spacing_zyx_um : Optional[ArrayLike]
            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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(self._round_ids[0] + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_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 = np.asarray(attributes["spacing_zyx_um"], dtype=np.float32)
            return (affine_zyx_um, origin_zyx_um, spacing_zyx_um)
        except (FileNotFoundError, json.JSONDecodeError):
            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: Union[int, str],
    ) -> None:
        """Save global registration transform for one tile.

        Parameters
        ----------
        affine_zyx_um : ArrayLike
            Global affine registration transform for one tile.
        origin_zyx_um : ArrayLike
            Global origin registration transform for one tile.
        spacing_zyx_um : ArrayLike
            Global spacing registration transform for one tile.
        tile : Union[int, 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:
            zattrs_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(self._round_ids[0] + ".zarr")
                / Path(".zattrs")
            )
            attributes = self._load_from_json(zattrs_path)
            attributes["affine_zyx_um"] = affine_zyx_um.tolist()
            attributes["origin_zyx_um"] = origin_zyx_um.tolist()
            attributes["spacing_zyx_um"] = spacing_zyx_um.tolist()
            self._save_to_json(attributes, zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(e)
            print("Could not save global coordinate transforms.")

    def load_global_fidicual_image(
        self,
        return_future: Optional[bool] = True,
    ) -> Optional[tuple[ArrayLike, ArrayLike, ArrayLike, ArrayLike]]:
        """Load downsampled, fused fidicual image.

        Parameters
        ----------
        return_future : Optional[bool]
            Return future array.

        Returns
        -------
        fused_image : Optional[ArrayLike]
            Downsampled, fused fidicual image.
        affine_zyx_um : Optional[ArrayLike]
            Global affine registration transform for fused image.
        origin_zyx_um : Optional[ArrayLike]
            Global origin registration transform for fused image.
        spacing_zyx_um : Optional[ArrayLike]
            Global spacing registration transform for fused image.
        """

        current_local_zarr_path = str(
            self._fused_root_path / Path("fused.zarr") / Path("fused_polyDT_iso_zyx")
        )

        if not Path(current_local_zarr_path).exists():
            print("Globally registered, fused image not found.")
            return None

        zattrs_path = str(current_local_zarr_path / Path(".zattrs"))

        try:
            fused_image = self._load_from_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
                return_future,
            )
            attributes = self._load_from_json(zattrs_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 = np.asarray(attributes["spacing_zyx_um"], dtype=np.float32)
            return fused_image, affine_zyx_um, origin_zyx_um, spacing_zyx_um
        except (IOError, OSError, ZarrError):
            print("Error loading globally registered, fused image.")
            return None

    def save_global_fidicual_image(
        self,
        fused_image: ArrayLike,
        affine_zyx_um: ArrayLike,
        origin_zyx_um: ArrayLike,
        spacing_zyx_um: ArrayLike,
        fusion_type: str = "polyDT",
        return_future: Optional[bool] = False,
    ):
        """Save downsampled, fused fidicual image.

        Parameters
        ----------
        fused_image : ArrayLike
            Downsampled, fused fidicual 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
            Global spacing registration transform for fused image.
        fusion_type : str
            Type of fusion (polyDT or all_channels).
        return_future : Optional[bool]
            Return future array.
        """

        if fusion_type == "polyDT":
            filename = "fused_polyDT_iso_zyx"
        else:
            filename = "fused_all_channels_zyx"
        current_local_zarr_path = str(
            self._fused_root_path / Path("fused.zarr") / Path(filename)
        )
        current_local_zattrs_path = str(
            self._fused_root_path
            / Path("fused.zarr")
            / Path(filename)
            / Path(".zattrs")
        )

        attributes = {
            "affine_zyx_um": affine_zyx_um.tolist(),
            "origin_zyx_um": origin_zyx_um.tolist(),
            "spacing_zyx_um": spacing_zyx_um.tolist(),
        }
        try:
            self._save_to_zarr_array(
                fused_image.astype(np.uint16),
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
                return_future,
            )
            self._save_to_json(attributes, current_local_zattrs_path)
        except (IOError, OSError, TimeoutError):
            print("Error saving fused image.")
            return None

    def load_local_decoded_spots(
        self,
        tile: Union[int, str],
    ) -> Optional[pd.DataFrame]:
        """Load decoded spots and features for one tile.

        Parameters
        ----------
        tile : Union[int, str]
            Tile index or tile id.

        Returns
        -------
        tile_features : Optional[pd.DataFrame]
            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_root_path / 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: Union[int, str],
    ) -> None:
        """Save decoded spots and features for one tile.

        Parameters
        ----------
        features_df : pd.DataFrame
            Decoded spots and features for one tile.
        tile : Union[int, 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

        current_tile_features_path = self._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,
    ) -> Optional[pd.DataFrame]:
        """Load all decoded and filtered spots.

        Returns
        -------
        all_tiles_filtered : Optional[pd.DataFrame]
            All decoded and filtered spots.
        """

        current_global_filtered_decoded_dir_path = self._datastore_path / Path(
            "all_tiles_filtered_decoded_features"
        )
        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
        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,
    ):
        """Save all decoded and filtered spots.

        Parameters
        ----------
        filtered_decoded_df : pd.DataFrame
            All decoded and filtered spots.
        """

        current_global_filtered_decoded_dir_path = self._datastore_path / Path(
            "all_tiles_filtered_decoded_features"
        )

        if not current_global_filtered_decoded_dir_path.exists():
            current_global_filtered_decoded_dir_path.mkdir()

        current_global_filtered_decoded_path = (
            current_global_filtered_decoded_dir_path / Path("decoded_features.parquet")
        )

        self._save_to_parquet(filtered_decoded_df, current_global_filtered_decoded_path)

    def load_global_cellpose_outlines(
        self,
    ) -> Optional[dict]:
        """Load Cellpose max projection cell outlines.

        Returns
        -------
        cellpose_outlines : Optional[dict]
            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_segmentation_image(
        self,
        return_future: Optional[bool] = True,
    ) -> Optional[ArrayLike]:
        """Load Cellpose max projection, downsampled segmentation image.

        Parameters
        ----------
        return_future : Optional[bool]
            Return future array.

        Returns
        -------
        fused_image : Optional[ArrayLike]
            Cellpose max projection, downsampled segmentation image.
        """

        current_local_zarr_path = str(
            self._segmentation_root_path
            / Path("cellpose")
            / Path("cellpose.zarr")
            / Path("masks_polyDT_iso_zyx")
        )

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

        try:
            fused_image = self._load_from_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
                return_future,
            )
            return fused_image
        except (IOError, OSError, ZarrError):
            print("Error loading Cellpose image.")
            return None

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

        Parameters
        ----------
        cellpose_image : ArrayLike
            Cellpose max projection, downsampled segmentation image.
        downsampling : Sequence[float]
            Downsample factors.
        return_future : Optional[bool]
            Return future array.
        """

        current_local_zarr_path = str(
            self._segmentation_root_path
            / Path("cellpose")
            / Path("cellpose.zarr")
            / Path("masks_polyDT_iso_zyx")
        )
        current_local_zattrs_path = str(
            self._segmentation_root_path
            / Path("cellpose")
            / Path("cellpose.zarr")
            / Path("masks_polyDT_iso_zyx")
            / Path(".zattrs")
        )

        attributes = {"downsampling": downsampling}

        try:
            self._save_to_zarr_array(
                cellpose_image,
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
                return_future,
            )
            self._save_to_json(attributes, current_local_zattrs_path)
        except (IOError, OSError, TimeoutError):
            print("Error saving Cellpose image.")
            return None

    def save_spots_prepped_for_baysor(self, prepped_for_baysor_df: pd.DataFrame):
        """Save spots prepped for Baysor.

        Parameters
        ----------
        prepped_for_baysor_df : pd.DataFrame
            Spots prepped for Baysor.
        """

        current_global_filtered_decoded_dir_path = self._datastore_path / Path(
            "all_tiles_filtered_decoded_features"
        )

        if not current_global_filtered_decoded_dir_path.exists():
            current_global_filtered_decoded_dir_path.mkdir()

        current_global_filtered_decoded_path = (
            current_global_filtered_decoded_dir_path / Path("transcripts.parquet")
        )

        self._save_to_parquet(prepped_for_baysor_df, current_global_filtered_decoded_path)

    def run_baysor(self):
        """Run Baysor"

        Assumes that spots are prepped for Baysor and the Baysor path and options are set.
        Reformats ROIs into ImageJ style ROIs for later use.
        """

        import subprocess

        baysor_input_path = self._datastore_path / Path("all_tiles_filtered_decoded_features") / Path("transcripts.parquet")
        baysor_output_path = self._segmentation_root_path / Path("baysor")
        baysor_output_path.mkdir(exist_ok=True)

        julia_threading = r"JULIA_NUM_THREADS="+str(self._julia_threads)+ " "
        preview_baysor_options = r"preview -c " +str(self._baysor_options)
        command = julia_threading + str(self._baysor_path) + " " + preview_baysor_options + " " +\
            str(baysor_input_path) + " -o " + str(baysor_output_path)

        try:
            result = subprocess.run(command, shell=True, check=True)
            print("Baysor finished with return code:", result.returncode)
        except subprocess.CalledProcessError as e:
            print("Baysor failed with:", e)

        # first try to run Baysor assuming that prior segmentations are present               
        try:
            run_baysor_options = r"run -p -c " +str(self._baysor_options)
            command = julia_threading + str(self._baysor_path) + " " + run_baysor_options + " " +\
                str(baysor_input_path) + " -o " + str(baysor_output_path) + \
                " --polygon-format GeometryCollectionLegacy --count-matrix-format tsv :cell_id"
            result = subprocess.run(command, shell=True, check=True)
            print("Baysor finished with return code:", result.returncode)
        except subprocess.CalledProcessError:
            # then fall back and run without prior segmentations.
            # IMPORTANT: the .toml file has to be defined correctly for this to work!
            try:
                run_baysor_options = r"run -p -c " +str(self._baysor_options)
                command = julia_threading + str(self._baysor_path) + " " + run_baysor_options + " " +\
                    str(baysor_input_path) + " -o " + str(baysor_output_path) + " --count-matrix-format tsv"
                result = subprocess.run(command, shell=True, check=True)
                print("Baysor finished with return code:", result.returncode)
            except subprocess.CalledProcessError as e:
                print("Baysor failed with:", e)

    def reformat_baysor_3D_oultines(self):
        """Reformat baysor 3D json file into ImageJ ROIs."""
        import re

        # Load the JSON file
        baysor_output_path = self._segmentation_root_path / Path("baysor")
        baysor_segmentation = baysor_output_path / Path(r"segmentation_polygons_3d.json")
        with open(baysor_segmentation, 'r') as file:
            data = json.load(file)


        # Dictionary to group polygons by cell ID
        cell_polygons = defaultdict(list)

        def parse_z_range(z_range):
            cleaned_range = re.sub(r"[^\d.,-]", "", z_range)  # Remove non-numeric, non-period, non-comma, non-dash characters
            return map(float, cleaned_range.split(","))

        # Iterate through each z-plane and corresponding polygons
        for z_range, details in data.items():
            z_start, z_end = parse_z_range(z_range)

            for geometry in details["geometries"]:
                coordinates = geometry["coordinates"][0]  # Assuming the outer ring of the polygon
                cell_id = geometry["cell"]  # Get the cell ID

                # Store the polygon with its z-range
                cell_polygons[cell_id].append({
                    "z_start": z_start,
                    "z_end": z_end,
                    "coordinates": coordinates
                })

        rois = []

        # Process each cell ID to create 3D ROIs
        for cell_id, polygons in cell_polygons.items():
            for idx, polygon in enumerate(polygons):
                x_coords = [point[0] for point in polygon["coordinates"]]
                y_coords = [point[1] for point in polygon["coordinates"]]


                z_start = polygon["z_start"]
                z_end = polygon["z_end"]

                try:
                    # Create an ImageJRoi object for the polygon using frompoints
                    coords = list(zip(x_coords, y_coords))  # List of (x, y) tuples
                    roi = ImagejRoi.frompoints(coords)
                    roi.roitype = ROI_TYPE.POLYGON  # Set the ROI type to Polygon
                    roi.coordinates = coords  # Explicitly assign coordinates to the ROI
                    roi.name = f"cell_{str(cell_id)}_zstart_{str(z_start)}_zend_{str(z_end)}"  # Ensure unique name
                    rois.append(roi)
                except Exception as e:
                    print(f"Error while creating ROI for cell ID {cell_id}: {e}")

        # Write all ROIs to a ZIP file   
        output_file = baysor_output_path / Path(r"3d_cell_rois.zip")
        roiwrite(output_file, rois,mode='w')

    def load_global_baysor_filtered_spots(
        self,
    ) -> Optional[pd.DataFrame]:
        """Load Baysor re-assigned decoded RNA.

        Assumes Baysor has been run.

        Returns
        -------
        baysor_filtered_genes : Optional[pd.DataFrame]
            Baysor re-assigned decoded RNA.
        """

        current_baysor_spots_path = (
            self._segmentation_root_path
            / Path("baysor")
            / Path("segmentation.csv")
        )

        if not current_baysor_spots_path.exists():
            print("Baysor filtered genes not found.")
            return None
        else:
            baysor_filtered_genes = self._load_from_csv(current_baysor_spots_path)
            return baysor_filtered_genes

    def load_global_baysor_outlines(
        self,
    ) -> Optional[dict]:
        """Load Baysor cell outlines.

        Assumes Baysor has been run.

        Returns
        -------
        baysor_outlines : Optional[dict]
            Baysor cell outlines.
        """

        current_baysor_outlines_path = (
            self._segmentation_root_path 
            / Path("baysor") 
            / Path(r"3d_cell_rois.zip")
        )

        if not current_baysor_outlines_path.exists():
            print("Baysor outlines not found.")
            return None
        else:
            baysor_rois = roiread(current_baysor_outlines_path)
            return baysor_rois

    @staticmethod
    def _roi_to_shapely(roi):
        return Polygon(roi.subpixel_coordinates[:, ::-1])

    def reprocess_and_save_filtered_spots_with_baysor_outlines(self):
        """Reprocess filtered spots using baysor cell outlines, then save.

        Loads the 3D cell outlines from Baysor, checks all points to see what 
        (if any) cell outline that the spot falls within, and then saves the
        data back to the datastore.
        """
        from rtree import index
        import re

        rois = self.load_global_baysor_outlines()
        filtered_spots_df = self.load_global_filtered_decoded_spots()

        parsed_spots_df = filtered_spots_df[
                [
                    "gene_id",
                    "global_z",
                    "global_y",
                    "global_x",
                    "cell_id",
                    "tile_idx",
                ]
        ].copy()
        parsed_spots_df.rename(
            columns={
                "global_x": "x",
                "global_y": "y",
                "global_z": "z",
                "gene_id" : "gene",
                "cell_id" : "cell",
            },
            inplace=True,
        )
        parsed_spots_df["transcript_id"] = pd.util.hash_pandas_object(
            parsed_spots_df, index=False
        )

        parsed_spots_df["assignment_confidence"] = 1.0

        # Create spatial index for ROIs
        roi_index = index.Index()
        roi_map = {}  # Map index IDs to ROIs

        for idx, roi in enumerate(rois):
            # Ensure roi.coordinates contains the polygon points
            coords = roi.coordinates()

            # Insert the polygon bounds into the spatial index
            polygon = Polygon(coords)
            roi_index.insert(idx, polygon.bounds)  # Use polygon bounds for indexing
            roi_map[idx] = roi

        # Function to check a single point
        def point_in_roi(row):
            point = Point(row["x"], row["y"])
            candidate_indices = list(roi_index.intersection(point.bounds))  # Search spatial index
            for idx in candidate_indices:
                roi = roi_map[idx]
                match = re.search(r"zstart_([-\d.]+)_zend_([-\d.]+)", roi.name)
                if match:
                    z_start = float(match.group(1))
                    z_end = float(match.group(2))
                    if z_start <= row["z"] <= z_end:
                        polygon = Polygon(roi.coordinates())
                        if polygon.contains(point):
                            return str(roi.name.split("_")[1]) 
            return -1

        # Apply optimized spatial lookup
        parsed_spots_df["cell"] = parsed_spots_df.apply(point_in_roi, axis=1)
        parsed_spots_df = parsed_spots_df.loc[parsed_spots_df["cell"] != -1]

        current_global_filtered_decoded_path = (
            self._datastore_path 
            / Path("all_tiles_filtered_decoded_features")
            / Path("refined_transcripts.parquet")
        )

        self._save_to_parquet(parsed_spots_df, current_global_filtered_decoded_path)

    def save_mtx(self, spots_source: str = ""):
        """Save mtx file for downstream analysis. Assumes Baysor has been run.

        Parameters
        ----------
        spots_source: str, default "baysor"
            source of spots. "baysor" or "resegmented".
        """

        from merfish3danalysis.utils.dataio import create_mtx

        if spots_source == "baysor":
            spots_path = self._datastore_path / Path("segmentation") / Path("baysor") / Path("segmentation.csv")
        elif spots_source == "resegmented":
            spots_path = (
                self._datastore_path 
                / Path("all_tiles_filtered_decoded_features")
                / Path("refined_transcripts.parquet")
            )

        mtx_output_path = self._datastore_path / Path("mtx_output")

        create_mtx(
            spots_path=spots_path,
            output_dir_path=mtx_output_path,
        )

baysor_options property writable

Baysor options

Returns:

Name Type Description
baysor_options Union[Path, str]

Baysor options.

baysor_path property writable

Baysor path

Returns:

Name Type Description
baysor_path Union[Path, str]

Baysor path.

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 Optional[str]

Camera model.

channel_psfs property writable

Channel point spread functions (PSF).

Return

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_state property writable

Datastore state.

Returns:

Name Type Description
datastore_state Optional[dict]

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.

julia_threads property writable

Julia thread number

Returns:

Name Type Description
julia_threads int

Julia thread number.

microscope_type property writable

Microscope type.

Returns:

Name Type Description
microscope_type Optional[str]

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

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).

_check_for_zarr_array(kvstore, spec) staticmethod

Check if zarr array exists using Tensortore.

Parameters:

Name Type Description Default
kvstore Union[Path, str]

Datastore location.

required
spec dict

Zarr specification.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _check_for_zarr_array(kvstore: Union[Path, str], spec: dict):
    """Check if zarr array exists using Tensortore.

    Parameters
    ----------
    kvstore : Union[Path, str]
        Datastore location.
    spec : dict
        Zarr specification.
    """

    current_zarr = ts.open(
        {
            **spec,
            "kvstore": kvstore,
        }
    ).result()

    del current_zarr

_get_kvstore_key(path) staticmethod

Convert datastore location to tensorstore kvstore key.

Parameters:

Name Type Description Default
path Union[Path, str]

Datastore location.

required

Returns:

Name Type Description
kvstore_key dict

Tensorstore kvstore key.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _get_kvstore_key(path: Union[Path, str]) -> dict:
    """Convert datastore location to tensorstore kvstore key.

    Parameters
    ----------
    path : Union[Path, str]
        Datastore location.

    Returns
    -------
    kvstore_key : dict
        Tensorstore kvstore key.
    """

    path_str = str(path)
    if path_str.startswith("s3://") or "s3.amazonaws.com" in path_str:
        return {"driver": "s3", "path": path_str}
    elif path_str.startswith("gs://") or "storage.googleapis.com" in path_str:
        return {"driver": "gcs", "path": path_str}
    elif path_str.startswith("azure://") or "blob.core.windows.net" in path_str:
        return {"driver": "azure", "path": path_str}
    elif path_str.startswith("http://") or path_str.startswith("https://"):
        raise ValueError("Unsupported cloud storage provider in URL")
    else:
        return {"driver": "file", "path": path_str}

_init_datastore()

Initialize datastore.

Create directory structure and initialize datastore state.

Source code in src/merfish3danalysis/qi2labDataStore.py
def _init_datastore(self):
    """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.zarr")
    self._calibrations_zarr_path.mkdir()
    calibrations_zattrs_path = self._calibrations_zarr_path / Path(r".zattrs")
    empty_zattrs = {}
    self._save_to_json(empty_zattrs, calibrations_zattrs_path)
    self._polyDT_root_path = self._datastore_path / Path(r"polyDT")
    self._polyDT_root_path.mkdir()
    self._readouts_root_path = self._datastore_path / Path(r"readouts")
    self._readouts_root_path.mkdir()
    self._ufish_localizations_root_path = self._datastore_path / Path(
        r"ufish_localizations"
    )
    self._ufish_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()
    self._mtx_output_root_path = self._datastore_path / Path(r"mtx_output")
    self._mtx_output_root_path.mkdir()
    self._baysor_path = r""
    self._baysor_options = r""
    self._julia_threads = 0

    # initialize datastore state
    self._datastore_state_json_path = self._datastore_path / Path(
        r"datastore_state.json"
    )
    self._datastore_state = {
        "Version": 0.3,
        "Initialized": True,
        "Calibrations": False,
        "Corrected": False,
        "LocalRegistered": False,
        "GlobalRegistered": False,
        "Fused": False,
        "SegmentedCells": False,
        "DecodedSpots": False,
        "FilteredSpots": False,
        "RefinedSpots": False,
        "mtxOutput": False,
        "BaysorPath": str(self._baysor_path),
        "BaysorOptions": str(self._baysor_options),
        "JuliaThreads": str(self._julia_threads)
    }

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

_load_from_json(dictionary_path) staticmethod

Load json as dictionary.

Parameters:

Name Type Description Default
dictionary_path Union[Path, 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: Union[Path, str]) -> dict:
    """Load json as dictionary.

    Parameters
    ----------
    dictionary_path : Union[Path, str]
        Path to json file.

    Returns
    -------
    dictionary : dict
        Dictionary from json file.
    """

    try:
        with open(dictionary_path, "r") as f:
            dictionary = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        dictionary = {}
    return dictionary

_load_from_microjson(dictionary_path) staticmethod

Load cell outlines outlines microjson as dictionary.

Parameters:

Name Type Description Default
dictionary_path Union[Path, 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: Union[Path, str]) -> dict:
    """Load cell outlines outlines microjson as dictionary.

    Parameters
    ----------
    dictionary_path : Union[Path, str]
        Path to microjson file.

    Returns
    -------
    outlines : dict
        Cell outlines dictionary.
    """

    try:
        with open(dictionary_path, "r") 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 Union[Path, 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: Union[Path, str]) -> pd.DataFrame:
    """Load dataframe from parquet.

    Parameters
    ----------
    parquet_path : Union[Path, str]
        Path to parquet file.

    Returns
    -------
    df : pd.DataFrame
        Dataframe from parquet file.
    """

    return pd.read_parquet(parquet_path)

_load_from_zarr_array(kvstore, spec, return_future=True) staticmethod

Return tensorstore array from zarr

Defaults to returning future result.

Parameters:

Name Type Description Default
kvstore dict

Tensorstore kvstore specification.

required
spec dict

Tensorstore zarr specification.

required
return_future bool

Return future (True) or immediately read (False).

True

Returns:

Name Type Description
array ArrayLike

Delayed (future) or immediate array.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _load_from_zarr_array(
    kvstore: dict, spec: dict, return_future=True
) -> ArrayLike:
    """Return tensorstore array from zarr

    Defaults to returning future result.

    Parameters
    ----------
    kvstore : dict
        Tensorstore kvstore specification.
    spec : dict
        Tensorstore zarr specification.
    return_future : bool
        Return future (True) or immediately read (False).

    Returns
    -------
    array : ArrayLike
        Delayed (future) or immediate array.
    """

    current_zarr = ts.open(
        {
            **spec,
            "kvstore": kvstore,
        }
    ).result()

    read_future = current_zarr.read()

    if return_future:
        return read_future
    else:
        return read_future.result()

_parse_datastore()

Parse datastore to discover available components.

Source code in src/merfish3danalysis/qi2labDataStore.py
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
def _parse_datastore(self):
    """Parse datastore to discover available components."""

    # directory structure as defined by qi2lab spec
    self._calibrations_zarr_path = self._datastore_path / Path(r"calibrations.zarr")
    self._polyDT_root_path = self._datastore_path / Path(r"polyDT")
    self._readouts_root_path = self._datastore_path / Path(r"readouts")
    self._ufish_localizations_root_path = self._datastore_path / Path(
        r"ufish_localizations"
    )
    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")
    self._mtx_output_root_path = self._datastore_path / Path(r"mtx_output")
    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, "r") as json_file:
        self._datastore_state = json.load(json_file)

    # validate calibrations.zarr
    if self._datastore_state["Calibrations"]:
        if not (self._calibrations_zarr_path.exists()):
            print("Calibration data error.")
        try:
            zattrs_path = self._calibrations_zarr_path / Path(".zattrs")
            attributes = self._load_from_json(zattrs_path)
        except (FileNotFoundError, json.JSONDecodeError):
            print("Calibration attributes not found")

        keys_to_check = [
            "num_rounds",
            "num_tiles",
            "channels_in_data",
            "tile_overlap",
            "binning",
            "e_per_ADU",
            "na",
            "ri",
            "exp_order",
            "codebook",
            "num_bits"
        ]
        if self._datastore_state["Version"] == 0.3:
            keys_to_check.append("microscope_type")
            keys_to_check.append("camera_model")
            keys_to_check.append("voxel_size_zyx_um")
        for key in keys_to_check:
            if key not in attributes.keys():
                raise KeyError("Calibration attributes incomplete")
            else:
                setattr(self, "_" + key, attributes[key])

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

        try:
            self._psfs = (
                self._load_from_zarr_array(
                    kvstore=self._get_kvstore_key(current_local_zarr_path),
                    spec=self._zarrv2_spec.copy(),
                )
            ).result()
        except (IOError, OSError, ZarrError):
            print("Calibration psfs missing.")

        del current_local_zarr_path

        # current_local_zarr_path = str(
        #     self._calibrations_zarr_path / Path("noise_map")
        # )

        # try:
        #     self._noise_map = (
        #         self._load_from_zarr_array(
        #             kvstore=self._get_kvstore_key(current_local_zarr_path),
        #             spec=self._zarrv2_spec,
        #         )
        #     ).result()
        # except Exception:
        #     print("Calibration noise map missing.")

    # validate polyDT and readout bits data
    if self._datastore_state["Corrected"]:
        if not (self._polyDT_root_path.exists()):
            raise FileNotFoundError("PolyDT directory not initialized")
        else:
            polyDT_tile_ids = sorted(
                [
                    entry.name
                    for entry in self._polyDT_root_path.iterdir()
                    if entry.is_dir()
                ],
                key=lambda x: int(x.split("tile")[1].split(".zarr")[0]),
            )
            current_tile_dir_path = self._polyDT_root_path / Path(
                polyDT_tile_ids[0]
            )
            self._round_ids = sorted(
                [
                    entry.name.split(".")[0]
                    for entry in current_tile_dir_path.iterdir()
                    if entry.is_dir()
                ],
                key=lambda x: int(x.split("round")[1].split(".zarr")[0]),
            )
        if not (self._readouts_root_path.exists()):
            raise FileNotFoundError("Readout directory not initialized")
        else:
            readout_tile_ids = sorted(
                [
                    entry.name
                    for entry in self._readouts_root_path.iterdir()
                    if entry.is_dir()
                ],
                key=lambda x: int(x.split("tile")[1].split(".zarr")[0]),
            )
            current_tile_dir_path = self._readouts_root_path / Path(
                readout_tile_ids[0]
            )
            self._bit_ids = sorted(
                [
                    entry.name.split(".")[0]
                    for entry in current_tile_dir_path.iterdir()
                    if entry.is_dir()
                ],
                key=lambda x: int(x.split("bit")[1].split(".zarr")[0]),
            )
        assert (
            polyDT_tile_ids == readout_tile_ids
        ), "polyDT and readout tile ids do not match. Conversion error."
        self._tile_ids = polyDT_tile_ids.copy()
        del polyDT_tile_ids, readout_tile_ids

        for tile_id, round_id in product(self._tile_ids, self._round_ids):
            try:
                zattrs_path = str(
                    self._polyDT_root_path
                    / Path(tile_id)
                    / Path(round_id + ".zarr")
                    / Path(".zattrs")
                )
                attributes = self._load_from_json(zattrs_path)
            except (FileNotFoundError, json.JSONDecodeError):
                print("polyDT tile attributes not found")

            keys_to_check = [
                "stage_zyx_um",
                "excitation_um",
                "emission_um",
                "bit_linker",
                # "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 polyDT attributes incomplete")

            current_local_zarr_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path("corrected_data")
            )

            try:
                self._check_for_zarr_array(
                    self._get_kvstore_key(current_local_zarr_path),
                    self._zarrv2_spec.copy(),
                )
            except (IOError, OSError, ZarrError):
                print(tile_id, round_id)
                print("Corrected polyDT data missing.")

        for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
            try:
                zattrs_path = str(
                    self._readouts_root_path
                    / Path(tile_id)
                    / Path(bit_id + ".zarr")
                    / Path(".zattrs")
                )
                attributes = self._load_from_json(zattrs_path)
            except (FileNotFoundError, json.JSONDecodeError):
                print("Readout tile attributes not found")

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

            current_local_zarr_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(bit_id + ".zarr")
                / Path("corrected_data")
            )

            try:
                self._check_for_zarr_array(
                    self._get_kvstore_key(current_local_zarr_path),
                    self._zarrv2_spec.copy(),
                )
            except (IOError, OSError, ZarrError):
                print(tile_id, bit_id)
                print("Corrected readout data missing.")

    # check and validate local registered data
    if self._datastore_state["LocalRegistered"]:
        for tile_id, round_id in product(self._tile_ids, self._round_ids):
            if round_id is not self._round_ids[0]:
                try:
                    zattrs_path = str(
                        self._polyDT_root_path
                        / Path(tile_id)
                        / Path(round_id + ".zarr")
                        / Path(".zattrs")
                    )
                    with open(zattrs_path, "r") as f:
                        attributes = json.load(f)
                except (FileNotFoundError, json.JSONDecodeError):
                    print("polyDT tile attributes not found")

                keys_to_check = ["rigid_xform_xyz_px"]

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

                current_local_zarr_path = str(
                    self._polyDT_root_path
                    / Path(tile_id)
                    / Path(round_id + ".zarr")
                    / Path("of_xform_px")
                )

                try:
                    self._check_for_zarr_array(
                        self._get_kvstore_key(current_local_zarr_path),
                        self._zarrv2_spec.copy(),
                    )
                except (IOError, OSError, ZarrError):
                    print(tile_id, round_id)
                    print("Optical flow registration data missing.")

            current_local_zarr_path = str(
                self._polyDT_root_path
                / Path(tile_id)
                / Path(round_id + ".zarr")
                / Path("registered_decon_data")
            )
            if round_id is self._round_ids[0]:
                try:
                    self._check_for_zarr_array(
                        self._get_kvstore_key(current_local_zarr_path),
                        self._zarrv2_spec.copy(),
                    )
                except (IOError, OSError, ZarrError):
                    print(tile_id, round_id)
                    print("Registered polyDT data missing.")

        for tile_id, bit_id in product(self._tile_ids, self._bit_ids):
            current_local_zarr_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(bit_id + ".zarr")
                / Path("registered_decon_data")
            )

            try:
                self._check_for_zarr_array(
                    self._get_kvstore_key(current_local_zarr_path),
                    self._zarrv2_spec.copy(),
                )
            except (IOError, OSError, ZarrError):
                print(tile_id, round_id)
                print("Registered readout data missing.")

            current_local_zarr_path = str(
                self._readouts_root_path
                / Path(tile_id)
                / Path(bit_id + ".zarr")
                / Path("registered_ufish_data")
            )

            try:
                self._check_for_zarr_array(
                    self._get_kvstore_key(current_local_zarr_path),
                    self._zarrv2_spec.copy(),
                )
            except (IOError, OSError, ZarrError):
                print(tile_id, round_id)
                print("Registered ufish prediction missing.")

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

    # check and validate global registered data
    if self._datastore_state["GlobalRegistered"]:
        for tile_id in self._tile_ids:
            try:
                zattrs_path = str(
                    self._polyDT_root_path
                    / Path(tile_id)
                    / Path(self._round_ids[0] + ".zarr")
                    / Path(".zattrs")
                )
                with open(zattrs_path, "r") as f:
                    attributes = json.load(f)
            except (FileNotFoundError, json.JSONDecodeError):
                print("polyDT tile attributes not found")

            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"]:
        try:
            zattrs_path = str(
                self._fused_root_path
                / Path("fused.zarr")
                / Path("fused_polyDT_iso_zyx")
                / Path(".zattrs")
            )
            with open(zattrs_path, "r") as f:
                attributes = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            print("Fused image attributes not found")

        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(
            self._fused_root_path
            / Path("fused.zarr")
            / Path("fused_polyDT_iso_zyx")
        )

        try:
            self._check_for_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
            )
        except (IOError, OSError, ZarrError):
            print("Fused data missing.")

    # check and validate cellpose segmentation
    if self._datastore_state["SegmentedCells"]:
        current_local_zarr_path = str(
            self._segmentation_root_path
            / Path("cellpose")
            / Path("cellpose.zarr")
            / Path("masks_polyDT_iso_zyx")
        )

        try:
            self._check_for_zarr_array(
                self._get_kvstore_key(current_local_zarr_path),
                self._zarrv2_spec.copy(),
            )
        except (IOError, OSError, ZarrError):
            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"]:
        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"]:
        filtered_path = self._decoded_root_path / Path(
            "all_tiles_filtered_decoded_features.parquet"
        )

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

    if self._datastore_state["RefinedSpots"]:
        baysor_spots_path = (
            self._segmentation_root_path
            / Path("baysor")
            / Path("segmentation.csv")
        )

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

    # check and validate mtx
    if self._datastore_state["mtxOutput"]:
        mtx_barcodes_path = self._mtx_output_root_path / Path("barcodes.tsv.gz")
        mtx_features_path = self._mtx_output_root_path / Path("features.tsv.gz")
        mtx_matrix_path = self._mtx_output_root_path / Path("matrix.tsv.gz")

        if (
            not (mtx_barcodes_path.exists())
            or not (mtx_features_path.exists())
            or not (mtx_matrix_path.exists())
        ):
            raise FileNotFoundError("mtx output missing.")

    try:
        self._baysor_path = Path(str(self._datastore_state["BaysorPath"]))
        self._baysor_options = Path(str(self._datastore_state["BaysorOptions"]))
        self._julia_threads = int(self._datastore_state["JuliaThreads"])
    except KeyError:
        self._baysor_path = r""
        self._baysor_options = r""
        self._julia_threads = 1

_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 Union[Path, 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: Union[Path, str]):
    """Save dictionary to json.

    Parameters
    ----------
    dictionary : dict
        The data to be saved.
    dictionary_path : Union[Path,str]
        The path to the JSON file where the data will be saved.
    """

    with open(dictionary_path, "w") as file:
        json.dump(dictionary, file, indent=4)

_save_to_parquet(df, parquet_path) staticmethod

Save dataframe to parquet.

Parameters:

Name Type Description Default
df DataFrame

Dataframe to save.

required
parquet_path Union[Path, str]

Path to parquet file.

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

    Parameters
    ----------
    df : pd.DataFrame
        Dataframe to save.
    parquet_path : Union[Path, str]
        Path to parquet file.
    """

    df.to_parquet(parquet_path)

_save_to_zarr_array(array, kvstore, spec, return_future=False) staticmethod

Save array to zarr using tensorstore.

Defaults to returning future result.

Parameters:

Name Type Description Default
array ArrayLike

Array to save.

required
kvstore dict

Tensorstore kvstore specification.

required
spec dict

Tensorstore zarr specification.

required
return_future Optional[bool]

Return future (True) or immediately write (False).

False

Returns:

Name Type Description
write_future Optional[ArrayLike]

Delayed (future) if return_future is True.

Source code in src/merfish3danalysis/qi2labDataStore.py
@staticmethod
def _save_to_zarr_array(
    array: ArrayLike,
    kvstore: dict,
    spec: dict,
    return_future: Optional[bool] = False,
) -> Optional[ArrayLike]:
    """Save array to zarr using tensorstore.

    Defaults to returning future result.

    Parameters
    ----------
    array : ArrayLike
        Array to save.
    kvstore : dict
        Tensorstore kvstore specification.
    spec : dict
        Tensorstore zarr specification.
    return_future : Optional[bool]
        Return future (True) or immediately write (False).

    Returns
    -------
    write_future : Optional[ArrayLike]
        Delayed (future) if return_future is True.
    """

    # check datatype
    if str(array.dtype) == "uint8":
        array_dtype = "<u1"
    elif str(array.dtype) == "uint16":
        array_dtype = "<u2"
    elif str(array.dtype) == "float16":
        array_dtype = "<f2"
    elif str(array.dtype) == "float32":
        array_dtype = "<f4"
    else:
        print("Unsupported data type: " + str(array.dtype))
        return None

    # check array dimension
    spec["metadata"]["shape"] = array.shape
    if len(array.shape) == 2:
        spec["metadata"]["chunks"] = [array.shape[0], array.shape[1]]
    elif len(array.shape) == 3:
        spec["metadata"]["chunks"] = [1, array.shape[1], array.shape[2]]
    elif len(array.shape) == 4:
        spec["metadata"]["chunks"] = [1, 1, array.shape[1], array.shape[2]]
    spec["metadata"]["dtype"] = array_dtype

    try:
        current_zarr = ts.open(
            {
                **spec,
                "kvstore": kvstore,
            }
        ).result()

        write_future = current_zarr.write(array)

        if return_future:
            return write_future
        else:
            write_future.result()
            return None
    except (IOError, OSError, TimeoutError):
        print("Error writing zarr array.")

initialize_tile(tile)

Initialize directory structure for a tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def initialize_tile(
    self,
    tile: Union[int, str],
):
    """Initialize directory structure for a tile.

    Parameters
    ----------
    tile : Union[int, 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:
        polyDT_tile_path = self._polyDT_root_path / Path(tile_id)
        polyDT_tile_path.mkdir()
        for round_idx, round_id in enumerate(self._round_ids):
            polyDT_round_path = polyDT_tile_path / Path(round_id + ".zarr")
            polyDT_round_path.mkdir()
            polydt_round_attrs_path = polyDT_round_path / Path(".zattrs")
            round_attrs = {
                "bit_linker": self._experiment_order.to_numpy()[round_idx, 1:]
                .astype(int)
                .tolist(),
            }
            self._save_to_json(round_attrs, polydt_round_attrs_path)
    except FileExistsError:
        print("Error creating polyDT 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 + ".zarr")
            readout_bit_path.mkdir()
            readout_bit_attrs_path = readout_bit_path / Path(".zattrs")
            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?")

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,
) -> Optional[tuple[Collection[str], ArrayLike]]:
    """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 fidicual optical flow matrix for one round and tile.

Parameters:

Name Type Description Default
tile Optional[Union[int, str]]

Tile index or tile id.

required
round Optional[Union[int, str]]

Round index or round id.

required
return_future Optional[bool]

Return future array.

True

Returns:

Name Type Description
of_xform_px Optional[ArrayLike]

Local fidicual optical flow matrix for one round and tile.

downsampling Optional[ArrayLike]

Downsampling factor.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_coord_of_xform_px(
    self,
    tile: Optional[Union[int, str]],
    round: Optional[Union[int, str]],
    return_future: Optional[bool] = True,
) -> Optional[tuple[ArrayLike, ArrayLike]]:
    """Local fidicual optical flow matrix for one round and tile.

    Parameters
    ----------
    tile : Optional[Union[int, str]]
        Tile index or tile id.
    round : Optional[Union[int, str]]
        Round index or round id.
    return_future : Optional[bool]
        Return future array.

    Returns
    -------
    of_xform_px : Optional[ArrayLike]
        Local fidicual optical flow matrix for one round and tile.
    downsampling : Optional[ArrayLike]
        Downsampling factor.
    """

    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:
            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

    current_local_zarr_path = str(
        self._polyDT_root_path
        / Path(tile_id)
        / Path(round_id + ".zarr")
        / Path("of_xform_px")
    )
    zattrs_path = str(
        self._polyDT_root_path
        / Path(tile_id)
        / Path(round_id + ".zarr")
        / Path(".zattrs")
    )

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

    try:
        compressor = {
            "id": "blosc",
            "cname": "zstd",
            "clevel": 5,
            "shuffle": 2,
        }
        spec_of = {
            "driver": "zarr",
            "kvstore": None,
            "metadata": {"compressor": compressor},
            "open": True,
            "assume_metadata": False,
            "create": True,
            "delete_existing": False,
        }
        spec_of["metadata"]["dtype"] = "<f4"
        of_xform_px = self._load_from_zarr_array(
            self._get_kvstore_key(current_local_zarr_path),
            spec_of.copy(),
            return_future,
        )
        attributes = self._load_from_json(zattrs_path)
        downsampling = np.asarray(
            attributes["opticalflow_downsampling"], dtype=np.float32
        )

        return of_xform_px, downsampling
    except (IOError, OSError, ZarrError) as e:
        print(e)
        print("Error loading optical flow transform.")
        return None

load_global_baysor_filtered_spots()

Load Baysor re-assigned decoded RNA.

Assumes Baysor has been run.

Returns:

Name Type Description
baysor_filtered_genes Optional[DataFrame]

Baysor re-assigned decoded RNA.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_baysor_filtered_spots(
    self,
) -> Optional[pd.DataFrame]:
    """Load Baysor re-assigned decoded RNA.

    Assumes Baysor has been run.

    Returns
    -------
    baysor_filtered_genes : Optional[pd.DataFrame]
        Baysor re-assigned decoded RNA.
    """

    current_baysor_spots_path = (
        self._segmentation_root_path
        / Path("baysor")
        / Path("segmentation.csv")
    )

    if not current_baysor_spots_path.exists():
        print("Baysor filtered genes not found.")
        return None
    else:
        baysor_filtered_genes = self._load_from_csv(current_baysor_spots_path)
        return baysor_filtered_genes

load_global_baysor_outlines()

Load Baysor cell outlines.

Assumes Baysor has been run.

Returns:

Name Type Description
baysor_outlines Optional[dict]

Baysor cell outlines.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_baysor_outlines(
    self,
) -> Optional[dict]:
    """Load Baysor cell outlines.

    Assumes Baysor has been run.

    Returns
    -------
    baysor_outlines : Optional[dict]
        Baysor cell outlines.
    """

    current_baysor_outlines_path = (
        self._segmentation_root_path 
        / Path("baysor") 
        / Path(r"3d_cell_rois.zip")
    )

    if not current_baysor_outlines_path.exists():
        print("Baysor outlines not found.")
        return None
    else:
        baysor_rois = roiread(current_baysor_outlines_path)
        return baysor_rois

load_global_cellpose_outlines()

Load Cellpose max projection cell outlines.

Returns:

Name Type Description
cellpose_outlines Optional[dict]

Cellpose cell mask outlines.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_cellpose_outlines(
    self,
) -> Optional[dict]:
    """Load Cellpose max projection cell outlines.

    Returns
    -------
    cellpose_outlines : Optional[dict]
        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_segmentation_image(return_future=True)

Load Cellpose max projection, downsampled segmentation image.

Parameters:

Name Type Description Default
return_future Optional[bool]

Return future array.

True

Returns:

Name Type Description
fused_image Optional[ArrayLike]

Cellpose max projection, downsampled segmentation image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_cellpose_segmentation_image(
    self,
    return_future: Optional[bool] = True,
) -> Optional[ArrayLike]:
    """Load Cellpose max projection, downsampled segmentation image.

    Parameters
    ----------
    return_future : Optional[bool]
        Return future array.

    Returns
    -------
    fused_image : Optional[ArrayLike]
        Cellpose max projection, downsampled segmentation image.
    """

    current_local_zarr_path = str(
        self._segmentation_root_path
        / Path("cellpose")
        / Path("cellpose.zarr")
        / Path("masks_polyDT_iso_zyx")
    )

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

    try:
        fused_image = self._load_from_zarr_array(
            self._get_kvstore_key(current_local_zarr_path),
            self._zarrv2_spec.copy(),
            return_future,
        )
        return fused_image
    except (IOError, OSError, ZarrError):
        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 Union[int, str]

Tile index or tile id.

required

Returns:

Name Type Description
affine_zyx_um Optional[ArrayLike]

Global affine registration transform for one tile.

origin_zyx_um Optional[ArrayLike]

Global origin registration transform for one tile.

spacing_zyx_um Optional[ArrayLike]

Global spacing registration transform for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_coord_xforms_um(
    self,
    tile: Union[int, str],
) -> Optional[tuple[ArrayLike, ArrayLike, ArrayLike]]:
    """Load global registration transform for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.

    Returns
    -------
    affine_zyx_um : Optional[ArrayLike]
        Global affine registration transform for one tile.
    origin_zyx_um : Optional[ArrayLike]
        Global origin registration transform for one tile.
    spacing_zyx_um : Optional[ArrayLike]
        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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(self._round_ids[0] + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_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 = np.asarray(attributes["spacing_zyx_um"], dtype=np.float32)
        return (affine_zyx_um, origin_zyx_um, spacing_zyx_um)
    except (FileNotFoundError, json.JSONDecodeError):
        print(tile_id, self._round_ids[0])
        print("Global coordinate transforms not found")
        return None, None, None

load_global_fidicual_image(return_future=True)

Load downsampled, fused fidicual image.

Parameters:

Name Type Description Default
return_future Optional[bool]

Return future array.

True

Returns:

Name Type Description
fused_image Optional[ArrayLike]

Downsampled, fused fidicual image.

affine_zyx_um Optional[ArrayLike]

Global affine registration transform for fused image.

origin_zyx_um Optional[ArrayLike]

Global origin registration transform for fused image.

spacing_zyx_um Optional[ArrayLike]

Global spacing registration transform for fused image.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_fidicual_image(
    self,
    return_future: Optional[bool] = True,
) -> Optional[tuple[ArrayLike, ArrayLike, ArrayLike, ArrayLike]]:
    """Load downsampled, fused fidicual image.

    Parameters
    ----------
    return_future : Optional[bool]
        Return future array.

    Returns
    -------
    fused_image : Optional[ArrayLike]
        Downsampled, fused fidicual image.
    affine_zyx_um : Optional[ArrayLike]
        Global affine registration transform for fused image.
    origin_zyx_um : Optional[ArrayLike]
        Global origin registration transform for fused image.
    spacing_zyx_um : Optional[ArrayLike]
        Global spacing registration transform for fused image.
    """

    current_local_zarr_path = str(
        self._fused_root_path / Path("fused.zarr") / Path("fused_polyDT_iso_zyx")
    )

    if not Path(current_local_zarr_path).exists():
        print("Globally registered, fused image not found.")
        return None

    zattrs_path = str(current_local_zarr_path / Path(".zattrs"))

    try:
        fused_image = self._load_from_zarr_array(
            self._get_kvstore_key(current_local_zarr_path),
            self._zarrv2_spec.copy(),
            return_future,
        )
        attributes = self._load_from_json(zattrs_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 = np.asarray(attributes["spacing_zyx_um"], dtype=np.float32)
        return fused_image, affine_zyx_um, origin_zyx_um, spacing_zyx_um
    except (IOError, OSError, ZarrError):
        print("Error loading globally registered, fused image.")
        return None

load_global_filtered_decoded_spots()

Load all decoded and filtered spots.

Returns:

Name Type Description
all_tiles_filtered Optional[DataFrame]

All decoded and filtered spots.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_global_filtered_decoded_spots(
    self,
) -> Optional[pd.DataFrame]:
    """Load all decoded and filtered spots.

    Returns
    -------
    all_tiles_filtered : Optional[pd.DataFrame]
        All decoded and filtered spots.
    """

    current_global_filtered_decoded_dir_path = self._datastore_path / Path(
        "all_tiles_filtered_decoded_features"
    )
    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
    else:
        all_tiles_filtered = self._load_from_parquet(
            current_global_filtered_decoded_path
        )
        return all_tiles_filtered

load_local_bit_linker(tile, round)

Load readout bits linked to fidicual round for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
round Union[int, str]

Round index or round id.

required

Returns:

Name Type Description
bit_linker Optional[Sequence[int]]

Readout bits linked to fidicual round for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_bit_linker(
    self,
    tile: Union[int, str],
    round: Union[int, str],
) -> Optional[Sequence[int]]:
    """Load readout bits linked to fidicual round for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    round : Union[int, str]
        Round index or round id.

    Returns
    -------
    bit_linker : Optional[Sequence[int]]
        Readout bits linked to fidicual 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:
            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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        return attributes["bits"][1:]
    except (FileNotFoundError, json.JSONDecodeError):
        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 Union[int, str]

Tile index or tile id.

required
round Optional[Union[int, str]]

Round index or round id.

None
bit Optional[Union[int, str]]

Bit index or bit id.

None
return_future Optional[bool]

Return future array.

True

Returns:

Name Type Description
corrected_image Optional[ArrayLike]

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: Union[int, str],
    round: Optional[Union[int, str]] = None,
    bit: Optional[Union[int, str]] = None,
    return_future: Optional[bool] = True,
) -> Optional[ArrayLike]:
    """Load gain and offset corrected image for fiducial OR readout bit for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    round : Optional[Union[int, str]]
        Round index or round id.
    bit : Optional[Union[int, str]]
        Bit index or bit id.
    return_future : Optional[bool]
        Return future array.

    Returns
    -------
    corrected_image : Optional[ArrayLike]
        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 + ".zarr")
            / Path("corrected_data")
        )
    else:
        if isinstance(round, int):
            if round < 0:
                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._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path("corrected_data")
        )

    if not Path(current_local_zarr_path).exists():
        print("Corrected image not found.")
        return None

    try:
        spec = self._zarrv2_spec.copy()
        spec["metadata"]["dtype"] = "<u2"
        corrected_image = self._load_from_zarr_array(
            self._get_kvstore_key(current_local_zarr_path),
            spec,
            return_future,
        )
        return corrected_image
    except (IOError, OSError, ZarrError):
        print("Error loading corrected image.")
        return None

load_local_decoded_spots(tile)

Load decoded spots and features for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required

Returns:

Name Type Description
tile_features Optional[DataFrame]

Decoded spots and features for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_decoded_spots(
    self,
    tile: Union[int, str],
) -> Optional[pd.DataFrame]:
    """Load decoded spots and features for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.

    Returns
    -------
    tile_features : Optional[pd.DataFrame]
        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_root_path / 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_registered_image(tile, round=None, bit=None, return_future=True)

Local registered, deconvolved image for fidiculial OR readout bit for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
round Optional[Union[int, str]]

Round index or round id.

None
bit Optional[Union[int, str]]

Bit index or bit id.

None
return_future Optional[bool]

Return future array.

True

Returns:

Name Type Description
registered_decon_image Optional[ArrayLike]

Registered, deconvolved image for fidiculial OR readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_registered_image(
    self,
    tile: Union[int, str],
    round: Optional[Union[int, str]] = None,
    bit: Optional[Union[int, str]] = None,
    return_future: Optional[bool] = True,
) -> Optional[ArrayLike]:
    """Local registered, deconvolved image for fidiculial OR readout bit for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    round : Optional[Union[int, str]]
        Round index or round id.
    bit : Optional[Union[int, str]]
        Bit index or bit id.
    return_future : Optional[bool]
        Return future array.

    Returns
    -------
    registered_decon_image : Optional[ArrayLike]
        Registered, deconvolved image for fidiculial 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 + ".zarr")
            / Path("registered_decon_data")
        )
    else:
        if isinstance(round, int):
            if round < 0:
                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._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path("registered_decon_data")
        )

    if not Path(current_local_zarr_path).exists():
        print("Registered deconvolved image not found.")
        return None

    try:
        spec = self._zarrv2_spec.copy()
        spec["metadata"]["dtype"] = "<u2"
        registered_decon_image = self._load_from_zarr_array(
            self._get_kvstore_key(current_local_zarr_path),
            spec,
            return_future,
        )
        return registered_decon_image
    except (IOError, OSError, ZarrError) as e:
        print(e)
        print("Error loading registered deconvolved image.")
        return None

load_local_rigid_xform_xyz_px(tile, round)

Load calculated rigid registration transform for one round and tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
round Union[int, str]

Round index or round id.

required

Returns:

Name Type Description
rigid_xform_xyz_px Optional[ArrayLike]

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: Union[int, str],
    round: Union[int, str],
) -> Optional[ArrayLike]:
    """Load calculated rigid registration transform for one round and tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    round : Union[int, str]
        Round index or round id.

    Returns
    -------
    rigid_xform_xyz_px : Optional[ArrayLike]
        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:
            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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        rigid_xform_xyz_px = np.asarray(
            attributes["rigid_xform_xyz_px"], dtype=np.float32
        )
        return rigid_xform_xyz_px
    except (FileNotFoundError, json.JSONDecodeError):
        print(tile_id, round_id)
        print("Rigid transform mapping back to first round not found.")
        return None

load_local_round_linker(tile, bit)

Load fidicual round linked to readout bit for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
bit Union[int, str]

Bit index or bit id.

required

Returns:

Name Type Description
round_linker Optional[Sequence[int]]

Fidicual round linked to readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_round_linker(
    self,
    tile: Union[int, str],
    bit: Union[int, str],
) -> Optional[Sequence[int]]:
    """Load fidicual round linked to readout bit for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    bit : Union[int, str]
        Bit index or bit id.

    Returns
    -------
    round_linker : Optional[Sequence[int]]
        Fidicual 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:
        zattrs_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(bit_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        return int(attributes["round_linker"])
    except FileNotFoundError:
        print(tile_id, bit_id)
        print("Round linker attribute not found.")
        return None

load_local_stage_position_zyx_um(tile, round)

Load tile stage position for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
round Union[int, str]

Round index or round id.

required

Returns:

Name Type Description
stage_zyx_um Optional[ArrayLike]

Tile stage position for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_stage_position_zyx_um(
    self,
    tile: Union[int, str],
    round: Union[int, str],
) -> Optional[ArrayLike]:
    """Load tile stage position for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    round : Union[int, str]
        Round index or round id.

    Returns
    -------
    stage_zyx_um : Optional[ArrayLike]
        Tile stage position 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:
            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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        return np.asarray(attributes["stage_zyx_um"], dtype=np.float32)
    except FileNotFoundError:
        print(tile_id, round_id)
        print("Stage position attribute not found.")
        return None

load_local_ufish_image(tile, bit, return_future=True)

Load readout bit U-FISH prediction image for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
bit Union[int, str]

Bit index or bit id.

required
return_future Optional[bool]
True

Returns:

Name Type Description
registered_ufish_image Optional[ArrayLike]

U-FISH prediction image for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_ufish_image(
    self,
    tile: Union[int, str],
    bit: Union[int, str],
    return_future: Optional[bool] = True,
) -> Optional[ArrayLike]:
    """Load readout bit U-FISH prediction image for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    bit : Union[int, str]
        Bit index or bit id.
    return_future : Optional[bool]

    Returns
    -------
    registered_ufish_image : Optional[ArrayLike]
        U-FISH 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 + ".zarr")
        / Path("registered_ufish_data")
    )

    if not Path(current_local_zarr_path).exists():
        print("U-FISH prediction image not found.")
        return None

    try:
        spec = self._zarrv2_spec.copy()
        spec["metadata"]["dtype"] = "<f4"
        registered_ufish_image = self._load_from_zarr_array(
            self._get_kvstore_key(current_local_zarr_path),
            spec,
            return_future,
        )
        return registered_ufish_image
    except (IOError, OSError, ZarrError) as e:
        print(e)
        print("Error loading U-FISH image.")
        return None

load_local_ufish_spots(tile, bit)

Load U-FISH spot localizations and features for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
bit Union[int, str]

Bit index or bit id.

required

Returns:

Name Type Description
ufish_localizations Optional[DataFrame]

U-FISH localizations and features for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_ufish_spots(
    self,
    tile: Union[int, str],
    bit: Union[int, str],
) -> Optional[pd.DataFrame]:
    """Load U-FISH spot localizations and features for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    bit : Union[int, str]
        Bit index or bit id.

    Returns
    -------
    ufish_localizations : Optional[pd.DataFrame]
        U-FISH 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_ufish_localizations_path = (
        self._ufish_localizations_root_path
        / Path(tile_id)
        / Path(bit_id + ".parquet")
    )

    if not current_ufish_localizations_path.exists():
        print("U-FISH localizations not found.")
        return None
    else:
        ufish_localizations = self._load_from_parquet(
            current_ufish_localizations_path
        )
        return ufish_localizations

load_local_wavelengths_um(tile, round=None, bit=None)

Load wavelengths for fidicual OR readout bit for one tile.

Parameters:

Name Type Description Default
tile Union[int, str]

Tile index or tile id.

required
round Optional[Union[int, str]]

Round index or round id.

None
bit Optional[Union[int, str]]

Bit index or bit id.

None

Returns:

Name Type Description
wavelengths_um Optional[tuple[float, float]]

Wavelengths for fidicual OR readout bit for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def load_local_wavelengths_um(
    self,
    tile: Union[int, str],
    round: Optional[Union[int, str]] = None,
    bit: Optional[Union[int, str]] = None,
) -> Optional[tuple[float, float]]:
    """Load wavelengths for fidicual OR readout bit for one tile.

    Parameters
    ----------
    tile : Union[int, str]
        Tile index or tile id.
    round : Optional[Union[int, str]]   
        Round index or round id.
    bit : Optional[Union[int, str]]
        Bit index or bit id.

    Returns
    -------
    wavelengths_um : Optional[tuple[float, float]]
        Wavelengths for fidicual 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
        zattrs_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )
    else:
        if isinstance(round, int):
            if round < 0:
                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
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )

    try:
        attributes = self._load_from_json(zattrs_path)
        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

reformat_baysor_3D_oultines()

Reformat baysor 3D json file into ImageJ ROIs.

Source code in src/merfish3danalysis/qi2labDataStore.py
def reformat_baysor_3D_oultines(self):
    """Reformat baysor 3D json file into ImageJ ROIs."""
    import re

    # Load the JSON file
    baysor_output_path = self._segmentation_root_path / Path("baysor")
    baysor_segmentation = baysor_output_path / Path(r"segmentation_polygons_3d.json")
    with open(baysor_segmentation, 'r') as file:
        data = json.load(file)


    # Dictionary to group polygons by cell ID
    cell_polygons = defaultdict(list)

    def parse_z_range(z_range):
        cleaned_range = re.sub(r"[^\d.,-]", "", z_range)  # Remove non-numeric, non-period, non-comma, non-dash characters
        return map(float, cleaned_range.split(","))

    # Iterate through each z-plane and corresponding polygons
    for z_range, details in data.items():
        z_start, z_end = parse_z_range(z_range)

        for geometry in details["geometries"]:
            coordinates = geometry["coordinates"][0]  # Assuming the outer ring of the polygon
            cell_id = geometry["cell"]  # Get the cell ID

            # Store the polygon with its z-range
            cell_polygons[cell_id].append({
                "z_start": z_start,
                "z_end": z_end,
                "coordinates": coordinates
            })

    rois = []

    # Process each cell ID to create 3D ROIs
    for cell_id, polygons in cell_polygons.items():
        for idx, polygon in enumerate(polygons):
            x_coords = [point[0] for point in polygon["coordinates"]]
            y_coords = [point[1] for point in polygon["coordinates"]]


            z_start = polygon["z_start"]
            z_end = polygon["z_end"]

            try:
                # Create an ImageJRoi object for the polygon using frompoints
                coords = list(zip(x_coords, y_coords))  # List of (x, y) tuples
                roi = ImagejRoi.frompoints(coords)
                roi.roitype = ROI_TYPE.POLYGON  # Set the ROI type to Polygon
                roi.coordinates = coords  # Explicitly assign coordinates to the ROI
                roi.name = f"cell_{str(cell_id)}_zstart_{str(z_start)}_zend_{str(z_end)}"  # Ensure unique name
                rois.append(roi)
            except Exception as e:
                print(f"Error while creating ROI for cell ID {cell_id}: {e}")

    # Write all ROIs to a ZIP file   
    output_file = baysor_output_path / Path(r"3d_cell_rois.zip")
    roiwrite(output_file, rois,mode='w')

reprocess_and_save_filtered_spots_with_baysor_outlines()

Reprocess filtered spots using baysor cell outlines, then save.

Loads the 3D cell outlines from Baysor, checks all points to see what (if any) cell outline that the spot falls within, and then saves the data back to the datastore.

Source code in src/merfish3danalysis/qi2labDataStore.py
def reprocess_and_save_filtered_spots_with_baysor_outlines(self):
    """Reprocess filtered spots using baysor cell outlines, then save.

    Loads the 3D cell outlines from Baysor, checks all points to see what 
    (if any) cell outline that the spot falls within, and then saves the
    data back to the datastore.
    """
    from rtree import index
    import re

    rois = self.load_global_baysor_outlines()
    filtered_spots_df = self.load_global_filtered_decoded_spots()

    parsed_spots_df = filtered_spots_df[
            [
                "gene_id",
                "global_z",
                "global_y",
                "global_x",
                "cell_id",
                "tile_idx",
            ]
    ].copy()
    parsed_spots_df.rename(
        columns={
            "global_x": "x",
            "global_y": "y",
            "global_z": "z",
            "gene_id" : "gene",
            "cell_id" : "cell",
        },
        inplace=True,
    )
    parsed_spots_df["transcript_id"] = pd.util.hash_pandas_object(
        parsed_spots_df, index=False
    )

    parsed_spots_df["assignment_confidence"] = 1.0

    # Create spatial index for ROIs
    roi_index = index.Index()
    roi_map = {}  # Map index IDs to ROIs

    for idx, roi in enumerate(rois):
        # Ensure roi.coordinates contains the polygon points
        coords = roi.coordinates()

        # Insert the polygon bounds into the spatial index
        polygon = Polygon(coords)
        roi_index.insert(idx, polygon.bounds)  # Use polygon bounds for indexing
        roi_map[idx] = roi

    # Function to check a single point
    def point_in_roi(row):
        point = Point(row["x"], row["y"])
        candidate_indices = list(roi_index.intersection(point.bounds))  # Search spatial index
        for idx in candidate_indices:
            roi = roi_map[idx]
            match = re.search(r"zstart_([-\d.]+)_zend_([-\d.]+)", roi.name)
            if match:
                z_start = float(match.group(1))
                z_end = float(match.group(2))
                if z_start <= row["z"] <= z_end:
                    polygon = Polygon(roi.coordinates())
                    if polygon.contains(point):
                        return str(roi.name.split("_")[1]) 
        return -1

    # Apply optimized spatial lookup
    parsed_spots_df["cell"] = parsed_spots_df.apply(point_in_roi, axis=1)
    parsed_spots_df = parsed_spots_df.loc[parsed_spots_df["cell"] != -1]

    current_global_filtered_decoded_path = (
        self._datastore_path 
        / Path("all_tiles_filtered_decoded_features")
        / Path("refined_transcripts.parquet")
    )

    self._save_to_parquet(parsed_spots_df, current_global_filtered_decoded_path)

run_baysor()

Run Baysor"

Assumes that spots are prepped for Baysor and the Baysor path and options are set. Reformats ROIs into ImageJ style ROIs for later use.

Source code in src/merfish3danalysis/qi2labDataStore.py
def run_baysor(self):
    """Run Baysor"

    Assumes that spots are prepped for Baysor and the Baysor path and options are set.
    Reformats ROIs into ImageJ style ROIs for later use.
    """

    import subprocess

    baysor_input_path = self._datastore_path / Path("all_tiles_filtered_decoded_features") / Path("transcripts.parquet")
    baysor_output_path = self._segmentation_root_path / Path("baysor")
    baysor_output_path.mkdir(exist_ok=True)

    julia_threading = r"JULIA_NUM_THREADS="+str(self._julia_threads)+ " "
    preview_baysor_options = r"preview -c " +str(self._baysor_options)
    command = julia_threading + str(self._baysor_path) + " " + preview_baysor_options + " " +\
        str(baysor_input_path) + " -o " + str(baysor_output_path)

    try:
        result = subprocess.run(command, shell=True, check=True)
        print("Baysor finished with return code:", result.returncode)
    except subprocess.CalledProcessError as e:
        print("Baysor failed with:", e)

    # first try to run Baysor assuming that prior segmentations are present               
    try:
        run_baysor_options = r"run -p -c " +str(self._baysor_options)
        command = julia_threading + str(self._baysor_path) + " " + run_baysor_options + " " +\
            str(baysor_input_path) + " -o " + str(baysor_output_path) + \
            " --polygon-format GeometryCollectionLegacy --count-matrix-format tsv :cell_id"
        result = subprocess.run(command, shell=True, check=True)
        print("Baysor finished with return code:", result.returncode)
    except subprocess.CalledProcessError:
        # then fall back and run without prior segmentations.
        # IMPORTANT: the .toml file has to be defined correctly for this to work!
        try:
            run_baysor_options = r"run -p -c " +str(self._baysor_options)
            command = julia_threading + str(self._baysor_path) + " " + run_baysor_options + " " +\
                str(baysor_input_path) + " -o " + str(baysor_output_path) + " --count-matrix-format tsv"
            result = subprocess.run(command, shell=True, check=True)
            print("Baysor finished with return code:", result.returncode)
        except subprocess.CalledProcessError as e:
            print("Baysor failed with:", e)

save_coord_of_xform_px(of_xform_px, tile, downsampling, round, return_future=False)

Save fidicual optical flow matrix for one round and tile.

Parameters:

Name Type Description Default
of_xform_px ArrayLike

Local fidicual optical flow matrix for one round and tile.

required
tile Union[int, str]

Tile index or tile id.

required
downsampling Sequence[float]

Downsampling factor.

required
round Union[int, str]

Round index or round id.

required
return_future Optional[bool]

Return future array.

False
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_coord_of_xform_px(
    self,
    of_xform_px: ArrayLike,
    tile: Union[int, str],
    downsampling: Sequence[float],
    round: Union[int, str],
    return_future: Optional[bool] = False,
):
    """Save fidicual optical flow matrix for one round and tile.

    Parameters
    ----------
    of_xform_px : ArrayLike
        Local fidicual optical flow matrix for one round and tile.
    tile : Union[int, str]
        Tile index or tile id.
    downsampling : Sequence[float]
        Downsampling factor.
    round : Union[int, str] 
        Round index or round id.
    return_future : Optional[bool]
        Return future array.
    """

    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:
            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._polyDT_root_path
        / Path(tile_id)
        / Path(local_id + ".zarr")
        / Path("of_xform_px")
    )
    current_local_zattrs_path = str(
        self._polyDT_root_path
        / Path(tile_id)
        / Path(local_id + ".zarr")
        / Path(".zattrs")
    )

    try:
        compressor = {
            "id": "blosc",
            "cname": "zstd",
            "clevel": 5,
            "shuffle": 2,
        }
        spec_of = {
            "driver": "zarr",
            "kvstore": None,
            "metadata": {"compressor": compressor},
            "open": True,
            "assume_metadata": False,
            "create": True,
            "delete_existing": False,
        }
        self._save_to_zarr_array(
            of_xform_px,
            self._get_kvstore_key(current_local_zarr_path),
            spec_of.copy(),
            return_future,
        )
        attributes = self._load_from_json(current_local_zattrs_path)
        attributes["opticalflow_downsampling"] = downsampling
        self._save_to_json(attributes, current_local_zattrs_path)
    except (IOError, OSError, TimeoutError):
        print("Error saving optical flow transform.")
        return None

save_global_cellpose_segmentation_image(cellpose_image, downsampling, return_future=False)

Save Cellpose max projection, downsampled segmentation image.

Parameters:

Name Type Description Default
cellpose_image ArrayLike

Cellpose max projection, downsampled segmentation image.

required
downsampling Sequence[float]

Downsample factors.

required
return_future Optional[bool]

Return future array.

False
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_cellpose_segmentation_image(
    self,
    cellpose_image: ArrayLike,
    downsampling: Sequence[float],
    return_future: Optional[bool] = False,
):
    """Save Cellpose max projection, downsampled segmentation image.

    Parameters
    ----------
    cellpose_image : ArrayLike
        Cellpose max projection, downsampled segmentation image.
    downsampling : Sequence[float]
        Downsample factors.
    return_future : Optional[bool]
        Return future array.
    """

    current_local_zarr_path = str(
        self._segmentation_root_path
        / Path("cellpose")
        / Path("cellpose.zarr")
        / Path("masks_polyDT_iso_zyx")
    )
    current_local_zattrs_path = str(
        self._segmentation_root_path
        / Path("cellpose")
        / Path("cellpose.zarr")
        / Path("masks_polyDT_iso_zyx")
        / Path(".zattrs")
    )

    attributes = {"downsampling": downsampling}

    try:
        self._save_to_zarr_array(
            cellpose_image,
            self._get_kvstore_key(current_local_zarr_path),
            self._zarrv2_spec.copy(),
            return_future,
        )
        self._save_to_json(attributes, current_local_zattrs_path)
    except (IOError, OSError, TimeoutError):
        print("Error saving Cellpose image.")
        return None

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

Global affine registration transform for one tile.

required
origin_zyx_um ArrayLike

Global origin registration transform for one tile.

required
spacing_zyx_um ArrayLike

Global spacing registration transform for one tile.

required
tile Union[int, 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: Union[int, str],
) -> None:
    """Save global registration transform for one tile.

    Parameters
    ----------
    affine_zyx_um : ArrayLike
        Global affine registration transform for one tile.
    origin_zyx_um : ArrayLike
        Global origin registration transform for one tile.
    spacing_zyx_um : ArrayLike
        Global spacing registration transform for one tile.
    tile : Union[int, 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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(self._round_ids[0] + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        attributes["affine_zyx_um"] = affine_zyx_um.tolist()
        attributes["origin_zyx_um"] = origin_zyx_um.tolist()
        attributes["spacing_zyx_um"] = spacing_zyx_um.tolist()
        self._save_to_json(attributes, zattrs_path)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(e)
        print("Could not save global coordinate transforms.")

save_global_fidicual_image(fused_image, affine_zyx_um, origin_zyx_um, spacing_zyx_um, fusion_type='polyDT', return_future=False)

Save downsampled, fused fidicual image.

Parameters:

Name Type Description Default
fused_image ArrayLike

Downsampled, fused fidicual 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

Global spacing registration transform for fused image.

required
fusion_type str

Type of fusion (polyDT or all_channels).

'polyDT'
return_future Optional[bool]

Return future array.

False
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_fidicual_image(
    self,
    fused_image: ArrayLike,
    affine_zyx_um: ArrayLike,
    origin_zyx_um: ArrayLike,
    spacing_zyx_um: ArrayLike,
    fusion_type: str = "polyDT",
    return_future: Optional[bool] = False,
):
    """Save downsampled, fused fidicual image.

    Parameters
    ----------
    fused_image : ArrayLike
        Downsampled, fused fidicual 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
        Global spacing registration transform for fused image.
    fusion_type : str
        Type of fusion (polyDT or all_channels).
    return_future : Optional[bool]
        Return future array.
    """

    if fusion_type == "polyDT":
        filename = "fused_polyDT_iso_zyx"
    else:
        filename = "fused_all_channels_zyx"
    current_local_zarr_path = str(
        self._fused_root_path / Path("fused.zarr") / Path(filename)
    )
    current_local_zattrs_path = str(
        self._fused_root_path
        / Path("fused.zarr")
        / Path(filename)
        / Path(".zattrs")
    )

    attributes = {
        "affine_zyx_um": affine_zyx_um.tolist(),
        "origin_zyx_um": origin_zyx_um.tolist(),
        "spacing_zyx_um": spacing_zyx_um.tolist(),
    }
    try:
        self._save_to_zarr_array(
            fused_image.astype(np.uint16),
            self._get_kvstore_key(current_local_zarr_path),
            self._zarrv2_spec.copy(),
            return_future,
        )
        self._save_to_json(attributes, current_local_zattrs_path)
    except (IOError, OSError, TimeoutError):
        print("Error saving fused image.")
        return None

save_global_filtered_decoded_spots(filtered_decoded_df)

Save all decoded and filtered spots.

Parameters:

Name Type Description Default
filtered_decoded_df DataFrame

All decoded and filtered spots.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_global_filtered_decoded_spots(
    self,
    filtered_decoded_df: pd.DataFrame,
):
    """Save all decoded and filtered spots.

    Parameters
    ----------
    filtered_decoded_df : pd.DataFrame
        All decoded and filtered spots.
    """

    current_global_filtered_decoded_dir_path = self._datastore_path / Path(
        "all_tiles_filtered_decoded_features"
    )

    if not current_global_filtered_decoded_dir_path.exists():
        current_global_filtered_decoded_dir_path.mkdir()

    current_global_filtered_decoded_path = (
        current_global_filtered_decoded_dir_path / Path("decoded_features.parquet")
    )

    self._save_to_parquet(filtered_decoded_df, current_global_filtered_decoded_path)

save_local_bit_linker(bit_linker, tile, round)

Save readout bits linked to fidicual round for one tile.

Parameters:

Name Type Description Default
bit_linker Sequence[int]

Readout bits linked to fidicual round for one tile.

required
tile Union[int, str]

Tile index or tile id.

required
round Union[int, 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: Union[int, str],
    round: Union[int, str],
):
    """Save readout bits linked to fidicual round for one tile.

    Parameters
    ----------
    bit_linker : Sequence[int]
        Readout bits linked to fidicual round for one tile.
    tile : Union[int, str]
        Tile index or tile id.
    round : Union[int, 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:
            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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        attributes["bits"] = bit_linker
        self._save_to_json(attributes, zattrs_path)
    except (FileNotFoundError, json.JSONDecodeError):
        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 Union[int, 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 Optional[Union[int, str]]

Round index or round id.

None
bit Optional[Union[int, str]]

Bit index or bit id.

None
return_future Optional[bool]

Return future array.

False
Source code in src/merfish3danalysis/qi2labDataStore.py
 def save_local_corrected_image(
     self,
     image: ArrayLike,
     tile: Union[int, str],
     gain_correction: bool = True,
     hotpixel_correction: bool = True,
     shading_correction: bool = False,
     psf_idx: int = 0,
     round: Optional[Union[int, str]] = None,
     bit: Optional[Union[int, str]] = None,
     return_future: Optional[bool] = False,
 ):
     """Save gain and offset corrected image.

     Parameters
     ----------
     image : ArrayLike
         Local corrected image.
     tile : Union[int, 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 : Optional[Union[int, str]]
         Round index or round id.
     bit : Optional[Union[int, str]]
         Bit index or bit id.
     return_future : Optional[bool]
         Return future array.
"""

     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 + ".zarr")
             / Path("corrected_data")
         )
         current_local_zattrs_path = str(
             self._readouts_root_path
             / Path(tile_id)
             / Path(local_id + ".zarr")
             / Path(".zattrs")
         )
     else:
         if isinstance(round, int):
             if round < 0:
                 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._polyDT_root_path
             / Path(tile_id)
             / Path(local_id + ".zarr")
             / Path("corrected_data")
         )
         current_local_zattrs_path = str(
             self._polyDT_root_path
             / Path(tile_id)
             / Path(local_id + ".zarr")
             / Path(".zattrs")
         )

     try:
         self._save_to_zarr_array(
             image,
             self._get_kvstore_key(current_local_zarr_path),
             self._zarrv2_spec,
             return_future,
         )
         attributes = self._load_from_json(current_local_zattrs_path)
         attributes["gain_correction"] = (gain_correction,)
         attributes["hotpixel_correction"] = (hotpixel_correction,)
         attributes["shading_correction"] = (shading_correction,)
         attributes["psf_idx"] = psf_idx
         self._save_to_json(attributes, current_local_zattrs_path)
     except (IOError, OSError, TimeoutError) as e:
         print(e)
         print("Error saving corrected image.")
         return None

save_local_decoded_spots(features_df, tile)

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 Union[int, str]

Tile index or tile id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_decoded_spots(
    self,
    features_df: pd.DataFrame,
    tile: Union[int, str],
) -> None:
    """Save decoded spots and features for one tile.

    Parameters
    ----------
    features_df : pd.DataFrame
        Decoded spots and features for one tile.
    tile : Union[int, 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

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

    self._save_to_parquet(features_df, current_tile_features_path)

save_local_registered_image(registered_image, tile, deconvolution=True, round=None, bit=None, return_future=False)

Save registered, deconvolved image.

Parameters:

Name Type Description Default
registered_image ArrayLike

Registered, deconvolved image.

required
tile Union[int, str]

Tile index or tile id.

required
deconvolution bool

Deconvolution applied (True) or not (False).

True
round Optional[Union[int, str]]

Round index or round id.

None
bit Optional[Union[int, str]]

Bit index or bit id.

None
return_future Optional[bool]

Return future array.

False
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_registered_image(
    self,
    registered_image: ArrayLike,
    tile: Union[int, str],
    deconvolution: bool = True,
    round: Optional[Union[int, str]] = None,
    bit: Optional[Union[int, str]] = None,
    return_future: Optional[bool] = False,
):
    """Save registered, deconvolved image.

    Parameters
    ----------
    registered_image : ArrayLike
        Registered, deconvolved image.
    tile : Union[int, str]
        Tile index or tile id.
    deconvolution : bool
        Deconvolution applied (True) or not (False).
    round : Optional[Union[int, str]]
        Round index or round id.
    bit : Optional[Union[int, str]]
        Bit index or bit id.
    return_future : Optional[bool]
        Return future array.
    """

    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 + ".zarr")
            / Path("registered_decon_data")
        )
        current_local_zattrs_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )
    else:
        if isinstance(round, int):
            if round < 0:
                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._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path("registered_decon_data")
        )
        current_local_zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )

    try:
        spec = self._zarrv2_spec.copy()
        spec["metadata"]["dtype"] = "<u2"
        self._save_to_zarr_array(
            registered_image,
            self._get_kvstore_key(current_local_zarr_path),
            spec,
            return_future,
        )
        attributes = self._load_from_json(current_local_zattrs_path)
        attributes["deconvolution"] = deconvolution
        self._save_to_json(attributes, current_local_zattrs_path)
    except (IOError, OSError, TimeoutError):
        print("Error saving corrected image.")
        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 Union[int, str]

Tile index or tile id.

required
round Union[int, str]

Round index or round id.

required

Returns:

Name Type Description
rigid_xform_xyz_px Optional[ArrayLike]

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: Union[int, str],
    round: Union[int, str],
) -> Optional[ArrayLike]:
    """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 : Union[int, str]
        Tile index or tile id.
    round : Union[int, str]
        Round index or round id.

    Returns
    -------
    rigid_xform_xyz_px : Optional[ArrayLike]
        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:
            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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        attributes["rigid_xform_xyz_px"] = rigid_xform_xyz_px.tolist()
        self._save_to_json(attributes, zattrs_path)
    except (FileNotFoundError, json.JSONDecodeError):
        print("Error writing rigid transform attribute.")
        return None

save_local_round_linker(round_linker, tile, bit)

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

Parameters:

Name Type Description Default
round_linker int

Fidicual round linked to readout bit for one tile.

required
tile Union[int, str]

Tile index or tile id.

required
bit Union[int, str]

Bit index or bit id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_round_linker(
    self,
    round_linker: int,
    tile: Union[int, str],
    bit: Union[int, str],
):
    """Save fidicual round linker attribute to readout bit for one tile.

    Parameters
    ----------
    round_linker : int
        Fidicual round linked to readout bit for one tile.
    tile : Union[int, str]
        Tile index or tile id.
    bit : Union[int, 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:
        zattrs_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(bit_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        attributes["round"] = int(round_linker)
        self._save_to_json(attributes, zattrs_path)
    except (FileNotFoundError, json.JSONDecodeError):
        print(tile_id, bit_id)
        print("Error writing round linker attribute.")
        return None

save_local_stage_position_zyx_um(stage_zyx_um, tile, round)

Save tile stage position for one tile.

Parameters:

Name Type Description Default
stage_zyx_um ArrayLike

Tile stage position for one tile.

required
tile Union[int, str]

Tile index or tile id.

required
round Union[int, str]

Round index or round id.

required

Returns:

Name Type Description
stage_zyx_um Optional[ArrayLike]

Tile stage position for one tile.

Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_stage_position_zyx_um(
    self,
    stage_zyx_um: ArrayLike,
    tile: Union[int, str],
    round: Union[int, str],
):
    """Save tile stage position for one tile.

    Parameters
    ----------
    stage_zyx_um : ArrayLike
        Tile stage position for one tile.
    tile : Union[int, str]
        Tile index or tile id.
    round : Union[int, str]
        Round index or round id.

    Returns
    -------
    stage_zyx_um : Optional[ArrayLike]
        Tile stage position 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:
            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:
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(round_id + ".zarr")
            / Path(".zattrs")
        )
        attributes = self._load_from_json(zattrs_path)
        attributes["stage_zyx_um"] = stage_zyx_um.tolist()
        self._save_to_json(attributes, zattrs_path)
    except (FileNotFoundError, json.JSONDecodeError):
        print(tile_id, round_id)
        print("Error writing stage position attribute.")
        return None

save_local_ufish_image(ufish_image, tile, bit, return_future=False)

Save U-FISH prediction image.

Parameters:

Name Type Description Default
ufish_image ArrayLike

U-FISH prediction image.

required
tile Union[int, str]

Tile index or tile id.

required
bit Union[int, str]

Bit index or bit id.

required
return_future Optional[bool]

Return future array.

False
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_ufish_image(
    self,
    ufish_image: ArrayLike,
    tile: Union[int, str],
    bit: Union[int, str],
    return_future: Optional[bool] = False,
):
    """Save U-FISH prediction image.

    Parameters
    ----------
    ufish_image : ArrayLike
        U-FISH prediction image.
    tile : Union[int, str]
        Tile index or tile id.
    bit : Union[int, str]
        Bit index or bit id.
    return_future : Optional[bool]
        Return future array.
    """

    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 + ".zarr")
            / Path("registered_ufish_data")
        )

    try:
        self._save_to_zarr_array(
            ufish_image,
            self._get_kvstore_key(current_local_zarr_path),
            self._zarrv2_spec.copy(),
            return_future,
        )
    except (IOError, OSError, ZarrError) as e:
        print(e)
        print("Error saving U-Fish image.")
        return None

save_local_ufish_spots(spot_df, tile, bit)

Save U-FISH localizations and features.

Parameters:

Name Type Description Default
spot_df DataFrame

U-FISH localizations and features.

required
tile Union[int, str]

Tile index or tile id.

required
bit Union[int, str]

Bit index or bit id.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_local_ufish_spots(
    self,
    spot_df: pd.DataFrame,
    tile: Union[int, str],
    bit: Union[int, str],
):
    """Save U-FISH localizations and features.

    Parameters
    ----------
    spot_df : pd.DataFrame
        U-FISH localizations and features.
    tile : Union[int, str]
        Tile index or tile id.
    bit : Union[int, 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

    if not (self._ufish_localizations_root_path / Path(tile_id)).exists():
        (self._ufish_localizations_root_path / Path(tile_id)).mkdir()

    current_ufish_localizations_path = (
        self._ufish_localizations_root_path
        / Path(tile_id)
        / Path(bit_id + ".parquet")
    )

    try:
        self._save_to_parquet(spot_df, current_ufish_localizations_path)
    except (IOError, OSError) as e:
        print(e)
        print("Error saving U-FISH localizations.")
        return None

save_local_wavelengths_um(wavelengths_um, tile, round=None, bit=None)

Save wavelengths for fidicual OR readout bit for one tile.

Parameters:

Name Type Description Default
wavelengths_um tuple[float, float]

Wavelengths for fidicual OR readout bit for one tile.

required
tile Union[int, str]

Tile index or tile id.

required
round Optional[Union[int, str]]

Round index or round id.

None
bit Optional[Union[int, str]]

Bit index or bit id.

None

Returns:

Name Type Description
wavelengths_um Optional[tuple[float, float]]

Wavelengths for fidicual 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: Union[int, str],
    round: Optional[Union[int, str]] = None,
    bit: Optional[Union[int, str]] = None,
) -> Optional[tuple[float, float]]:
    """Save wavelengths for fidicual OR readout bit for one tile.

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

    Returns
    -------
    wavelengths_um : Optional[tuple[float, float]]
        Wavelengths for fidicual 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
        zattrs_path = str(
            self._readouts_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )
    else:
        if isinstance(round, int):
            if round < 0:
                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
        zattrs_path = str(
            self._polyDT_root_path
            / Path(tile_id)
            / Path(local_id + ".zarr")
            / Path(".zattrs")
        )

    try:
        attributes = self._load_from_json(zattrs_path)
        attributes["excitation_um"] = float(wavelengths_um[0])
        attributes["emission_um"] = float(wavelengths_um[1])
        self._save_to_json(attributes, zattrs_path)
    except (FileNotFoundError, json.JSONDecodeError):
        print("Error writing wavelength attributes.")
        return None

save_mtx(spots_source='')

Save mtx file for downstream analysis. Assumes Baysor has been run.

Parameters:

Name Type Description Default
spots_source str

source of spots. "baysor" or "resegmented".

''
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_mtx(self, spots_source: str = ""):
    """Save mtx file for downstream analysis. Assumes Baysor has been run.

    Parameters
    ----------
    spots_source: str, default "baysor"
        source of spots. "baysor" or "resegmented".
    """

    from merfish3danalysis.utils.dataio import create_mtx

    if spots_source == "baysor":
        spots_path = self._datastore_path / Path("segmentation") / Path("baysor") / Path("segmentation.csv")
    elif spots_source == "resegmented":
        spots_path = (
            self._datastore_path 
            / Path("all_tiles_filtered_decoded_features")
            / Path("refined_transcripts.parquet")
        )

    mtx_output_path = self._datastore_path / Path("mtx_output")

    create_mtx(
        spots_path=spots_path,
        output_dir_path=mtx_output_path,
    )

save_spots_prepped_for_baysor(prepped_for_baysor_df)

Save spots prepped for Baysor.

Parameters:

Name Type Description Default
prepped_for_baysor_df DataFrame

Spots prepped for Baysor.

required
Source code in src/merfish3danalysis/qi2labDataStore.py
def save_spots_prepped_for_baysor(self, prepped_for_baysor_df: pd.DataFrame):
    """Save spots prepped for Baysor.

    Parameters
    ----------
    prepped_for_baysor_df : pd.DataFrame
        Spots prepped for Baysor.
    """

    current_global_filtered_decoded_dir_path = self._datastore_path / Path(
        "all_tiles_filtered_decoded_features"
    )

    if not current_global_filtered_decoded_dir_path.exists():
        current_global_filtered_decoded_dir_path.mkdir()

    current_global_filtered_decoded_path = (
        current_global_filtered_decoded_dir_path / Path("transcripts.parquet")
    )

    self._save_to_parquet(prepped_for_baysor_df, current_global_filtered_decoded_path)