1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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
|
# -*- coding: utf-8 -*-
import os
from nibabel.streamlines.tests.test_tractogram import make_dummy_streamline
from nibabel.streamlines import LazyTractogram
import numpy as np
import pytest
try:
import dipy
dipy_available = True
except ImportError:
dipy_available = False
from trx.io import get_trx_tmp_dir
import trx.trx_file_memmap as tmm
from trx.fetcher import (get_testing_files_dict,
fetch_data, get_home)
tmp_dir = get_trx_tmp_dir()
@pytest.mark.parametrize(
"arr,expected,value_error",
[
(np.ones((5, 5, 5), dtype=np.int16), None, True),
(np.ones((5, 4), dtype=np.int16), "mean_fa.4.int16", False),
(np.ones((5, 4), dtype=np.float64), "mean_fa.4.float64", False),
(np.ones((5, 1), dtype=np.float64), "mean_fa.float64", False),
(np.ones((1), dtype=np.float64), "mean_fa.float64", False),
],
)
def test__generate_filename_from_data(
arr, expected, value_error, filename="mean_fa.bit"
):
if value_error:
with pytest.raises(ValueError):
new_fn = tmm._generate_filename_from_data(arr=arr,
filename=filename)
assert new_fn is None
else:
new_fn = tmm._generate_filename_from_data(arr=arr, filename=filename)
assert new_fn == expected
@pytest.mark.parametrize(
"filename,expected,value_error",
[
("mean_fa.float64", ("mean_fa", 1, ".float64"), False),
("mean_fa.5.int32", ("mean_fa", 5, ".int32"), False),
("mean_fa", None, True),
("mean_fa.5.4.int32", None, True),
pytest.param(
"mean_fa.fa", None, True, marks=pytest.mark.xfail,
id="invalid extension"
),
],
)
def test__split_ext_with_dimensionality(filename, expected, value_error):
if value_error:
with pytest.raises(ValueError):
assert tmm._split_ext_with_dimensionality(filename) == expected
else:
assert tmm._split_ext_with_dimensionality(filename) == expected
@pytest.mark.parametrize(
"offsets,nb_vertices,expected",
[
(np.array(range(5), dtype=np.int16), 4, np.array([1, 1, 1, 1, 0])),
(np.array([0, 1, 1, 3, 4], dtype=np.int32),
4, np.array([1, 0, 2, 1, 0])),
(np.array(range(4), dtype=np.uint64), 4, np.array([1, 1, 1, 1])),
pytest.param(np.array([0, 1, 0, 3, 4], dtype=np.int16), 4,
np.array([1, 3, 0, 1, 0]), marks=pytest.mark.xfail,
id="offsets not sorted"),
],
)
def test__compute_lengths(offsets, nb_vertices, expected):
offsets = tmm._append_last_offsets(offsets, nb_vertices)
lengths = tmm._compute_lengths(offsets=offsets)
assert np.array_equal(lengths, expected)
@pytest.mark.parametrize(
"ext,expected",
[
(".bit", True),
(".int16", True),
(".float32", True),
(".ushort", True),
(".txt", False),
],
)
def test__is_dtype_valid(ext, expected):
assert tmm._is_dtype_valid(ext) == expected
@pytest.mark.parametrize(
"arr,l_bound,r_bound,expected",
[
(np.array(range(5), dtype=np.int16), None, None, 4),
(np.array([0, 1, 0, 3, 4], dtype=np.int16), None, None, 1),
(np.array([0, 1, 2, 0, 4], dtype=np.int16), None, None, 2),
(np.array(range(5), dtype=np.int16), 1, 2, 2),
(np.array(range(5), dtype=np.int16), 3, 3, 3),
(np.zeros((5), dtype=np.int16), 3, 3, -1),
],
)
def test__dichotomic_search(arr, l_bound, r_bound, expected):
end_idx = tmm._dichotomic_search(arr, l_bound=l_bound, r_bound=r_bound)
assert end_idx == expected
@pytest.mark.parametrize(
"basename, create, expected",
[
("offsets.int16", True, np.array(range(12), dtype=np.int16).reshape((
3, 4))),
("offsets.float32", False, None),
],
)
def test__create_memmap(basename, create, expected):
if create:
# Need to create array before evaluating
with get_trx_tmp_dir() as dirname:
filename = os.path.join(dirname, basename)
fp = np.memmap(filename, dtype=np.int16, mode="w+", shape=(3, 4))
fp[:] = expected[:]
mmarr = tmm._create_memmap(filename=filename, shape=(3, 4),
dtype=np.int16)
assert np.array_equal(mmarr, expected)
else:
with get_trx_tmp_dir() as dirname:
filename = os.path.join(dirname, basename)
mmarr = tmm._create_memmap(filename=filename, shape=(0,),
dtype=np.int16)
assert os.path.isfile(filename)
assert np.array_equal(mmarr, np.zeros(
shape=(0,), dtype=np.float32))
# need dpg test with missing keys
@pytest.mark.parametrize(
"path,check_dpg,value_error",
[
("small_compressed.trx", False, False),
("small.trx", True, False),
("small_fldr.trx", False, False),
("dontexist.trx", False, True),
],
)
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_load(path, check_dpg, value_error):
path = os.path.join(get_home(), 'memmap_test_data', path)
# Need to perhaps improve test
if value_error:
with pytest.raises(ValueError):
assert not isinstance(
tmm.load(input_obj=path, check_dpg=check_dpg), tmm.TrxFile
)
else:
assert isinstance(tmm.load(input_obj=path, check_dpg=check_dpg),
tmm.TrxFile)
@pytest.mark.parametrize("path", [("small.trx")])
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_load_zip(path):
path = os.path.join(get_home(), 'memmap_test_data', path)
assert isinstance(tmm.load_from_zip(path), tmm.TrxFile)
@pytest.mark.parametrize("path", [("small_fldr.trx")])
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_load_directory(path):
path = os.path.join(get_home(), 'memmap_test_data', path)
assert isinstance(tmm.load_from_directory(path), tmm.TrxFile)
@pytest.mark.parametrize("path", [("small.trx")])
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_concatenate(path):
path = os.path.join(get_home(), 'memmap_test_data', path)
trx1 = tmm.load(path)
trx2 = tmm.load(path)
concat = tmm.concatenate([trx1, trx2])
assert len(concat) == 2 * len(trx2)
trx1.close()
trx2.close()
concat.close()
@pytest.mark.parametrize("path", [("small.trx")])
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_resize(path):
path = os.path.join(get_home(), 'memmap_test_data', path)
trx1 = tmm.load(path)
concat = tmm.TrxFile(nb_vertices=1000000, nb_streamlines=10000,
init_as=trx1)
tmm.concatenate([concat, trx1], preallocation=True, delete_groups=True)
concat.resize()
assert len(concat) == len(trx1)
trx1.close()
concat.close()
@pytest.mark.parametrize(
"path, buffer",
[
("small.trx", 10000),
("small.trx", 0)
]
)
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_append(path, buffer):
path = os.path.join(get_home(), 'memmap_test_data', path)
trx1 = tmm.load(path)
concat = tmm.TrxFile(nb_vertices=1, nb_streamlines=1,
init_as=trx1)
concat.append(trx1, extra_buffer=buffer)
if buffer > 0:
concat.resize()
assert len(concat) == len(trx1)
trx1.close()
concat.close()
@pytest.mark.parametrize("path, buffer", [("small.trx", 10000)])
@pytest.mark.skipif(not dipy_available, reason="Dipy is not installed")
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_append_StatefulTractogram(path, buffer):
path = os.path.join(get_home(), 'memmap_test_data', path)
trx = tmm.load(path)
obj = trx.to_sft()
concat = tmm.TrxFile(nb_vertices=1, nb_streamlines=1, init_as=trx)
concat.append(obj, extra_buffer=buffer)
if buffer > 0:
concat.resize()
assert len(concat) == len(obj)
trx.close()
concat.close()
@pytest.mark.parametrize("path, buffer", [("small.trx", 10000)])
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_append_Tractogram(path, buffer):
path = os.path.join(get_home(), 'memmap_test_data', path)
trx = tmm.load(path)
obj = trx.to_tractogram()
concat = tmm.TrxFile(nb_vertices=1, nb_streamlines=1, init_as=trx)
concat.append(obj, extra_buffer=buffer)
if buffer > 0:
concat.resize()
assert len(concat) == len(obj)
trx.close()
concat.close()
@pytest.mark.parametrize("path, size, buffer", [("small.trx", 50, 10000),
("small.trx", 0, 10000),
("small.trx", 25000, 10000),
("small.trx", 50, 0),
("small.trx", 0, 0),
("small.trx", 25000, 10000)])
@pytest.mark.skip(reason='requires memmap_test_data which needs internet')
def test_from_lazy_tractogram(path, size, buffer):
_ = np.random.RandomState(1776)
streamlines = []
fa = []
commit_weights = []
clusters_QB = []
gen_range = [1, 2, 5, 2, 1] * (size // 5)
for i in gen_range:
data = make_dummy_streamline(i)
streamline, data_per_point, data_for_streamline = data
streamlines.append(streamline)
fa.append(data_per_point['fa'].astype(np.float16))
commit_weights.append(
data_for_streamline['mean_curvature'].astype(np.float32))
clusters_QB.append(
data_for_streamline['mean_torsion'].astype(np.uint16))
def streamlines_func(): return (e for e in streamlines)
data_per_point_func = {'fa': lambda: (e for e in fa)}
data_per_streamline_func = {
'commit_weights': lambda: (e for e in commit_weights),
'clusters_QB': lambda: (e for e in clusters_QB)}
obj = LazyTractogram(streamlines_func,
data_per_streamline_func,
data_per_point_func,
affine_to_rasmm=np.eye(4))
dtype_dict = {'positions': np.float32, 'offsets': np.uint32,
'dpv': {'fa': np.float16},
'dps': {'commit_weights': np.float32,
'clusters_QB': np.uint16}}
path = os.path.join(get_home(), 'memmap_test_data', path)
trx = tmm.TrxFile.from_lazy_tractogram(obj, reference=path,
extra_buffer=buffer,
chunk_size=1000,
dtype_dict=dtype_dict)
assert len(trx) == len(gen_range)
def test_zip_from_folder():
pass
def test_trxfile_init():
pass
def test_trxfile_print():
pass
def test_trxfile_len():
fake = tmm.TrxFile(nb_vertices=100, nb_streamlines=10)
assert len(fake) == 10
def test_trxfile_getitem():
pass
def test_trxfile_deepcopy():
pass
def test_get_real_len():
fake = tmm.TrxFile(nb_vertices=100, nb_streamlines=10)
assert fake._get_real_len() == (0, 0)
def test_copy_fixed_arrays_from():
pass
def test_initialize_empty_trx():
pass
def test_create_trx_from_pointer():
pass
def test_trxfile_getgroup():
pass
def test_trxfile_select():
pass
def test_trxfile_to_memory():
pass
def test_trxfile_close():
pass
|