-
Notifications
You must be signed in to change notification settings - Fork 9
/
misc.py
738 lines (562 loc) · 22.1 KB
/
misc.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
174
175
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
220
221
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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
424
425
426
427
428
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# Copyright 2018 Matthias J. Ehrhardt, University of Cambridge
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
"""Functions for folders and files."""
from __future__ import print_function
from builtins import super
import numpy as np
import odl
import scipy.signal
import matplotlib
import matplotlib.pyplot as plt
from skimage.io import imsave
__all__ = ('total_variation', 'TotalVariationNonNegative', 'save_image',
'save_signal', 'divide_1Darray_equally', 'Blur2D',
'KullbackLeiblerSmooth')
def save_image(image, name, folder, fignum, cmap='gray', clim=None):
matplotlib.rc('text', usetex=False)
fig = plt.figure(fignum)
plt.clf()
image.show(name, cmap=cmap, fig=fig)
fig.savefig('{}/{}_fig.png'.format(folder, name), bbox_inches='tight')
if clim is None:
x = image - np.min(image)
if np.max(x) > 1e-4:
x /= np.max(x)
else:
x = (image - clim[0]) / (clim[1] - clim[0])
x = np.minimum(np.maximum(x, 0), 1)
imsave('{}/{}.png'.format(folder, name), np.rot90(x, 1))
def save_signal(signal, name, folder, fignum):
matplotlib.rc('text', usetex=False)
fig = plt.figure(fignum)
plt.clf()
signal.show(name, fig=fig)
fig.savefig('{}/{}_fig.png'.format(folder, name), bbox_inches='tight')
def partition_1d(arr, slices):
return tuple(arr[slc] for slc in slices)
def partition_equally_1d(arr, nparts, order='interlaced'):
if order == 'block':
stride = int(np.ceil(arr.size / nparts))
slc_list = [slice(i * stride, (i + 1) * stride) for i in range(nparts)]
elif order == 'interlaced':
slc_list = [slice(i, len(arr), nparts) for i in range(nparts)]
else:
raise ValueError
return partition_1d(arr, slc_list)
def divide_1Darray_equally(ind, nsub):
"""Divide an array into equal chunks to be used for instance in OSEM.
Parameters
----------
ind : ndarray
input array
nsubsets : int
number of subsets to be divided into
Returns
-------
sub2ind : list
list of indices for each subset
ind2sub : list
list of subsets for each index
"""
n_ind = len(ind)
sub2ind = partition_equally_1d(ind, nsub, order='interlaced')
ind2sub = []
for i in range(n_ind):
ind2sub.append([])
for i in range(nsub):
for j in sub2ind[i]:
ind2sub[j].append(i)
return (sub2ind, ind2sub)
def total_variation(domain, grad=None):
"""Total variation functional.
Parameters
----------
domain : odlspace
domain of TV functional
grad : gradient operator, optional
Gradient operator of the total variation functional. This may be any
linear operator and thereby generalizing TV. default=forward
differences with Neumann boundary conditions
Examples
--------
Check that the total variation of a constant is zero
>>> import odl.contrib.spdhg as spdhg, odl
>>> space = odl.uniform_discr([0, 0], [3, 3], [3, 3])
>>> tv = spdhg.total_variation(space)
>>> x = space.one()
>>> tv(x) < 1e-10
"""
if grad is None:
grad = odl.Gradient(domain, method='forward', pad_mode='symmetric')
grad.norm = 2 * np.sqrt(sum(1 / grad.domain.cell_sides**2))
else:
grad = grad
f = odl.solvers.GroupL1Norm(grad.range, exponent=2)
return f * grad
class TotalVariationNonNegative(odl.solvers.Functional):
"""Total variation function with nonnegativity constraint and strongly
convex relaxation.
In formulas, this functional may represent
alpha * |grad x|_1 + char_fun(x) + beta/2 |x|^2_2
with regularization parameter alpha and strong convexity beta. In addition,
the nonnegativity constraint is achieved with the characteristic function
char_fun(x) = 0 if x >= 0 and infty else.
Parameters
----------
domain : odlspace
domain of TV functional
alpha : scalar, optional
Regularization parameter, positive
prox_options : dict, optional
name: string, optional
name of the method to perform the prox operator, default=FGP
warmstart: boolean, optional
Do you want a warm start, i.e. start with the dual variable
from the last call? default=True
niter: int, optional
number of iterations per call, default=5
p: array, optional
initial dual variable, default=zeros
grad : gradient operator, optional
Gradient operator to be used within the total variation functional.
default=see TV
"""
def __init__(self, domain, alpha=1, prox_options={}, grad=None,
strong_convexity=0):
"""
"""
self.strong_convexity = strong_convexity
if 'name' not in prox_options:
prox_options['name'] = 'FGP'
if 'warmstart' not in prox_options:
prox_options['warmstart'] = True
if 'niter' not in prox_options:
prox_options['niter'] = 5
if 'p' not in prox_options:
prox_options['p'] = None
if 'tol' not in prox_options:
prox_options['tol'] = None
self.prox_options = prox_options
self.alpha = alpha
self.tv = total_variation(domain, grad=grad)
self.grad = self.tv.right
self.nn = odl.solvers.IndicatorBox(domain, 0, np.inf)
self.l2 = 0.5 * odl.solvers.L2NormSquared(domain)
self.proj_P = self.tv.left.convex_conj.proximal(0)
self.proj_C = self.nn.proximal(1)
super().__init__(space=domain, linear=False, grad_lipschitz=0)
def __call__(self, x):
"""Evaluate functional.
Examples
--------
Check that the total variation of a constant is zero
>>> import odl.contrib.spdhg as spdhg, odl
>>> space = odl.uniform_discr([0, 0], [3, 3], [3, 3])
>>> tvnn = spdhg.TotalVariationNonNegative(space, alpha=2)
>>> x = space.one()
>>> tvnn(x) < 1e-10
Check that negative functions are mapped to infty
>>> import odl.contrib.spdhg as spdhg, odl, numpy as np
>>> space = odl.uniform_discr([0, 0], [3, 3], [3, 3])
>>> tvnn = spdhg.TotalVariationNonNegative(space, alpha=2)
>>> x = -space.one()
>>> np.isinf(tvnn(x))
"""
nn = self.nn(x)
if nn is np.inf:
return nn
else:
out = self.alpha * self.tv(x) + nn
if self.strong_convexity > 0:
out += self.strong_convexity * self.l2(x)
return out
def proximal(self, sigma):
"""Prox operator of TV. It allows the proximal step length to be a
vector of positive elements.
Examples
--------
Check that the proximal operator is the identity for sigma=0
>>> import odl.contrib.solvers.spdhg as spdhg, odl, numpy as np
>>> space = odl.uniform_discr([0, 0], [3, 3], [3, 3])
>>> tvnn = spdhg.TotalVariationNonNegative(space, alpha=2)
>>> x = -space.one()
>>> y = tvnn.proximal(0)(x)
>>> (y-x).norm() < 1e-10
Check that negative functions are mapped to 0
>>> import odl.contrib.solvers.spdhg as spdhg, odl, numpy as np
>>> space = odl.uniform_discr([0, 0], [3, 3], [3, 3])
>>> tvnn = spdhg.TotalVariationNonNegative(space, alpha=2)
>>> x = -space.one()
>>> y = tvnn.proximal(0.1)(x)
>>> y.norm() < 1e-10
"""
if sigma == 0:
return odl.IdentityOperator(self.domain)
else:
def tv_prox(z, out=None):
if out is None:
out = z.space.zero()
opts = self.prox_options
sigma_ = np.copy(sigma)
z_ = z.copy()
if self.strong_convexity > 0:
sigma_ /= (1 + sigma * self.strong_convexity)
z_ /= (1 + sigma * self.strong_convexity)
if opts['name'] == 'FGP':
if opts['warmstart']:
if opts['p'] is None:
opts['p'] = self.grad.range.zero()
p = opts['p']
else:
p = self.grad.range.zero()
sigma_sqrt = np.sqrt(sigma_)
z_ /= sigma_sqrt
grad = sigma_sqrt * self.grad
grad.norm = sigma_sqrt * self.grad.norm
niter = opts['niter']
alpha = self.alpha
out[:] = fgp_dual(p, z_, alpha, niter, grad, self.proj_C,
self.proj_P, tol=opts['tol'])
out *= sigma_sqrt
return out
else:
raise NotImplementedError('Not yet implemented')
return tv_prox
def fgp_dual(p, data, alpha, niter, grad, proj_C, proj_P, tol=None, **kwargs):
"""Computes a solution to the ROF problem with the fast gradient
projection algorithm.
Parameters
----------
p : np.array
dual initial variable
data : np.array
noisy data / proximal point
alpha : float
regularization parameter
niter : int
number of iterations
grad : instance of gradient class
class that supports grad(x), grad.adjoint(x), grad.norm
proj_C : function
projection onto the constraint set of the primal variable,
e.g. non-negativity
proj_P : function
projection onto the constraint set of the dual variable,
e.g. norm <= 1
tol : float (optional)
nonnegative parameter that gives the tolerance for convergence. If set
None, then the algorithm will run for a fixed number of iterations
Other Parameters
----------------
callback : callable, optional
Function called with the current iterate after each iteration.
"""
# Callback object
callback = kwargs.pop('callback', None)
if callback is not None and not callable(callback):
raise TypeError('`callback` {} is not callable'.format(callback))
factr = 1 / (grad.norm**2 * alpha)
q = p.copy()
x = data.space.zero()
t = 1.
if tol is None:
def convergence_eval(p1, p2):
return False
else:
def convergence_eval(p1, p2):
return (p1 - p2).norm() / p1.norm() < tol
pnew = p.copy()
if callback is not None:
callback(p)
for k in range(niter):
t0 = t
grad.adjoint(q, out=x)
proj_C(data - alpha * x, out=x)
grad(x, out=pnew)
pnew *= factr
pnew += q
proj_P(pnew, out=pnew)
converged = convergence_eval(p, pnew)
if not converged:
# update step size
t = (1 + np.sqrt(1 + 4 * t0 ** 2)) / 2.
# calculate next iterate
q[:] = pnew + (t0 - 1) / t * (pnew - p)
p[:] = pnew
if converged:
t = None
break
if callback is not None:
callback(p)
# get current image estimate
x = proj_C(data - alpha * grad.adjoint(p))
return x
class Blur2D(odl.Operator):
"""Blur operator"""
def __init__(self, domain, kernel, boundary_condition='wrap'):
"""Initialize a new instance.
"""
super().__init__(domain=domain, range=domain, linear=True)
self.__kernel = kernel
self.__boundary_condition = boundary_condition
@property
def kernel(self):
return self.__kernel
@property
def boundary_condition(self):
return self.__boundary_condition
def _call(self, x, out):
out[:] = scipy.signal.convolve2d(x, self.kernel, mode='same',
boundary='wrap')
@property
def gradient(self):
raise NotImplementedError('No yet implemented')
@property
def adjoint(self):
adjoint_kernel = self.kernel.copy().conj()
adjoint_kernel = np.fliplr(np.flipud(adjoint_kernel))
return Blur2D(self.domain, adjoint_kernel, self.boundary_condition)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, {!r}, {!r})'.format(
self.__class__.__name__, self.domain, self.kernel,
self.boundary_condition)
class KullbackLeiblerSmooth(odl.solvers.Functional):
"""The smooth Kullback-Leibler divergence functional.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^n`-like space, the
smooth Kullback-Leibler functional :math:`\\phi` is defined as
.. math::
\\phi(x) = \\sum_{i=1}^n \\begin{cases}
x + r - y + y * \\log(y / (x + r))
& \\text{if $x \geq 0$} \\
(y / (2 * r^2)) * x^2 + (1 - y / r) * x + r - b +
b * \\log(b / r) & \\text{else}
\\end{cases}
where all variables on the right hand side of the equation have a subscript
i which is omitted for readability.
References
----------
[CERS2017] A. Chambolle, M. J. Ehrhardt, P. Richtarik and C.-B. Schoenlieb,
*Stochastic Primal-Dual Hybrid Gradient Algorithm with Arbitrary Sampling
and Imaging Applications*. ArXiv: http://arxiv.org/abs/1706.04957 (2017).
"""
def __init__(self, space, data, background):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `TensorSpace`
Domain of the functional.
data : ``space`` `element-like`
Data vector which has to be non-negative.
background : ``space`` `element-like`
Background vector which has to be non-negative.
"""
self.strong_convexity = 0
if background.ufuncs.less_equal(0).ufuncs.sum() > 0:
raise NotImplementedError('Background must be positive')
super().__init__(space=space, linear=False,
grad_lipschitz=np.max(data / background ** 2))
if data not in self.domain:
raise ValueError('`data` not in `domain`'
''.format(data, self.domain))
self.__data = data
self.__background = background
@property
def data(self):
"""The data in the Kullback-Leibler functional."""
return self.__data
@property
def background(self):
"""The background in the Kullback-Leibler functional."""
return self.__background
def _call(self, x):
"""Return the KL-diveregnce in the point ``x``.
If any components of ``x`` is non-positive, the value is positive
infinity.
"""
y = self.data
r = self.background
obj = self.domain.zero()
# x + r - y + y * log(y / (x + r)) = x - y * log(x + r) + c1
# with c1 = r - y + y * log y
i = x.ufuncs.greater_equal(0)
obj[i] = x[i] + r[i] - y[i]
j = y.ufuncs.greater(0)
k = i.ufuncs.logical_and(j)
obj[k] += y[k] * (y[k] / (x[k] + r[k])).ufuncs.log()
# (y / (2 * r^2)) * x^2 + (1 - y / r) * x + r - b + b * log(b / r)
# = (y / (2 * r^2)) * x^2 + (1 - y / r) * x + c2
# with c2 = r - b + b * log(b / r)
i = i.ufuncs.logical_not()
obj[i] += (y[i] / (2 * r[i]**2) * x[i]**2 + (1 - y[i] / r[i]) * x[i] +
r[i] - y[i])
k = i.ufuncs.logical_and(j)
obj[k] += y[k] * (y[k] / r[k]).ufuncs.log()
return obj.inner(self.domain.one())
@property
def gradient(self):
"""Gradient operator of the functional.
"""
raise NotImplementedError('No yet implemented')
@property
def proximal(self):
"""Return the `proximal factory` of the functional.
"""
raise NotImplementedError('No yet implemented')
@property
def convex_conj(self):
"""The convex conjugate functional of the KL-functional."""
return KullbackLeiblerSmoothConvexConj(self.domain, self.data,
self.background)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, {!r}, {!r})'.format(
self.__class__.__name__, self.domain, self.data, self.background)
class KullbackLeiblerSmoothConvexConj(odl.solvers.Functional):
"""The convex conjugate of the smooth Kullback-Leibler divergence functional.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^n`-like space, the
convex conjugate of the smooth Kullback-Leibler functional :math:`\\phi^*`
is defined as
.. math::
\\phi^*(x) = \\sum_{i=1}^n \\begin{cases}
r^2 / (2 * y) * x^2 + (r - r^2 / y) * x + r^2 / (2 * y) +
3 / 2 * y - 2 * r - y * log(y / r)
& \\text{if $x < 1 - y / r$} \\
- r * x - y * log(1 - x)
& \\text{if $1 - y / r <= x < 1} \\
+ \infty
& \\text{else}
\\end{cases}
where all variables on the right hand side of the equation have a subscript
:math:`i` which is omitted for readability.
References
----------
[CERS2017] A. Chambolle, M. J. Ehrhardt, P. Richtarik and C.-B. Schoenlieb,
*Stochastic Primal-Dual Hybrid Gradient Algorithm with Arbitrary Sampling
and Imaging Applications*. ArXiv: http://arxiv.org/abs/1706.04957 (2017).
"""
def __init__(self, space, data, background):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `TensorSpace`
Domain of the functional.
data : ``space`` `element-like`
Data vector which has to be non-negative.
background : ``space`` `element-like`
Background vector which has to be non-negative.
"""
if background.ufuncs.less_equal(0).ufuncs.sum() > 0:
raise NotImplementedError('Background must be positive')
super().__init__(space=space, linear=False,
grad_lipschitz=np.inf)
if data is not None and data not in self.domain:
raise ValueError('`data` not in `domain`'
''.format(data, self.domain))
self.__data = data
self.__background = background
if np.min(self.data) == 0:
self.strong_convexity = np.inf
else:
self.strong_convexity = np.min(self.background**2 / self.data)
@property
def data(self):
"""The data in the Kullback-Leibler functional."""
return self.__data
@property
def background(self):
"""The background in the Kullback-Leibler functional."""
return self.__background
def _call(self, x):
"""Return the value in the point ``x``.
If any components of ``x`` is larger than or equal to 1, the value is
positive infinity.
"""
# TODO: cover properly the case data = 0
y = self.data
r = self.background
# if any element is greater or equal to one
if x.ufuncs.greater_equal(1).ufuncs.sum() > 0:
return np.inf
obj = self.domain.zero()
# out = sum(f)
# f =
# if x < 1 - y / r:
# r^2 / (2 * y) * x^2 + (r - r^2 / y) * x + r^2 / (2 * y) +
# 3 / 2 * y - 2 * r - y * log(y / r)
# if x >= 1 - y / r:
# - r * x - y * log(1 - x)
i = x.ufuncs.less(1 - y / r)
ry = r[i]**2 / y[i]
obj[i] += (ry / 2 * x[i]**2 + (r[i] - ry) * x[i] + ry / 2 +
3 / 2 * y[i] - 2 * r[i])
j = y.ufuncs.greater(0)
k = i.ufuncs.logical_and(j)
obj[k] -= y[k] * (y[k] / r[k]).ufuncs.log()
i = i.ufuncs.logical_not()
obj[i] -= r[i] * x[i]
k = i.ufuncs.logical_and(j)
obj[k] -= y[k] * (1 - x[k]).ufuncs.log()
return obj.inner(self.domain.one())
@property
def gradient(self):
"""Gradient operator of the functional."""
raise NotImplementedError('No yet implemented')
@property
def proximal(self):
space = self.domain
y = self.data
r = self.background
class ProxKullbackLeiblerSmoothConvexConj(odl.Operator):
"""Proximal operator of the convex conjugate of the smooth
Kullback-Leibler functional.
"""
def __init__(self, sigma):
"""Initialize a new instance.
Parameters
----------
sigma : positive float
Step size parameter
"""
self.sigma = float(sigma)
self.background = r
self.data = y
super().__init__(domain=space, range=space, linear=False)
def _call(self, x, out):
s = self.sigma
y = self.data
r = self.background
sr = s * r
sy = s * y
# out =
# if x < 1 - y / r:
# (y * x - s * r * y + s * r**2) / (y + s * r**2)
# if x >= 1 - y / r:
# 0.5 * (x + s * r + 1 -
# sqrt((x + s * r - 1)**2 + 4 * s * y)
i = x.ufuncs.less(1 - y / r)
# TODO: This may be faster without indexing on the GPU?
out[i] = ((y[i] * x[i] - sr[i] * y[i] + sr[i] * r[i]) /
(y[i] + sr[i] * r[i]))
i.ufuncs.logical_not(out=i)
out[i] = (x[i] + sr[i] + 1 -
((x[i] + sr[i] - 1) ** 2 + 4 * sy[i]).ufuncs.sqrt())
out[i] /= 2
return out
return ProxKullbackLeiblerSmoothConvexConj
@property
def convex_conj(self):
"""The convex conjugate functional of the smooth KL-functional."""
return KullbackLeiblerSmooth(self.domain, self.data,
self.background)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, {!r}, {!r})'.format(
self.__class__.__name__, self.domain, self.data, self.background)