test_superresolution.py 15.9 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(
Stephan Seitz's avatar
Stephan Seitz committed
122
123
124
                (args.norm(),
                 sympy.atan2(args[1] - x.shape[1] / 2,
                             args[0] - x.shape[0] / 2) / sympy.pi * x.shape[1] / 2))
125
126

        def inv():
127
128
            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
129
                              + sympy.Matrix(x.shape) * 0.5)
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145

    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()
146
147
    # while True:
    # sleep(100)
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


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()
176
177
    # while True:
    # sleep(100)
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


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()
222
223
    # while True:
    # sleep(100)
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


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()

256
257
    # while True:
    # sleep(100)
258
259
260
261
262
263
264


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
265
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center + pystencils.y_))
266
267
268
269
    })

    backward_assignments = pystencils.autodiff.create_backward_assignments(assignments)

Stephan Seitz's avatar
Stephan Seitz committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    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))
288
    print("backward_assignments: " + str(backward_assignments))
Stephan Seitz's avatar
Stephan Seitz committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305


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
306
307
        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
308
309
310
311
312
    }).create_pytorch_op()().forward

    dh.run_kernel(kernel)

    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
313
314


315
316
@pytest.mark.parametrize('scalar_experiment', (False,))
def test_get_shift_tensors(scalar_experiment):
Stephan Seitz's avatar
Stephan Seitz committed
317
318
319
320
321
322
323
324
325
326
327
328
329
    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()
330
    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
331
332

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

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

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

341
342
343
344
345
346
347
348
349
350
    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
351
352
        y.center: x.interpolated_access((tx.center + pystencils.x_,
                                         2 * ty.center + pystencils.y_))
353
354
355
356
    })

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

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

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

    for i in range(100):
367
368
369
370
371
372
373
374
        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
375
376
377
378
379
        y = dh.run_kernel(kernel)
        loss = (y - y_array).norm()

        optimizer.zero_grad()

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

        optimizer.step()
        print(loss.cpu().detach().numpy())
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
424
425
        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
426
427
428

    pyconrad.imshow(dh.gpu_arrays)
    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490


@pytest.mark.parametrize('scalar_experiment', (False,))
def test_rotation(scalar_experiment):
    from pystencils_autodiff.framework_integration.datahandling import PyTorchDataHandling
    from pystencils_reco.resampling import rotation_transform

    import torch

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

    GROUNDTRUTH_ANGLE = 0.3

    target = np.zeros(lenna.shape)
    rotation_transform(lenna, target, GROUNDTRUTH_ANGLE)()
    target = torch.Tensor(target).cuda()

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

    if scalar_experiment:
        var_angle = torch.zeros((), requires_grad=True)
    else:
        var_angle = torch.zeros(lenna.shape, requires_grad=True)

    var_lenna = torch.autograd.Variable(torch.from_numpy(
        lenna + np.random.randn(*lenna.shape).astype(np.float32)), requires_grad=True)
    assert var_lenna.requires_grad

    learning_rate = 0.1
    params = (var_angle, var_lenna)

    optimizer = torch.optim.Adam(params, lr=learning_rate)

    assignments = rotation_transform(x, y, angle)
    kernel = assignments.create_pytorch_op()
    print(kernel)

    kernel = kernel().call

    for i in range(100000):
        if scalar_experiment:
            dh.cpu_arrays.angle = torch.ones(lenna.shape) * (var_angle + 0.29)
        else:
            dh.cpu_arrays.angle = var_angle
        dh.cpu_arrays.x = var_lenna
        dh.all_to_gpu()

        y = dh.run_kernel(kernel)
        loss = (y - target).norm()

        optimizer.zero_grad()

        loss.backward(retain_graph=True)
        assert y.requires_grad

        optimizer.step()
        print(loss.cpu().detach().numpy())
        pyconrad.imshow(var_lenna)

    pyconrad.show_everything()