test_superresolution.py 14.1 KB
Newer Older
Stephan Seitz's avatar
Stephan Seitz committed
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
11
from os.path import dirname, join

Stephan Seitz's avatar
Stephan Seitz committed
12
import numpy as np
13
import pytest
14
import skimage.io
Stephan Seitz's avatar
Stephan Seitz committed
15
import sympy
Stephan Seitz's avatar
Stephan Seitz committed
16
17

import pystencils
18
19
20
21
22
import pystencils_reco.transforms
from pystencils_reco.filters import gauss_filter
from pystencils_reco.resampling import (
    downsample, resample, resample_to_shape, scale_transform, translate)
from pystencils_reco.stencils import BallStencil
Stephan Seitz's avatar
Stephan Seitz committed
23
24
25
26
27
28
29
30
31
32

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


def test_superresolution():

33
    x, y = np.random.rand(20, 10), np.zeros((20, 10))
Stephan Seitz's avatar
Stephan Seitz committed
34
35
36
37
38
39
40
41
42
43
44

    kernel = scale_transform(x, y, 0.5).compile()
    print(pystencils.show_code(kernel))
    kernel()

    pyconrad.show_everything()


def test_downsample():
    shape = (20, 10)

45
    x, y = np.random.rand(*shape), np.zeros(tuple(s // 2 for s in shape))
Stephan Seitz's avatar
Stephan Seitz committed
46
47
48
49
50
51

    kernel = downsample(x, y, 2).compile()
    print(pystencils.show_code(kernel))
    kernel()

    pyconrad.show_everything()
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70


def test_warp():
    import torch
    NUM_LENNAS = 5
    perturbation = 0.1

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    warp_vectors = list(perturbation * torch.randn(lenna.shape + (2,)) for _ in range(NUM_LENNAS))

    warped = [torch.zeros(lenna.shape) for _ in range(NUM_LENNAS)]

    warp_kernel = translate(lenna, warped[0], pystencils.autodiff.ArrayWrapper(
        warp_vectors[0], index_dimensions=1), interpolation_mode='linear').compile()

    for i in range(len(warped)):
        warp_kernel(lenna[i], warped[i], warp_vectors[i])
Stephan Seitz's avatar
Stephan Seitz committed
71
72
73
74
75
76
77
78
79
80
81


def test_polar_transform():
    x, y = pystencils.fields('x, y:  float32[2d]')

    x.set_coordinate_origin_to_field_center()
    y.set_coordinate_origin_to_field_center()

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

82
    transformed = np.zeros((400, 400), np.float32)
Stephan Seitz's avatar
Stephan Seitz committed
83
84
85

    resample(x, y).compile()(x=lenna, y=transformed)

86
    pyconrad.show_everything()
87
88
    # while True:
    # sleep(100)
89
90
91
92
93
94
95


def test_polar_transform2():
    x, y = pystencils.fields('x, y:  float32[2d]')

    class PolarTransform(sympy.Function):
        def eval(args):
Stephan Seitz's avatar
Stephan Seitz committed
96
97
98
            return sympy.Matrix((args.norm(),
                                 sympy.atan2(args[1] - x.shape[1] / 2,
                                             args[0] - x.shape[0] / 2) / sympy.pi * x.shape[1] / 2))
99
100
101
102
103
104
105
106
107
108
109
110
111

    x.set_coordinate_origin_to_field_center()
    y.coordinate_transform = PolarTransform
    y.set_coordinate_origin_to_field_center()

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    transformed = np.zeros((400, 400), np.float32)

    resample(x, y).compile()(x=lenna, y=transformed)

    pyconrad.show_everything()
112
113
    # while True:
    # sleep(100)
114
115
116
117
118
119
120
121


def test_polar_inverted_transform():
    x, y = pystencils.fields('x, y:  float32[2d]')

    class PolarTransform(sympy.Function):
        def eval(args):
            return sympy.Matrix(
122
                (args.norm(), sympy.atan2(args[1] - x.shape[1] / 2, args[0] - x.shape[0] / 2) / sympy.pi * x.shape[1] / 2))
123
124

        def inv():
125
126
            return lambda l: (sympy.Matrix((sympy.cos(l[1] * sympy.pi / x.shape[1] * 2) * l[0],
                                            sympy.sin(l[1] * sympy.pi / x.shape[1] * 2) * l[0]))
Stephan Seitz's avatar
Stephan Seitz committed
127
                              + sympy.Matrix(x.shape) * 0.5)
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    # transformed = np.zeros((400, 400), np.float32)
    # back_transformed = np.zeros((400, 400), np.float32)
    transformed = np.zeros_like(lenna)
    back_transformed = np.zeros_like(lenna)

    x.set_coordinate_origin_to_field_center()
    y.coordinate_transform = PolarTransform
    y.set_coordinate_origin_to_field_center()
    resample(x, y).compile()(x=lenna, y=transformed)
    resample(y, x).compile()(x=back_transformed, y=transformed)

    pyconrad.show_everything()
144
145
    # while True:
    # sleep(100)
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


def test_shift():
    x, y = pystencils.fields('x, y:  float32[2d]')

    class ShiftTransform(sympy.Function):
        def eval(args):
            return args + sympy.Matrix((5, 5))

        def inv():
            return lambda l: l - sympy.Matrix((5, 5))

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    transformed = np.zeros_like(lenna)
    back_transformed = np.zeros_like(lenna)

    x.set_coordinate_origin_to_field_center()
    y.coordinate_transform = ShiftTransform
    y.set_coordinate_origin_to_field_center()
    resample(x, y).compile()(x=lenna, y=transformed)
    resample(y, x).compile()(x=back_transformed, y=transformed)

    diff = lenna - back_transformed
    assert diff is not None

    pyconrad.show_everything()
174
175
    # while True:
    # sleep(100)
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


def test_motion_model():
    x, y = pystencils.fields('x, y:  float32[2d]')
    transform_field = pystencils.fields('t_x, t_y: float32[2d]')

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    # transformed = np.zeros((400, 400), np.float32)
    # back_transformed = np.zeros((400, 400), np.float32)
    transformed = np.zeros_like(lenna)
    back_transformed = np.zeros_like(lenna)
    translate_x = np.zeros((10, 10), np.float32)
    translate_y = np.zeros((10, 10), np.float32)

    pystencils_reco.transforms.extend_to_size_of_other_field(transform_field[0], x)
    pystencils_reco.transforms.extend_to_size_of_other_field(transform_field[1], x)

    shift = sympy.Matrix(sympy.symbols('s:2'))
    shift_val = sympy.Matrix([transform_field[i].interpolated_access(
        transform_field[i].physical_to_index(x.physical_coordinates))
        for i in range(x.ndim)])

    class ShiftTransform(sympy.Function):
        def eval(args):
            return args + shift

        def inv():
            return lambda args: args - shift

    y.coordinate_transform = ShiftTransform
    pystencils_reco.AssignmentCollection([*resample(x, y),
                                          *[pystencils.Assignment(shift[i], shift_val[i]) for i in range(2)]]
                                         ).compile()(x=lenna, y=transformed, t_x=translate_x, t_y=translate_y)

    pystencils_reco.AssignmentCollection([*resample(x, y),
                                          *[pystencils.Assignment(shift[i], shift_val[i]) for i in range(2)]]
                                         ).compile()(x=back_transformed,
                                                     y=transformed,
                                                     t_x=translate_x,
                                                     t_y=translate_y)

    pyconrad.show_everything()
220
221
    # while True:
    # sleep(100)
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


def test_motion_model2():
    x, y = pystencils.fields('x, y:  float32[2d]')
    transform_field = pystencils.fields('t_x, t_y: float32[2d]')

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    # transformed = np.zeros((400, 400), np.float32)
    # back_transformed = np.zeros((400, 400), np.float32)
    transformed = np.zeros_like(lenna)
    blurred = np.zeros_like(lenna)

    translate_x = np.zeros_like(lenna)
    translate_y = np.zeros_like(lenna)
    amplitude = 20

    resample_to_shape(amplitude * np.random.randn(10, 10).astype(np.float32), lenna.shape).compile()(output=translate_x)
    resample_to_shape(amplitude * np.random.randn(10, 10).astype(np.float32), lenna.shape).compile()(output=translate_y)

    translate(x, y, sympy.Matrix((transform_field[0].center, transform_field[1].center))
              ).compile()(x=lenna, y=transformed, t_x=translate_x, t_y=translate_y)

    # resample(x, y).compile()(x=back_transformed, y=transformed, t_x=translate_x, t_y=translate_y)

    kernel = gauss_filter(transformed, blurred, BallStencil(5, ndim=2), 10).compile()
    print(pystencils.show_code(kernel))
    kernel(input_field=transformed, output_field=blurred)

    pyconrad.show_everything()

254
255
    # while True:
    # sleep(100)
256
257
258
259
260
261
262


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

    assignments = pystencils.AssignmentCollection({
Stephan Seitz's avatar
Stephan Seitz committed
263
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center + pystencils.y_))
264
265
266
267
    })

    backward_assignments = pystencils.autodiff.create_backward_assignments(assignments)

