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
|
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2019-2022 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "Wout De Nolf"
__contact__ = "wout.de_nolf@esrf.eu"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import unittest
import tempfile
import shutil
import os
import sys
import numpy
import itertools
from contextlib import contextmanager
try:
from PyMca5.PyMcaCore import McaStackView
except ImportError:
McaStackView = None
try:
import h5py
except ImportError:
h5py = None
class testMcaStackView(unittest.TestCase):
def setUp(self):
self.path = tempfile.mkdtemp(prefix='pymca')
def tearDown(self):
shutil.rmtree(self.path)
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
def testViewUtils(self):
n = 20
slices = [slice(None), slice(1, -2),
slice(8, 2, -1), slice(0, n, 3),
slice(0, n, -2), slice(n-2, 2, -3),
slice(n-1, None, -1), slice(None, -2, 3)]
lst = list(range(n))
for idx in slices:
idxn = McaStackView.sliceNormalize(idx, n)
self.assertEqual(lst[idx], lst[idxn])
for idx in slices:
self.assertEqual(McaStackView.sliceLen(idx, n), len(lst[idx]))
for idx in slices:
idxi = McaStackView.sliceReverse(idx, n)
self.assertEqual(lst[idx][::-1], lst[idxi])
for idx in slices:
idxc = McaStackView.sliceComplement(idx, n)
self.assertEqual(list(sorted(lst[idx]+idxc)), lst)
for idx in slices:
start, stop, step = idx.indices(n)
lst1 = list(range(start, stop, int(numpy.sign(step))))
it = McaStackView.chunkIndexGen(start, stop, step)
self.assertEqual(len(lst1), sum(ns for it, ns in it))
it = McaStackView.chunkIndexGen(start, stop, step)
lst2 = [i for idxc, ns in it for i in lst[idxc]]
self.assertEqual(lst1, lst2)
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
def testfullChunkIndex(self):
for ndim in [2, 3, 4]:
shape = tuple(range(3, 3+ndim))
data = numpy.zeros(shape, dtype=int)
for chunkAxes, axesOrder, nChunksTot in self._chunkIndexAxes(shape, ndim):
for nChunksMax in range(nChunksTot+2):
data[()] = 0
result = McaStackView.fullChunkIndex(shape, nChunksMax,
chunkAxes=chunkAxes,
axesOrder=axesOrder)
chunkIndex, chunkAxes, axesOrder, nChunksMax2 = result
self.assertTrue(nChunksMax2 <= max(nChunksMax, 1))
for i, (idxChunk, idxShape, nChunks) in enumerate(chunkIndex, 1):
data[idxChunk] += i
self.assertEqual(data[idxChunk].shape, idxShape)
self.assertTrue(nChunks <= nChunksMax2)
# Verify data coverage:
self.assertFalse((data == 0).any())
# Verify single element access and chunk access order:
arr = data.transpose(axesOrder[::-1]+chunkAxes).flatten()
lst1 = [k for k, g in itertools.groupby(arr)]
lst2 = list(range(1, i+1))
self.assertEqual(lst1, lst2)
def _chunkIndexAxes(self, shape, ndim):
axes = set(range(ndim))
for ndimChunk in range(ndim+1):
nOther = ndim-ndimChunk
for chunkAxes in itertools.permutations(axes, ndimChunk):
nChunksTot = numpy.prod([shape[i] for i in axes])
yield chunkAxes, None, nChunksTot
other = axes-set(chunkAxes)
if other:
nChunksTot = numpy.prod([shape[i] for i in other])
else:
nChunksTot = 1
for axesOrder in itertools.permutations(other, nOther):
yield chunkAxes, axesOrder, nChunksTot
def assert_array_equal(self, *var):
if sys.maxsize > 2**32:
# 64-bit interpreter
return numpy.testing.assert_array_equal(*var)
else:
# 32-bit interpreter
return numpy.testing.assert_allclose(*var)
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
def testMaskedChunkIndex(self):
for ndim in [2, 3, 4]:
shape = tuple(range(3, 3+ndim))
data = numpy.zeros(shape, dtype=int)
for chunkAxes, axesOrder, nChunksTot in self._chunkIndexAxes(shape, ndim):
# Create Mask
mask, indices, nmask = self._randomMask(shape, chunkAxes, axesOrder)
# Mask entire array
maskFull = numpy.zeros(shape, dtype=bool)
if mask is None:
maskFull[()] = False
nmask = 0
else:
indicesFull = [slice(None)]*ndim
if axesOrder:
for i, ind in zip(axesOrder, indices):
indicesFull[i] = ind
elif chunkAxes:
tmp = tuple(i for i in range(ndim)
if i not in chunkAxes)
for i, ind in zip(tmp, indices):
indicesFull[i] = ind
else:
indicesFull = indices
indicesFull = tuple(indicesFull)
maskFull[indicesFull] = True
for nChunksMax in [2, nmask//3, nmask-1, nmask+1]:
for usedmask in [mask, None]:
data[()] = 0
self.assertFalse((data != 0).any())
chunkIndex, chunkAxes2, axesOrder, nChunksMax2 =\
McaStackView.maskedChunkIndex(shape, nChunksMax,
mask=usedmask,
chunkAxes=chunkAxes,
axesOrder=axesOrder)
for i, (idxChunk, idxShape, nChunks) in enumerate(chunkIndex, 1):
data[idxChunk] += i
self.assertEqual(data[idxChunk].shape, idxShape)
self.assertTrue(nChunks <= nChunksMax2)
# Verify data coverage:
if usedmask is None:
self.assertFalse((data == 0).any())
else:
self.assertFalse((data[maskFull] == 0).any())
self.assertTrue((data[~maskFull] == 0).all())
# Verify single element access:
lst1 = numpy.unique(data).tolist()
lst2 = list(range(int(usedmask is None), i+1))
self.assertEqual(lst1, lst2)
def _randomMask(self, shape, chunkAxes, axesOrder):
if axesOrder:
mshape = tuple(shape[i] for i in axesOrder)
elif chunkAxes:
mshape = tuple(shape[i] for i in range(len(shape))
if i not in chunkAxes)
else:
mshape = shape
if mshape:
mask = numpy.zeros(mshape, dtype=bool)
indices = numpy.arange(mask.size)
numpy.random.shuffle(indices)
indices = indices[:mask.size//2]
nmask = indices.size
indices = numpy.unravel_index(indices, mshape)
mask[indices] = True
else:
mask = None
indices = None
nmask = 0
return mask, indices, nmask
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
def testFullViewNumpy(self):
for ndim in [2, 3, 4]:
shape = range(6, 6+ndim)
data = numpy.random.uniform(size=shape)
self._assertFullView(data)
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
@unittest.skipIf(h5py is None,
'h5py cannot be imported')
def testFullViewH5py(self):
for ndim in [2, 3]:
shape = range(6, 6+ndim)
data = numpy.random.uniform(size=shape)
with self.h5Open('testFullView') as f:
name = 'data{}'.format(ndim)
f.create_dataset(name, data=data, chunks=(1,)*ndim)
self._assertFullView(f[name])
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
def testMaskedViewNumpy(self):
for ndim in [2, 3, 4]:
shape = range(6, 6+ndim)
data = numpy.random.uniform(size=shape)
self._assertMaskedView(data)
@unittest.skipIf(McaStackView is None,
'PyMca5.PyMcaCore.McaStackView cannot be imported')
@unittest.skipIf(h5py is None,
'h5py cannot be imported')
def testMaskedViewH5py(self):
for ndim in [2, 3]:
shape = range(6, 6+ndim)
data = numpy.random.uniform(size=shape)
with self.h5Open('testMaskedView') as f:
name = 'data{}'.format(ndim)
f.create_dataset(name, data=data, chunks=(1,)*ndim)
self._assertMaskedView(f[name])
def _assertFullView(self, data):
mcaSlice = slice(2, -1)
for nMca in range(numpy.prod(data.shape[1:])+2):
for mcaAxis in range(data.ndim):
dataView = McaStackView.FullView(data,
readonly=False,
mcaAxis=mcaAxis,
mcaSlice=mcaSlice,
nMca=nMca)
npAdd = numpy.arange(data.size).reshape(data.shape)
addView = McaStackView.FullView(npAdd,
readonly=True,
mcaAxis=mcaAxis,
mcaSlice=mcaSlice,
nMca=nMca)
idxFull = dataView.idxFull
for readonly in [True, False]:
dataView.readonly = readonly
dataOrg = numpy.copy(data)
iters = dataView.items(), addView.items()
chunks = McaStackView.izipChunkItems(*iters)
for (key, chunk), (addKey, add) in chunks:
chunk += add
for idxFullComplement in dataView.idxFullComplement:
numpy.testing.assert_allclose(data[idxFullComplement],
dataOrg[idxFullComplement])
if readonly:
numpy.testing.assert_allclose(data[idxFull],
dataOrg[idxFull])
else:
numpy.testing.assert_allclose(data[idxFull],
dataOrg[idxFull]+npAdd[idxFull])
def _assertMaskedView(self, data):
mcaSlice = slice(2, -1)
isH5py = isinstance(data, h5py.Dataset)
for mcaAxis in range(data.ndim):
mask, indices, nmask = self._randomMask(data.shape, (mcaAxis,), None)
it = itertools.product([2, nmask//3, nmask-1, nmask+1], [mask, None])
for nMca, usedmask in it:
dataView = McaStackView.MaskedView(data,
mask=usedmask,
readonly=False,
mcaAxis=mcaAxis,
mcaSlice=mcaSlice,
nMca=nMca)
npAdd = numpy.arange(data.size).reshape(data.shape)
addView = McaStackView.MaskedView(npAdd,
mask=usedmask,
readonly=True,
mcaAxis=mcaAxis,
mcaSlice=mcaSlice,
nMca=nMca)
idxFull = dataView.idxFull
for readonly in [True, False]:
dataView.readonly = readonly
dataOrg = numpy.copy(data)
iters = dataView.items(), addView.items()
chunks = McaStackView.izipChunkItems(*iters)
for (key, chunk), (addKey, add) in chunks:
chunk += add
if isH5py:
_data = data[()]
else:
_data = data
for idxFullComplement in dataView.idxFullComplement:
numpy.testing.assert_allclose(_data[idxFullComplement],
dataOrg[idxFullComplement])
if readonly:
numpy.testing.assert_allclose(_data[idxFull],
dataOrg[idxFull])
else:
numpy.testing.assert_allclose(_data[idxFull],
dataOrg[idxFull]+npAdd[idxFull])
@contextmanager
def h5Open(self, name):
filename = os.path.join(self.path, name+'.h5')
with h5py.File(filename, mode='a') as f:
yield f
def getSuite(auto=True):
testSuite = unittest.TestSuite()
if auto:
testSuite.addTest(
unittest.TestLoader().loadTestsFromTestCase(testMcaStackView))
else:
# use a predefined order
testSuite.addTest(testMcaStackView('testViewUtils'))
testSuite.addTest(testMcaStackView('testfullChunkIndex'))
testSuite.addTest(testMcaStackView('testFullViewNumpy'))
testSuite.addTest(testMcaStackView('testFullViewH5py'))
testSuite.addTest(testMcaStackView('testMaskedChunkIndex'))
testSuite.addTest(testMcaStackView('testMaskedViewNumpy'))
testSuite.addTest(testMcaStackView('testMaskedViewH5py'))
return testSuite
def test(auto=False):
unittest.TextTestRunner(verbosity=2).run(getSuite(auto=auto))
if __name__ == '__main__':
test()
|