Skip to content

Commit ad14300

Browse files
grg2rsrk1o0
andauthored
Redownload volumes (#28)
* bugfix for #27 * enhanced specificity, only removing corrupted file and not everything. locally tested. * Added test --------- Co-authored-by: Miles Wells <k1o0@3tk.co>
1 parent e18db77 commit ad14300

File tree

4 files changed

+58
-4
lines changed

4 files changed

+58
-4
lines changed

iblatlas/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__version__ = '0.9.0'
1+
__version__ = '0.10.0'
22

33
"""A package for working with brain atlases.
44

iblatlas/atlas.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1455,9 +1455,16 @@ def __init__(self, res_um=25, scaling=(1, 1, 1), mock=False, hist_path=None):
14551455
super().__init__(image, label, dxyz, regions, ibregma, dims2xyz=dims2xyz, xyz2dims=xyz2dims)
14561456

14571457
@staticmethod
1458-
def _read_volume(file_volume):
1458+
def _read_volume(file_volume: Path):
14591459
if file_volume.suffix == '.nrrd':
1460-
volume, _ = nrrd.read(file_volume, index_order='C') # ml, dv, ap
1460+
try:
1461+
volume, _ = nrrd.read(file_volume, index_order='C') # ml, dv, ap
1462+
except nrrd.NRRDError as e:
1463+
_logger.error(f"An error occured when loading atlas volumes: {e}. \
1464+
Deleting and redownloading the files.")
1465+
file_volume.unlink(missing_ok=True)
1466+
file_volume = _download_atlas_allen(file_volume)
1467+
volume, _ = nrrd.read(file_volume, index_order='C') # ml, dv, ap
14611468
# we want the coronal slice to be the most contiguous
14621469
volume = np.transpose(volume, (2, 0, 1)) # image[iap, iml, idv]
14631470
elif file_volume.suffix == '.npz':

iblatlas/tests/__init__.py

Whitespace-only changes.

iblatlas/tests/test_allen_atlas.py

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1+
import tempfile
2+
from pathlib import Path
3+
import unittest
4+
from unittest import mock
5+
from textwrap import dedent
6+
17
import numpy as np
28
import matplotlib.pyplot as plt
3-
import unittest
9+
410
from iblatlas.atlas import AllenAtlas, BrainRegions
511
from iblatlas.flatmaps import FlatMap
612
from iblatlas.plots import plot_swanson, annotate_swanson
@@ -118,3 +124,44 @@ def test_load(self):
118124
df_genes, gene_expression, atlas_agea = agea.load()
119125
self.assertEqual(df_genes.shape[0], gene_expression.shape[0])
120126
self.assertEqual(gene_expression.shape[1:], (58, 41, 67))
127+
128+
129+
class TestReadVolume(unittest.TestCase):
130+
131+
@mock.patch('iblatlas.atlas._download_atlas_allen')
132+
def test_read_volume(self, mock_download):
133+
"""Test that NRRD files are read corrrectly, and redownloaded when corrupted."""
134+
with tempfile.TemporaryDirectory() as tmpdir:
135+
tmpdir_path = Path(tmpdir)
136+
file_image = tmpdir_path / 'annotation_25.nrrd'
137+
# create dummy files
138+
file_image.write_bytes(b'\xFF') # invalid nrrd
139+
# mock the download to just write a dummy file
140+
mock_download.side_effect = self._side_effect
141+
with self.assertLogs('iblatlas.atlas', level='ERROR') as cm:
142+
volume = AllenAtlas._read_volume(file_image)
143+
self.assertIn('An error occured when loading atlas volumes', cm.output[0])
144+
# the mock should have been called twice, once for each file
145+
self.assertEqual(mock_download.call_count, 1)
146+
self.assertEqual(volume.shape, (3, 3, 3))
147+
148+
@staticmethod
149+
def _side_effect(file_path):
150+
"""Write a dummy file with correct header for nrrd."""
151+
s = dedent(
152+
"""\
153+
NRRD0003
154+
type: unsigned char
155+
dimension: 3
156+
sizes: 3 3 3
157+
spacings: 1.0458000000000001 1.0458000000000001 1.0458000000000001
158+
kinds: domain domain domain
159+
encoding: ASCII\n\n
160+
""")
161+
s += '\n'.join(map(str, list(range(3**3))))
162+
file_path.write_bytes(s.encode())
163+
return file_path
164+
165+
166+
if __name__ == "__main__":
167+
unittest.main(exit=False, verbosity=2)

0 commit comments

Comments
 (0)