Stephan Seitz's avatar
Stephan Seitz committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
    print("assignments: " + str(assignments))
    print("backward_assignments: " + str(backward_assignments))


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

    assignments = pystencils.AssignmentCollection({
        y.center: x.interpolated_access((tx.center + pystencils.x_, ty.center + 2 * pystencils.y_))
    })

    backward_assignments = pystencils.autodiff.create_backward_assignments(assignments)

    assert backward_assignments.atoms(pystencils.interpolation_astnodes.DiffInterpolatorAccess)

    print("assignments: " + str(assignments))
286
    print("backward_assignments: " + str(backward_assignments))
Stephan Seitz's avatar
Stephan Seitz committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303


def test_get_shift():
    from pystencils_autodiff.framework_integration.datahandling import PyTorchDataHandling

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    dh = PyTorchDataHandling(lenna.shape)
    x, y, tx, ty = dh.add_arrays('x, y, tx, ty')

    dh.cpu_arrays['x'] = lenna
    dh.cpu_arrays['tx'][...] = 0.7
    dh.cpu_arrays['ty'][...] = -0.7
    dh.all_to_gpu()

    kernel = pystencils_reco.AssignmentCollection({
Stephan Seitz's avatar
Stephan Seitz committed
304
305
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center +
                                         pystencils.y_), interpolation_mode='cubic_spline')
