test_interpolation.py 8.19 KB
Newer Older
1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
#
# Copyright © 2019 Stephan Seitz <stephan.seitz@fau.de>
#
# Distributed under terms of the GPLv3 license.

"""

"""
10
import itertools
11
12
13
from os.path import dirname, join

import numpy as np
14
import pytest
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
import sympy

import pystencils
from pystencils.interpolation_astnodes import LinearInterpolator
from pystencils.spatial_coordinates import x_, y_

type_map = {
    np.float32: 'float32',
    np.float64: 'float64',
    np.int32: 'int32',
}

try:
    import pyconrad.autoinit
except Exception:
    import unittest.mock
    pyconrad = unittest.mock.MagicMock()

LENNA_FILE = join(dirname(__file__), 'test_data', 'lenna.png')

try:
    import skimage.io
    lenna = skimage.io.imread(LENNA_FILE, as_gray=True).astype(np.float64)
    pyconrad.imshow(lenna)
except Exception:
    lenna = np.random.rand(20, 30)


def test_interpolation():
    x_f, y_f = pystencils.fields('x,y: float64 [2d]')

    assignments = pystencils.AssignmentCollection({
        y_f.center(): LinearInterpolator(x_f).at([x_ + 2.7, y_ + 7.2])
    })
    print(assignments)
    ast = pystencils.create_kernel(assignments)
    print(ast)
52
    print(pystencils.show_code(ast))
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    kernel = ast.compile()

    pyconrad.imshow(lenna)

    out = np.zeros_like(lenna)
    kernel(x=lenna, y=out)
    pyconrad.imshow(out, "out")


def test_scale_interpolation():
    x_f, y_f = pystencils.fields('x,y: float64 [2d]')

    for address_mode in ['border', 'wrap', 'clamp', 'mirror']:
        assignments = pystencils.AssignmentCollection({
            y_f.center(): LinearInterpolator(x_f, address_mode=address_mode).at([0.5 * x_ + 2.7, 0.25 * y_ + 7.2])
        })
        print(assignments)
        ast = pystencils.create_kernel(assignments)
        print(ast)
72
        print(pystencils.show_code(ast))
73
74
75
76
77
78
79
        kernel = ast.compile()

        out = np.zeros_like(lenna)
        kernel(x=lenna, y=out)
        pyconrad.imshow(out, "out " + address_mode)


80
81
82
83
@pytest.mark.parametrize('address_mode',
                         ['border',
                          'clamp',
                          pytest.param('warp', marks=pytest.mark.xfail(
84
                              reason="requires interpolation-refactoring branch")),
85
                          pytest.param('mirror', marks=pytest.mark.xfail(
86
                              reason="requires interpolation-refactoring branch")),
87
88
89
90
91
                          ])
def test_rotate_interpolation(address_mode):
    """
    'wrap', 'mirror' currently fails on new sympy due to conjugate()
    """
92
93
94
95
    x_f, y_f = pystencils.fields('x,y: float64 [2d]')

    rotation_angle = sympy.pi / 5

96
97
98
99
100
101
102
    transformed = sympy.rot_axis3(rotation_angle)[:2, :2] * sympy.Matrix((x_, y_))
    assignments = pystencils.AssignmentCollection({
        y_f.center(): LinearInterpolator(x_f, address_mode=address_mode).at(transformed)
    })
    print(assignments)
    ast = pystencils.create_kernel(assignments)
    print(ast)
103
    print(pystencils.show_code(ast))
104
    kernel = ast.compile()
105

106
107
108
    out = np.zeros_like(lenna)
    kernel(x=lenna, y=out)
    pyconrad.imshow(out, "out " + address_mode)
109
110


Stephan Seitz's avatar
Stephan Seitz committed
111
112
@pytest.mark.parametrize('dtype', (np.int32, np.float32, np.float64))
@pytest.mark.parametrize('address_mode', ('border', 'wrap', 'clamp', 'mirror'))
113
114
@pytest.mark.parametrize('use_textures', ('use_textures', False))
def test_rotate_interpolation_gpu(dtype, address_mode, use_textures):
115
    pytest.importorskip('pycuda')
116

117
118
    import pycuda.gpuarray as gpuarray
    import pycuda.autoinit  # noqa
119
120
121
    rotation_angle = sympy.pi / 5
    scale = 1

122
123
124
125
126
127
    if dtype == np.int32:
        lenna_gpu = gpuarray.to_gpu(
            np.ascontiguousarray(lenna * 255, dtype))
    else:
        lenna_gpu = gpuarray.to_gpu(
            np.ascontiguousarray(lenna, dtype))
128
    x_f, y_f = pystencils.fields(f'x,y: {type_map[dtype]} [2d]', ghost_layers=0)
129

130
131
132
133
134
135
136
137
138
139
    transformed = scale * \
        sympy.rot_axis3(rotation_angle)[:2, :2] * sympy.Matrix((x_, y_)) - sympy.Matrix([2, 2])
    assignments = pystencils.AssignmentCollection({
        y_f.center(): LinearInterpolator(x_f, address_mode=address_mode).at(transformed)
    })
    print(assignments)
    ast = pystencils.create_kernel(assignments, target='gpu', use_textures_for_interpolation=use_textures)
    print(ast)
    print(pystencils.show_code(ast))
    kernel = ast.compile()
