test_superresolution.py 16.4 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
import pystencils_reco.transforms
19
from pystencils_reco import crazy
20
21
22
23
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
24
25
26
27
28
29
30
31
32
33

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


def test_superresolution():

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

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

    pyconrad.show_everything()


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def test_torch_simple():

    import pytest
    pytest.importorskip("torch")
    import torch

    x, y = torch.zeros((20, 20)), torch.zeros((20, 20))
    a = sympy.Symbol('a')

    @crazy
    def move(x, y, a):
        return {
            y.center: x.interpolated_access((pystencils.x_, pystencils.y_ + a))
        }

    kernel = move(x, y, a).compile()
    pystencils.autodiff.show_code(kernel.ast)


Stephan Seitz's avatar
Stephan Seitz committed
62
63
64
def test_downsample():
    shape = (20, 10)

65
    x, y = np.random.rand(*shape), np.zeros(tuple(s // 2 for s in shape))
Stephan Seitz's avatar
Stephan Seitz committed
66
67
68
69
70
71

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

    pyconrad.show_everything()
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90


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
91
92
93
94
95
96
97
98
99
100
101


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)

102
    transformed = np.zeros((400, 400), np.float32)
Stephan Seitz's avatar
Stephan Seitz committed
103
104
105

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

106
    pyconrad.show_everything()
107
108
    # while True:
    # sleep(100)
109
110
111
112
113
114
115


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
116
117
118
            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))
119
120
121
122
123
124
125
126
127
128
129
130
131

    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()
132
133
    # while True:
    # sleep(100)
134
135
136
137
138
139
140
141


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
142
143
144
                (args.norm(),
                 sympy.atan2(args[1] - x.shape[1] / 2,
                             args[0] - x.shape[0] / 2) / sympy.pi * x.shape[1] / 2))
145
146

        def inv():
147
148
            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
149
                              + sympy.Matrix(x.shape) * 0.5)
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

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


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


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


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

276
277
    # while True:
    # sleep(100)
278
279
280
281
282
283
284


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
285
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center + pystencils.y_))
286
287
288
289
    })

    backward_assignments = pystencils.autodiff.create_backward_assignments(assignments)

Stephan Seitz's avatar
Stephan Seitz committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    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))
308
    print("backward_assignments: " + str(backward_assignments))
Stephan Seitz's avatar
Stephan Seitz committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325


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
326
327
        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
328
329
330
331
332
    }).create_pytorch_op()().forward

    dh.run_kernel(kernel)

    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
333
334


335
336
@pytest.mark.parametrize('scalar_experiment', (False,))
def test_get_shift_tensors(scalar_experiment):
Stephan Seitz's avatar
Stephan Seitz committed
337
338
339
340
341
342
343
344
345
346
347
348
349
    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()
350
    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
351
352

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

356
    y_array = dh.run_kernel(kernel)
Stephan Seitz's avatar
Stephan Seitz committed
357
358
359
360

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

361
362
363
364
365
366
367
368
369
370
    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
371
372
        y.center: x.interpolated_access((tx.center + pystencils.x_,
                                         2 * ty.center + pystencils.y_))
373
374
375
376
    })

    print(pystencils.autodiff.create_backward_assignments(assignments))
    kernel = assignments.create_pytorch_op()
Stephan Seitz's avatar
Stephan Seitz committed
377
378
379
380

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

381
382
    learning_rate = 0.1
    params = (var_x, var_y)
Stephan Seitz's avatar
Stephan Seitz committed
383
384
385
386
    # assert all([p.is_leaf for p in params])
    optimizer = torch.optim.Adam(params, lr=learning_rate)

    for i in range(100):
387
388
389
390
391
392
393
394
        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
395
396
397
398
399
        y = dh.run_kernel(kernel)
        loss = (y - y_array).norm()

        optimizer.zero_grad()

400
        loss.backward(retain_graph=True)
Stephan Seitz's avatar
Stephan Seitz committed
401
402
403
404
        assert y.requires_grad

        optimizer.step()
        print(loss.cpu().detach().numpy())
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
        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
446
447
448

    pyconrad.imshow(dh.gpu_arrays)
    pyconrad.imshow(dh.gpu_arrays)
Stephan Seitz's avatar
Stephan Seitz committed
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510


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