Stephan Seitz's avatar
Stephan Seitz committed
306
307
308
309
310
    }).create_pytorch_op()().forward

    dh.run_kernel(kernel)

    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
311
312


313
314
@pytest.mark.parametrize('scalar_experiment', (False,))
def test_get_shift_tensors(scalar_experiment):
Stephan Seitz's avatar
Stephan Seitz committed
315
316
317
318
319
320
321
322
323
324
325
326
327
    from pystencils_autodiff.framework_integration.datahandling import PyTorchDataHandling
    import torch

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    dh = PyTorchDataHandling(lenna.shape)
    x, y, tx, ty = dh.add_arrays('xw, yw, txw, tyw')

    dh.cpu_arrays['xw'] = lenna
    dh.cpu_arrays['txw'][...] = 0.7
    dh.cpu_arrays['tyw'][...] = -0.7
    dh.all_to_gpu()
328
    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
329
330

    kernel = pystencils_reco.AssignmentCollection({
331
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center + pystencils.y_))
Stephan Seitz's avatar
Stephan Seitz committed
332
333
    }).create_pytorch_op()().call

334
    y_array = dh.run_kernel(kernel)
Stephan Seitz's avatar
Stephan Seitz committed
335
336
337
338

    dh = PyTorchDataHandling(lenna.shape)
    x, y, tx, ty = dh.add_arrays('x, y, tx, ty')

