Skip to content

Commit 887431b

Browse files
committed
smarter handling of suffixes in dummy nifti generation
1 parent 6811227 commit 887431b

File tree

1 file changed

+46
-7
lines changed

1 file changed

+46
-7
lines changed

medimages4tests/dummy/nifti.py

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import tempfile
23
from pathlib import Path
34
import gzip
@@ -11,16 +12,53 @@ def get_image(
1112
data: np.ndarray = None,
1213
vox_sizes=(1.0, 1.0, 1.0),
1314
qform=(1, 2, 3, 1),
14-
compressed=False,
15+
compressed=None,
1516
) -> Path:
16-
"""Create a random Nifti file to satisfy BIDS parsers"""
17+
"""Create a random Nifti file to satisfy BIDS parsers
18+
19+
Parameters
20+
----------
21+
out_file : Path
22+
23+
24+
"""
1725
if out_file is None:
1826
out_file = Path(tempfile.mkdtemp()) / "sample.nii"
27+
out_file = Path(out_file)
28+
29+
suffix = "".join(out_file.suffixes) if out_file.suffixes else ""
30+
out_stem = out_file.parent / out_file.name[:-len(suffix)]
31+
if not suffix:
32+
if compressed is None:
33+
raise RuntimeError(
34+
f"Must either specify the suffix of the 'out_file' ('{out_file}') or the "
35+
"compression type ('compressed' option)"
36+
)
37+
elif compressed:
38+
suffix = ".nii.gz"
39+
else:
40+
suffix = ".nii"
41+
elif compressed is None:
42+
compressed = suffix == ".nii.gz"
43+
elif suffix == ".nii":
44+
if compressed:
45+
raise RuntimeError(
46+
f"Suffix '{suffix}' doesn't match the compressed being True"
47+
)
48+
elif suffix == ".nii.gz":
49+
if not compressed:
50+
raise RuntimeError(
51+
f"Suffix '{suffix}' doesn't match the compressed being True"
52+
)
53+
else:
54+
raise RuntimeError(
55+
f"Unrecognised suffix for nifti file, '{suffix}'"
56+
)
1957

2058
if data is None:
2159
data = np.random.randint(0, 1, size=[10, 10, 10])
2260

23-
uncompressed = out_file.with_suffix('.nii')
61+
uncompressed = out_stem.with_suffix('.nii')
2462

2563
hdr = nb.Nifti1Header()
2664
hdr.set_data_shape(data.shape)
@@ -37,11 +75,12 @@ def get_image(
3775
)
3876

3977
if compressed:
40-
out_file = out_file.with_suffix('.nii.gz')
78+
out_path = out_stem.with_suffix('.nii.gz')
4179
with open(uncompressed, 'rb') as f_in:
42-
with gzip.open(out_file, 'wb') as f_out:
80+
with gzip.open(out_path, 'wb') as f_out:
4381
shutil.copyfileobj(f_in, f_out)
82+
os.unlink(uncompressed)
4483
else:
45-
out_file = uncompressed
84+
out_path = uncompressed
4685

47-
return out_file
86+
return out_path

0 commit comments

Comments
 (0)