File: util.py

package info (click to toggle)
python-dtcwt 0.12.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 8,404 kB
  • sloc: python: 6,253; sh: 29; makefile: 13
file content (71 lines) | stat: -rw-r--r-- 2,393 bytes parent folder | download | duplicates (3)
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
import functools
import numpy as np
import pytest

from dtcwt.opencl.lowlevel import _HAVE_CL as HAVE_CL
#  from dtcwt.utils import _HAVE_TF as HAVE_TF
from dtcwt.tf.lowlevel import _HAVE_TF as HAVE_TF

from six.moves import xrange

TOLERANCE = 1e-6

def assert_almost_equal(a, b, tolerance=TOLERANCE):
    md = np.abs(a-b).max()
    if md <= tolerance:
        return

    raise AssertionError(
            'Arrays differ by a maximum of {0} which is greater than the tolerance of {1}'.
            format(md, tolerance))

def assert_percentile_almost_equal(a, b, percentile=90, tolerance=TOLERANCE):
    md = np.percentile(np.abs(a-b), percentile)
    if md <= tolerance:
        return

    raise AssertionError(
            'Arrays differ by a maximum of {0} in the {2}th percentile which is greater than the tolerance of {1}'.
            format(md, tolerance, percentile))

def _mean(a, axis=None, *args, **kwargs):
    """Equivalent to numpy.mean except that the axis along which the mean is taken is not removed."""

    rv = np.mean(a, axis=axis, *args, **kwargs)

    if axis is not None:
        rv = np.expand_dims(rv, axis)

    return rv

def centre_indices(ndim=2,apron=8):
    """Returns the centre indices for the correct number of dimension
    """
    return tuple([slice(apron,-apron) for i in xrange(ndim)])

def summarise_mat(M, apron=8):
    """HACK to provide a 'summary' matrix consisting of the corners of the
    matrix and summed versions of the sub matrices.

    N.B. Keep this in sync with matlab/verif_m_to_npz.py.

    """
    centre = M[apron:-apron,apron:-apron,...]
    centre_sum = _mean(_mean(centre, axis=0), axis=1)

    return np.vstack((
        np.hstack((M[:apron,:apron,...], _mean(M[:apron,apron:-apron,...], axis=1), M[:apron,-apron:,...])),
        np.hstack((_mean(M[apron:-apron,:apron,...], axis=0), centre_sum, _mean(M[apron:-apron,-apron:,...], axis=0))),
        np.hstack((M[-apron:,:apron,...], _mean(M[-apron:,apron:-apron,...], axis=1), M[-apron:,-apron:,...])),
    ))

def summarise_cube(M, apron=4):
    """Provide a summary cube, extending  summarise_mat to 3D
    """
    return np.dstack(
        [summarise_mat(M[:,:,i,...], apron) for i in xrange(M.shape[-2])]
    )

skip_if_no_cl = pytest.mark.skipif(not HAVE_CL, reason="OpenCL not present")
skip_if_no_tf = pytest.mark.skipif(not HAVE_TF, reason="Tensorflow not present")