339
340
341
342
343
344
345
346
347
348
    if scalar_experiment:
        var_x = torch.zeros((), requires_grad=True)
        var_y = torch.zeros((), requires_grad=True)
    else:
        var_x = torch.zeros(lenna.shape, requires_grad=True)
        var_y = torch.zeros(lenna.shape, requires_grad=True)

    dh.cpu_arrays.x = lenna

    assignments = pystencils_reco.AssignmentCollection({
Stephan Seitz's avatar
Stephan Seitz committed
349
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center +
350
351
352
353
354
                                         pystencils.y_))
    })

    print(pystencils.autodiff.create_backward_assignments(assignments))
    kernel = assignments.create_pytorch_op()
Stephan Seitz's avatar
Stephan Seitz committed
355
356
357
358

    print(kernel.ast)
    kernel = kernel().call

359
360
    learning_rate = 0.1
    params = (var_x, var_y)
Stephan Seitz's avatar
Stephan Seitz committed
361
362
363
364
    # assert all([p.is_leaf for p in params])
    optimizer = torch.optim.Adam(params, lr=learning_rate)

    for i in range(100):
365
366
367
368
369
370
371
372
        if scalar_experiment:
            dh.cpu_arrays.tx = torch.ones(lenna.shape) * var_x
            dh.cpu_arrays.ty = torch.ones(lenna.shape) * var_y
        else:
            dh.cpu_arrays.tx = var_x
            dh.cpu_arrays.ty = var_y
        dh.all_to_gpu()

Stephan Seitz's avatar
Stephan Seitz committed
373
374
375
376
377
        y = dh.run_kernel(kernel)
        loss = (y - y_array).norm()

        optimizer.zero_grad()

378
        loss.backward(retain_graph=True)
Stephan Seitz's avatar
Stephan Seitz committed
379
380
381
382
        assert y.requires_grad

        optimizer.step()
        print(loss.cpu().detach().numpy())
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        print("var_x: " + str(var_x.mean()))
        pyconrad.imshow(var_x)
    # pyconrad.imshow(dh.gpu_arrays)
    pyconrad.imshow(dh.gpu_arrays, wait_window_close=True)


@pytest.mark.parametrize('with_spline', ('with_spline', False))
def test_spline_diff(with_spline):
    from pystencils.fd import Diff
    from pystencils.datahandling import SerialDataHandling

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    dh = SerialDataHandling(lenna.shape, default_target='gpu', default_ghost_layers=0, default_layout='numpy')
    x, y, tx, ty = dh.add_arrays('x, y, tx, ty', dtype=np.float32)

    dh.cpu_arrays['x'] = lenna
    dh.cpu_arrays['tx'][...] = 0.7
    dh.cpu_arrays['ty'][...] = -0.7
    out = dh.add_array('out', dtype=np.float32)
    dh.all_to_gpu()

    kernel = pystencils_reco.AssignmentCollection({
        y.center: Diff(x, 0).interpolated_access((tx.center + pystencils.x_,
                                                  ty.center + pystencils.y_),
                                                 interpolation_mode='cubic_spline' if with_spline else 'linear')
    }).compile(target='gpu')

    dh.run_kernel(kernel)

    print(pystencils.show_code(kernel))

    kernel = pystencils_reco.AssignmentCollection({
        out.center: x.interpolated_access((tx.center + pystencils.x_, ty.center + pystencils.y_),
                                          interpolation_mode='cubic_spline' if with_spline else 'linear')
    }).compile(target='gpu')

    dh.run_kernel(kernel)

    print(pystencils.show_code(kernel))
Stephan Seitz's avatar
Stephan Seitz committed
424
425
426

    pyconrad.imshow(dh.gpu_arrays)
    pyconrad.imshow(dh.gpu_arrays)