Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-15-intel, windows-latest, macos-14]
os: [ubuntu-latest, macos-15-intel, windows-latest, macos-15]
steps:
- name: Checkout 🛎️
uses: actions/checkout@v3
Expand Down
12 changes: 11 additions & 1 deletion src/bfio/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,17 @@ def __init__(self, parent, index):
self._tiff_frame = tifffile.TiffFrame(parent, index)

def get_offset(self):
return self._tiff_frame._nextifd()
# tifffile removed the private TiffFrame._nextifd(); reimplement it
# using only the public TiffFile/TiffFormat attributes.
f = self._tiff_frame
fh, tiff = f.parent.filehandle, f.parent.tiff
fh.seek(f.offset)
tagno = struct.unpack(tiff.tagnoformat, fh.read(tiff.tagnosize))[0]
if tiff.is_ndpi:
fh.seek(f.offset + tiff.tagnosize + tagno * 16 + 8)
else:
fh.seek(f.offset + tiff.tagnosize + tagno * tiff.tagsize)
return int(struct.unpack(tiff.offsetformat, fh.read(tiff.offsetsize))[0])

def get_index(self):
return self._tiff_frame.index
Expand Down
41 changes: 41 additions & 0 deletions tests/_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Download helpers for test data, with retries and zip unpacking."""

import pathlib
import time
import urllib.request
import zipfile

# Pinned to a commit of sameeul/polus-test-data so the data cannot change.
DATA_REPO = (
"https://raw.githubusercontent.com/sameeul/polus-test-data/"
"c5630e67ba6394b9abf73dbb85ac1fdce4b50528/bfio"
)
# zarr v2 (NGFF 0.4), 2 levels: (Y,X,Z,C) = (300,302,1,4) and (150,151,1,4)
PYRAMID_ZARR = "small_5d_pyramid.zarr"
# zarr v3 (NGFF 0.5), same shapes
V3_ZARR = "small_5d_v3.ome.zarr"
ZARR_URLS = {n: f"{DATA_REPO}/{n}.zip" for n in (PYRAMID_ZARR, V3_ZARR)}


def fetch(url, dest, tries=4, timeout=60):
"""Download url to dest, retrying with backoff; raises on final failure."""
dest = pathlib.Path(dest)
for i in range(tries):
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
data = r.read()
dest.write_bytes(data)
return dest
except Exception:
if i == tries - 1:
raise
time.sleep(2**i)


def fetch_zarr(name, test_dir):
"""Download the zipped zarr `name` and unpack it into test_dir."""
test_dir = pathlib.Path(test_dir)
z = fetch(ZARR_URLS[name], test_dir / f"{name}.zip")
with zipfile.ZipFile(z) as zf:
zf.extractall(test_dir)
z.unlink()
64 changes: 27 additions & 37 deletions tests/test_read.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
# -*- coding: utf-8 -*-
import unittest
import requests, pathlib, shutil, logging, sys
import pathlib, shutil, logging, sys
import bfio
import numpy as np
import pickle
import random
import tifffile
from PIL import Image
import zarr
from ome_zarr.utils import download as zarr_download

try:
from ._data import PYRAMID_ZARR, V3_ZARR, fetch, fetch_zarr
except ImportError: # run via `unittest discover -s tests`
from _data import PYRAMID_ZARR, V3_ZARR, fetch, fetch_zarr

TEST_IMAGES = {
"ExpD_chicken_embryo_MIP.ome.zarr": "https://uk1s3.embassy.ebi.ac.uk/idr/zarr/v0.5/idr0066/ExpD_chicken_embryo_MIP.ome.zarr",
"5025551.zarr": "https://uk1s3.embassy.ebi.ac.uk/idr/zarr/v0.4/idr0054A/5025551.zarr",
"Plate1-Blue-A-12-Scene-3-P3-F2-03.czi": "https://downloads.openmicroscopy.org/images/Zeiss-CZI/idr0011/Plate1-Blue-A_TS-Stinger/Plate1-Blue-A-12-Scene-3-P3-F2-03.czi",
"0.tif": "https://osf.io/j6aer/download",
"img_r001_c001.ome.tif": "https://github.com/usnistgov/WIPP/raw/master/data/PyramidBuilding/inputCollection/img_r001_c001.ome.tif",
Expand All @@ -35,21 +37,13 @@ def setUpModule():
"""Download images for testing"""
TEST_DIR.mkdir(exist_ok=True)

fetch_zarr(PYRAMID_ZARR, TEST_DIR)
fetch_zarr(V3_ZARR, TEST_DIR)

for file, url in TEST_IMAGES.items():
logger.info(f"setup - Downloading: {file}")

if not file.endswith(".zarr"):
if TEST_DIR.joinpath(file).exists():
continue

r = requests.get(url)

with open(TEST_DIR.joinpath(file), "wb") as fw:
fw.write(r.content)
else:
if TEST_DIR.joinpath(file).exists():
shutil.rmtree(TEST_DIR.joinpath(file))
zarr_download(url, str(TEST_DIR))
if not TEST_DIR.joinpath(file).exists():
fetch(url, TEST_DIR.joinpath(file))

"""Load the czi image, and save as a npy file for further testing."""
with bfio.BioReader(
Expand Down Expand Up @@ -334,23 +328,21 @@ def test_get_channel_names(self):

def test_sub_resolution_read(self):
"""Testing multi-resolution read"""
with bfio.BioReader(TEST_DIR.joinpath("5025551.zarr")) as br:
with bfio.BioReader(TEST_DIR.joinpath(PYRAMID_ZARR)) as br:
get_dims(br)
self.assertEqual(br.shape, (2700, 2702, 1, 27))
with bfio.BioReader(TEST_DIR.joinpath("5025551.zarr"), level=1) as br:
self.assertEqual(br.shape, (300, 302, 1, 4))
with bfio.BioReader(TEST_DIR.joinpath(PYRAMID_ZARR), level=1) as br:
get_dims(br)
self.assertEqual(br.shape, (1350, 1351, 1, 27))
self.assertEqual(br.shape, (150, 151, 1, 4))

def test_read_zarr_v3(self):
"""Testing zarr v3 format (NGFF 0.5) read with zarr backend"""
with bfio.BioReader(
TEST_DIR.joinpath("ExpD_chicken_embryo_MIP.ome.zarr"), backend="zarr3"
) as br:
with bfio.BioReader(TEST_DIR.joinpath(V3_ZARR), backend="zarr3") as br:
get_dims(br)
# Verify it's using the zarr backend
self.assertEqual(br._backend_name, "zarr3")
# Verify dimensions are read correctly
self.assertEqual(br.shape, (8978, 6510))
self.assertEqual(br.shape, (300, 302, 1, 4))
# Verify we can actually read data
data = br[:100, :100, 0, 0]
self.assertEqual(data.shape, (100, 100))
Expand Down Expand Up @@ -391,26 +383,24 @@ def test_get_channel_names(self):
def test_sub_resolution_read(self):
"""Testing multi-resolution read"""
with bfio.BioReader(
TEST_DIR.joinpath("5025551.zarr"), backend="tensorstore"
TEST_DIR.joinpath(PYRAMID_ZARR), backend="tensorstore"
) as br:
get_dims(br)
self.assertEqual(br.shape, (2700, 2702, 1, 27))
self.assertEqual(br.shape, (300, 302, 1, 4))
with bfio.BioReader(
TEST_DIR.joinpath("5025551.zarr"), backend="tensorstore", level=1
TEST_DIR.joinpath(PYRAMID_ZARR), backend="tensorstore", level=1
) as br:
get_dims(br)
self.assertEqual(br.shape, (1350, 1351, 1, 27))
self.assertEqual(br.shape, (150, 151, 1, 4))

def test_read_zarr_v3(self):
"""Testing zarr v3 format (NGFF 0.5) read with tensorstore backend"""
with bfio.BioReader(
TEST_DIR.joinpath("ExpD_chicken_embryo_MIP.ome.zarr"), backend="tensorstore"
) as br:
with bfio.BioReader(TEST_DIR.joinpath(V3_ZARR), backend="tensorstore") as br:
get_dims(br)
# Verify it's using the tensorstore backend
self.assertEqual(br._backend_name, "tensorstore")
# Verify dimensions are read correctly
self.assertEqual(br.shape, (8978, 6510))
self.assertEqual(br.shape, (300, 302, 1, 4))
# Verify we can actually read data
data = br[:100, :100, 0, 0]
self.assertEqual(data.shape, (100, 100))
Expand All @@ -421,22 +411,22 @@ def test_read_zarr_v3_multi_resolution(self):
"""Testing zarr v3 multi-resolution read with tensorstore backend"""
# Test resolution level 0 (highest resolution)
with bfio.BioReader(
TEST_DIR.joinpath("ExpD_chicken_embryo_MIP.ome.zarr"),
TEST_DIR.joinpath(V3_ZARR),
backend="tensorstore",
level=0,
) as br:
self.assertEqual(br._backend_name, "tensorstore")
self.assertEqual(br.shape, (8978, 6510))
self.assertEqual(br.shape, (300, 302, 1, 4))

# Test resolution level 1
with bfio.BioReader(
TEST_DIR.joinpath("ExpD_chicken_embryo_MIP.ome.zarr"),
TEST_DIR.joinpath(V3_ZARR),
backend="tensorstore",
level=1,
) as br:
self.assertEqual(br._backend_name, "tensorstore")
# Level 1 should be downsampled by 2x
self.assertEqual(br.shape, (4489, 3255))
self.assertEqual(br.shape, (150, 151, 1, 4))


class TestZarrMetadata(unittest.TestCase):
Expand Down
36 changes: 15 additions & 21 deletions tests/test_write.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# -*- coding: utf-8 -*-
import unittest
import requests, pathlib, shutil, logging, sys, os
import pathlib, shutil, logging, sys, os
import bfio
import numpy as np
import tempfile
from ome_zarr.utils import download as zarr_download

try:
from ._data import PYRAMID_ZARR, V3_ZARR, fetch, fetch_zarr
except ImportError: # run via `unittest discover -s tests`
from _data import PYRAMID_ZARR, V3_ZARR, fetch, fetch_zarr

TEST_IMAGES = {
"Plate1-Blue-A-12-Scene-3-P3-F2-03.czi": "https://downloads.openmicroscopy.org/images/Zeiss-CZI/idr0011/Plate1-Blue-A_TS-Stinger/Plate1-Blue-A-12-Scene-3-P3-F2-03.czi",
"5025551.zarr": "https://uk1s3.embassy.ebi.ac.uk/idr/zarr/v0.4/idr0054A/5025551.zarr",
"0.tif": "https://osf.io/j6aer/download",
}

Expand All @@ -28,21 +31,12 @@ def setUpModule():
"""Download images for testing"""
TEST_DIR.mkdir(exist_ok=True)

fetch_zarr(PYRAMID_ZARR, TEST_DIR)

for file, url in TEST_IMAGES.items():
logger.info(f"setup - Downloading: {file}")

if not file.endswith(".zarr"):
if TEST_DIR.joinpath(file).exists():
continue

r = requests.get(url)

with open(TEST_DIR.joinpath(file), "wb") as fw:
fw.write(r.content)
else:
if TEST_DIR.joinpath(file).exists():
shutil.rmtree(TEST_DIR.joinpath(file))
zarr_download(url, str(TEST_DIR))
if not TEST_DIR.joinpath(file).exists():
fetch(url, TEST_DIR.joinpath(file))


def tearDownModule():
Expand Down Expand Up @@ -109,7 +103,7 @@ class TestPythonZarrWriter(unittest.TestCase):

def test_write_zarr_append_no_file(self):

with bfio.BioReader(str(TEST_DIR.joinpath("5025551.zarr"))) as br:
with bfio.BioReader(str(TEST_DIR.joinpath(PYRAMID_ZARR))) as br:

actual_shape = br.shape
actual_dtype = br.dtype
Expand All @@ -136,7 +130,7 @@ def test_write_zarr_append_no_file(self):

def test_write_zarr_append_file_exist(self):

with bfio.BioReader(str(TEST_DIR.joinpath("5025551.zarr"))) as br:
with bfio.BioReader(str(TEST_DIR.joinpath(PYRAMID_ZARR))) as br:

actual_shape = br.shape
actual_dtype = br.dtype
Expand All @@ -151,14 +145,14 @@ def test_write_zarr_append_file_exist(self):
) as bw:

expanded = np.expand_dims(actual_image, axis=-1)
bw[:, :, :, 0:13, :] = expanded[:, :, :, 0:13, :]
bw[:, :, :, 0:2, :] = expanded[:, :, :, 0:2, :]

with bfio.BioWriter(
test_file_path, metadata=actual_mdata, backend="zarr", append=True
) as bw:

expanded = np.expand_dims(actual_image, axis=-1)
bw[:, :, :, 13:, :] = expanded[:, :, :, 13:, :]
bw[:, :, :, 2:, :] = expanded[:, :, :, 2:, :]
with bfio.BioReader(test_file_path) as br:

assert br.shape == actual_shape
Expand All @@ -171,7 +165,7 @@ class TestOmeZarrWriter(unittest.TestCase):

def test_write_zarr_tensorstore(self):

with bfio.BioReader(str(TEST_DIR.joinpath("5025551.zarr"))) as br:
with bfio.BioReader(str(TEST_DIR.joinpath(PYRAMID_ZARR))) as br:

actual_shape = br.shape
actual_dtype = br.dtype
Expand Down
Loading