140

141
142
143
144
    out = gpuarray.zeros_like(lenna_gpu)
    kernel(x=lenna_gpu, y=out)
    pyconrad.imshow(out,
                    f"out {address_mode} texture:{use_textures} {type_map[dtype]}")
145
146


147
148
149
150
151
152
@pytest.mark.parametrize('address_mode', ['border', 'wrap',
                                          pytest.param('warp', marks=pytest.mark.xfail(
                                              reason="% printed as fmod on old sympy")),
                                          pytest.param('mirror', marks=pytest.mark.xfail(
                                              reason="% printed as fmod on old sympy")),
                                          ])
153
154
155
@pytest.mark.parametrize('dtype', [np.float64, np.float32, np.int32])
@pytest.mark.parametrize('use_textures', ('use_textures', False,))
def test_shift_interpolation_gpu(address_mode, dtype, use_textures):
156
157
158
159
160
    sver = sympy.__version__.split(".")
    if (int(sver[0]) == 1 and int(sver[1]) < 2) and address_mode in ['mirror', 'warp']:
        pytest.skip()
    pytest.importorskip('pycuda')

161
    import pycuda.gpuarray as gpuarray
162
    import pycuda.autoinit  # noqa
163
164
165
166
167
168

    rotation_angle = 0  # sympy.pi / 5
    scale = 1
    # shift = - sympy.Matrix([1.5, 1.5])
    shift = sympy.Matrix((0.0, 0.0))

169
170
171
172
173
174
175
    if dtype == np.int32:
        lenna_gpu = gpuarray.to_gpu(
            np.ascontiguousarray(lenna * 255, dtype))
    else:
        lenna_gpu = gpuarray.to_gpu(
            np.ascontiguousarray(lenna, dtype))

176
    x_f, y_f = pystencils.fields(f'x,y: {type_map[dtype]} [2d]', ghost_layers=0)
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

    if use_textures:
        transformed = scale * sympy.rot_axis3(rotation_angle)[:2, :2] * sympy.Matrix((x_, y_)) + shift
    else:
        transformed = scale * sympy.rot_axis3(rotation_angle)[:2, :2] * sympy.Matrix((x_, y_)) + shift
    assignments = pystencils.AssignmentCollection({
        y_f.center(): LinearInterpolator(x_f, address_mode=address_mode).at(transformed)
    })
    # print(assignments)
    ast = pystencils.create_kernel(assignments, target='gpu', use_textures_for_interpolation=use_textures)
    # print(ast)
    print(pystencils.show_code(ast))
    kernel = ast.compile()

    out = gpuarray.zeros_like(lenna_gpu)
    kernel(x=lenna_gpu, y=out)
    pyconrad.imshow(out,
                    f"out {address_mode} texture:{use_textures} {type_map[dtype]}")
195
196
197
198
199
200
201


@pytest.mark.parametrize('address_mode', ['border', 'clamp'])
def test_rotate_interpolation_size_change(address_mode):
    """
    'wrap', 'mirror' currently fails on new sympy due to conjugate()
    """
202
203
204
205
    x_f, y_f = pystencils.fields('x,y: float64 [2d]')

    rotation_angle = sympy.pi / 5

206
207
208
209
210
211
212
    transformed = sympy.rot_axis3(rotation_angle)[:2, :2] * sympy.Matrix((x_, y_))
    assignments = pystencils.AssignmentCollection({
        y_f.center(): LinearInterpolator(x_f, address_mode=address_mode).at(transformed)
    })
    print(assignments)
    ast = pystencils.create_kernel(assignments)
    print(ast)
213
    print(pystencils.show_code(ast))
214
    kernel = ast.compile()
215

216
217
218
    out = np.zeros((100, 150), np.float64)
    kernel(x=lenna, y=out)
    pyconrad.imshow(out, "small out " + address_mode)
219
220


221
@pytest.mark.parametrize('address_mode, target',
222
                         itertools.product(['border', 'wrap', 'clamp', 'mirror'], ['cpu']))
223
def test_field_interpolated(address_mode, target):
224
225
    x_f, y_f = pystencils.fields('x,y: float64 [2d]')

226
227
228
229
    assignments = pystencils.AssignmentCollection({
        y_f.center(): x_f.interpolated_access([0.5 * x_ + 2.7, 0.25 * y_ + 7.2], address_mode=address_mode)
    })
    print(assignments)
230
    ast = pystencils.create_kernel(assignments, target=target)
231
    print(ast)
232
    print(pystencils.show_code(ast))
233
    kernel = ast.compile()
234

235
236
237
    out = np.zeros_like(lenna)
    kernel(x=lenna, y=out)
    pyconrad.imshow(out, "out " + address_mode)
238
239
240
241
242
243
244
245


def test_spatial_derivative():
    x, y = pystencils.fields('x, y:  float32[2d]')
    tx, ty = pystencils.fields('t_x, t_y: float32[2d]')

    diff = sympy.diff(x.interpolated_access((tx.center, ty.center)), tx.center)
    print("diff: " + str(diff))