-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathfunctional.py
1597 lines (1235 loc) · 52.5 KB
/
functional.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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2014-2019 The ODL contributors
#
# This file is part of ODL.
#
# 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/.
from __future__ import print_function, division, absolute_import
import numpy as np
from odl.operator.operator import (
Operator, OperatorComp, OperatorLeftScalarMult, OperatorRightScalarMult,
OperatorRightVectorMult, OperatorSum, OperatorPointwiseProduct)
from odl.operator.default_ops import (IdentityOperator, ConstantOperator)
from odl.solvers.nonsmooth import (proximal_arg_scaling, proximal_translation,
proximal_quadratic_perturbation,
proximal_const_func, proximal_convex_conj)
from odl.util import signature_string, indent
__all__ = ('Functional', 'FunctionalLeftScalarMult',
'FunctionalRightScalarMult', 'FunctionalComp',
'FunctionalRightVectorMult', 'FunctionalSum', 'FunctionalScalarSum',
'FunctionalTranslation', 'InfimalConvolution',
'FunctionalQuadraticPerturb', 'FunctionalProduct',
'FunctionalQuotient', 'BregmanDistance', 'simple_functional')
class Functional(Operator):
"""Implementation of a functional class.
A functional is an operator ``f`` that maps from some domain ``X`` to the
field of scalars ``F`` associated with the domain:
``f : X -> F``.
Notes
-----
The implementation of the functional class assumes that the domain
:math:`X` is a Hilbert space and that the field of scalars :math:`F` is a
is the real numbers. It is possible to create functions that do not fulfil
these assumptions, however some mathematical results might not be valid in
this case. For more information, see `the ODL functional guide
<http://odlgroup.github.io/odl/guide/in_depth/functional_guide.html>`_.
"""
def __init__(self, space, linear=False, grad_lipschitz=np.nan):
"""Initialize a new instance.
Parameters
----------
space : `LinearSpace`
The domain of this functional, i.e., the set of elements to
which this functional can be applied.
linear : bool, optional
If `True`, the functional is considered as linear.
grad_lipschitz : float, optional
The Lipschitz constant of the gradient. Default: ``nan``
"""
# Cannot use `super(Functional, self)` here since that breaks
# subclasses with multiple inheritance (at least those where both
# parents implement `__init__`, e.g., in `ScalingFunctional`)
Operator.__init__(self, domain=space, range=space.field, linear=linear)
self.__grad_lipschitz = float(grad_lipschitz)
@property
def grad_lipschitz(self):
"""Lipschitz constant for the gradient of the functional."""
return self.__grad_lipschitz
@grad_lipschitz.setter
def grad_lipschitz(self, value):
"""Setter for the Lipschitz constant for the gradient."""
self.__grad_lipschitz = float(value)
@property
def gradient(self):
r"""Gradient operator of the functional.
Notes
-----
The operator that corresponds to the mapping
.. math::
x \to \nabla f(x)
where :math:`\nabla f(x)` is the element used to evaluate
derivatives in a direction :math:`d` by
:math:`\langle \nabla f(x), d \rangle`.
"""
raise NotImplementedError(
'no gradient implemented for functional {!r}'
''.format(self))
@property
def proximal(self):
r"""Proximal factory of the functional.
Notes
-----
The proximal operator of a function :math:`f` is an operator defined as
.. math::
prox_{\sigma f}(x) = \sup_{y} \left\{ f(y) -
\frac{1}{2\sigma} \| y-x \|_2^2 \right\}.
Proximal operators are often used in different optimization algorithms,
especially when designed to handle nonsmooth functionals.
A `proximal factory` is a function that, when called with a step
length :math:`\sigma`, returns the corresponding proximal operator.
The nonsmooth solvers that make use of proximal operators to solve a
given optimization problem take a `proximal factory` as input,
i.e., a function returning a proximal operator. See for example
`forward_backward_pd`.
In general, the step length :math:`\sigma` is expected to be a
positive float, but certain functionals might accept more types of
objects as a stepsize:
- If a functional is a `SeparableSum`, then, instead of a positive
float, one may call the `proximal factory` with a list of positive
floats, and the stepsize are applied to each component individually.
- For certain special functionals like `L1Norm` and `L2NormSquared`,
which are not implemented as a `SeparableSum`, the proximal factory
will accept an argument which is `element-like` regarding the domain
of the functional. Its components must be strictly positive floats.
A stepsize like :math:`(\sigma_1, \ldots, \sigma_n)` coincides
with a matrix-valued distance according to Section XV.4 of [HL1993]
and the rule
.. math::
M = \mathrm{diag}(\sigma_1^{-1}, \ldots, \sigma_n^{-1})
or the Bregman-proximal according to [E1993] and the rule
.. math::
h(x) = \langle x, M x \rangle.
References
----------
[HL1993] Hiriart-Urruty J-B, and Lemaréchal C. *Convex analysis and
minimization algorithms II. Advanced theory and bundle methods.*
Springer, 1993.
[E1993] Eckstein J. *Nonlinear proximal point algorithms using Bregman
functions, with applications to convex programming.* Mathematics of
Operations Research, 18.1 (1993), pp 202--226.
"""
raise NotImplementedError(
'no proximal operator implemented for functional {!r}'
''.format(self))
@property
def convex_conj(self):
r"""Convex conjugate functional of the functional.
Notes
-----
The convex conjugate functional of a convex functional :math:`f(x)`,
defined on a Hilber space, is defined as the functional
.. math::
f^*(x^*) = \sup_{x} \{ \langle x^*,x \rangle - f(x) \}.
The concept is also known as the Legendre transformation.
For literature references see, e.g., [Lue1969], [Roc1970], the
wikipedia article on `Convex conjugate
<https://en.wikipedia.org/wiki/Convex_conjugate>`_ or the wikipedia
article on the `Legendre transformation
<https://en.wikipedia.org/wiki/Legendre_transformation>`_.
References
----------
[Lue1969] Luenberger, D G. *Optimization by vector space methods*.
Wiley, 1969.
[Roc1970] Rockafellar, R. T. *Convex analysis*. Princeton
University Press, 1970.
"""
return FunctionalDefaultConvexConjugate(self)
def derivative(self, point):
"""Return the derivative operator in the given point.
This function returns the linear operator given by::
self.derivative(point)(x) == self.gradient(point).inner(x)
Parameters
----------
point : `domain` element
The point in which the gradient is evaluated.
Returns
-------
derivative : `Operator`
"""
return self.gradient(point).T
def translated(self, shift):
"""Return a translation of the functional.
For a given functional ``f`` and an element ``translation`` in the
domain of ``f``, this operation creates the functional
``f(. - translation)``.
Parameters
----------
translation : `domain` element
Element in the domain of the functional
Returns
-------
out : `FunctionalTranslation`
The functional ``f(. - translation)``
"""
return FunctionalTranslation(self, shift)
def bregman(self, point, subgrad):
r"""Return the Bregman distance functional.
Parameters
----------
point : element of ``functional.domain``
Point from which to define the Bregman distance.
subgrad : element of ``functional.domain``
A subgradient of ``functional`` in ``point``. If it exists, a
valid option is ``functional.gradient(point)``.
Returns
-------
out : `BregmanDistance`
The Bregman distance functional.
Notes
-----
Given a functional :math:`f`, a point :math:`y`, and a (sub)gradient
:math:`p \in \partial f(y)`, the Bregman distance functional
:math:`D_f^p(\cdot, y)` in a point :math:`x` is given by
.. math::
D_f^p(x, y) = f(x) - f(y) - \langle p, x - y \rangle.
For mathematical details, see
`[Bur2016] <https://arxiv.org/abs/1505.05191>`_. See also the Wikipedia
article: https://en.wikipedia.org/wiki/Bregman_divergence
References
----------
[Bur2016] Burger, M. *Bregman Distances in Inverse Problems and Partial
Differential Equation*. In: Advances in Mathematical Modeling,
Optimization and Optimal Control, 2016. p. 3-33.
"""
return BregmanDistance(self, point, subgrad)
def __mul__(self, other):
"""Return ``self * other``.
If ``other`` is an `Operator`, this corresponds to composition with the
operator:
``(func * op)(x) == func(op(x))``
If ``other`` is a scalar, this corresponds to right multiplication of
scalars with functionals:
``(func * scalar)(x) == func(scalar * x)``
If ``other`` is a vector, this corresponds to right multiplication of
vectors with functionals:
``(func * vector) == func(vector * x)``
Note that left and right multiplications are generally different.
Parameters
----------
other : `Operator`, `domain` element or scalar
`Operator`:
The `Operator.range` of ``other`` must match this functional's
`domain`.
`domain` element:
``other`` must be an element of this functionals's
`Functional.domain`.
scalar:
The `domain` of this functional must be a
`LinearSpace` and ``other`` must be an element of the `field`
of this functional's `domain`. Note that this `field` is also this
functional's `range`.
Returns
-------
mul : `Functional`
Multiplication result.
If ``other`` is an `Operator`, ``mul`` is a
`FunctionalComp`.
If ``other`` is a scalar, ``mul`` is a
`FunctionalRightScalarMult`.
If ``other`` is a vector, ``mul`` is a
`FunctionalRightVectorMult`.
"""
if isinstance(other, Operator):
return FunctionalComp(self, other)
elif other in self.range:
# Left multiplication is more efficient, so we can use this in the
# case of linear functional.
if other == 0:
from odl.solvers.functional.default_functionals import (
ConstantFunctional)
return ConstantFunctional(self.domain,
self(self.domain.zero()))
elif self.is_linear:
return FunctionalLeftScalarMult(self, other)
else:
return FunctionalRightScalarMult(self, other)
elif other in self.domain:
return FunctionalRightVectorMult(self, other)
else:
return super(Functional, self).__mul__(other)
def __rmul__(self, other):
"""Return ``other * self``.
If ``other`` is an `Operator`, since a functional is also an operator
this corresponds to operator composition:
``(op * func)(x) == op(func(x))``
If ``other`` is a scalar, this corresponds to left multiplication of
scalars with functionals:
``(scalar * func)(x) == scalar * func(x)``
If ``other`` is a vector, since a functional is also an operator this
corresponds to left multiplication of vectors with operators:
``(vector * func)(x) == vector * func(x)``
Note that left and right multiplications are generally different.
Parameters
----------
other : `Operator`, `domain` element or scalar
`Operator`:
The `Operator.domain` of ``other`` must match this functional's
`Functional.range`.
`LinearSpaceElement`:
``other`` must be an element of this functionals's
`Functional.range`.
scalar:
The `Operator.domain` of this operator must be a
`LinearSpace` and ``other`` must be an
element of the ``field`` of this operator's
`Operator.domain`.
Returns
-------
rmul : `Functional` or `Operator`
Multiplication result.
If ``other`` is an `Operator`, ``rmul`` is an `OperatorComp`.
If ``other`` is a scalar, ``rmul`` is a
`FunctionalLeftScalarMult`.
If ``other`` is a vector, ``rmul`` is a
`OperatorLeftVectorMult`.
"""
if other in self.range:
if other == 0:
from odl.solvers.functional.default_functionals import (
ZeroFunctional)
return ZeroFunctional(self.domain)
else:
return FunctionalLeftScalarMult(self, other)
else:
return super(Functional, self).__rmul__(other)
def __add__(self, other):
"""Return ``self + other``.
If ``other`` is a `Functional`, this corresponds to
``(func1 + func2)(x) == func1(x) + func2(x)``
If ``other`` is a scalar, this corresponds to adding a scalar to the
value of the functional:
``(func + scalar)(x) == func(x) + scalar``
Parameters
----------
other : `Functional` or scalar
`Functional`:
The `Functional.domain` and `Functional.range` of ``other``
must match this functional's `Functional.domain` and
`Functional.range`.
scalar:
The scalar needs to be in this functional's `Functional.range`.
Returns
-------
sum : `Functional`
Addition result.
If ``other`` is in ``Functional.range``, ``sum`` is a
`FunctionalScalarSum`.
If ``other`` is a `Functional`, ``sum`` is a `FunctionalSum`.
"""
if other in self.domain.field:
return FunctionalScalarSum(self, other)
elif isinstance(other, Functional):
return FunctionalSum(self, other)
else:
return super(Functional, self).__add__(other)
# Since addition is commutative, right and left addition is the same
__radd__ = __add__
def __sub__(self, other):
"""Return ``self - other``."""
return self + (-1) * other
class FunctionalLeftScalarMult(Functional, OperatorLeftScalarMult):
"""Scalar multiplication of functional from the left.
Given a functional ``f`` and a scalar ``scalar``, this represents the
functional
``(scalar * f)(x) == scalar * f(x)``.
``Functional.__rmul__`` takes care of the case scalar = 0.
"""
def __init__(self, func, scalar):
"""Initialize a new instance.
Parameters
----------
func : `Functional`
Functional to be scaled.
scalar : float, nonzero
Number with which to scale the functional.
"""
if not isinstance(func, Functional):
raise TypeError('`func` {!r} is not a `Functional` instance'
''.format(func))
Functional.__init__(
self, space=func.domain, linear=func.is_linear,
grad_lipschitz=np.abs(scalar) * func.grad_lipschitz)
OperatorLeftScalarMult.__init__(self, operator=func, scalar=scalar)
@property
def functional(self):
"""The original functional."""
return self.operator
@property
def gradient(self):
"""Gradient operator of the functional."""
return self.scalar * self.functional.gradient
@property
def convex_conj(self):
"""Convex conjugate functional of the scaled functional.
``Functional.__rmul__`` takes care of the case scalar = 0.
"""
if self.scalar <= 0:
raise ValueError('scaling with nonpositive values have no convex '
'conjugate. Current value: {}.'
''.format(self.scalar))
return self.scalar * self.functional.convex_conj * (1.0 / self.scalar)
@property
def proximal(self):
"""Proximal factory of the scaled functional.
``Functional.__rmul__`` takes care of the case scalar = 0
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_const_func
"""
if self.scalar < 0:
raise ValueError('proximal operator of functional scaled with a '
'negative value {} is not well-defined'
''.format(self.scalar))
elif self.scalar == 0:
# Should not get here. `Functional.__rmul__` takes care of the case
# scalar = 0
return proximal_const_func(self.domain)
else:
def proximal_left_scalar_mult(sigma=1.0):
"""Proximal operator for left scalar multiplication.
Parameters
----------
sigma : positive float, optional
Step size parameter. Default: 1.0
"""
return self.functional.proximal(sigma * self.scalar)
return proximal_left_scalar_mult
class FunctionalRightScalarMult(Functional, OperatorRightScalarMult):
"""Scalar multiplication of the argument of functional.
Given a functional ``f`` and a scalar ``scalar``, this represents the
functional
``(f * scalar)(x) == f(scalar * x)``.
`Functional.__mul__` takes care of the case scalar = 0.
"""
def __init__(self, func, scalar):
"""Initialize a new instance.
Parameters
----------
func : `Functional`
The functional which will have its argument scaled.
scalar : float, nonzero
The scaling parameter with which the argument is scaled.
"""
if not isinstance(func, Functional):
raise TypeError('`func` {!r} is not a `Functional` instance'
''.format(func))
scalar = func.domain.field.element(scalar)
Functional.__init__(
self, space=func.domain, linear=func.is_linear,
grad_lipschitz=np.abs(scalar) * func.grad_lipschitz)
OperatorRightScalarMult.__init__(self, operator=func, scalar=scalar)
@property
def functional(self):
"""The original functional."""
return self.operator
@property
def gradient(self):
"""Gradient operator of the functional."""
return self.scalar * self.functional.gradient * self.scalar
@property
def convex_conj(self):
"""Convex conjugate functional of functional with scaled argument.
`Functional.__mul__` takes care of the case scalar = 0.
"""
return self.functional.convex_conj * (1 / self.scalar)
@property
def proximal(self):
"""Proximal factory of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_arg_scaling
"""
return proximal_arg_scaling(self.functional.proximal, self.scalar)
class FunctionalComp(Functional, OperatorComp):
"""Composition of a functional with an operator.
Given a functional ``func`` and an operator ``op``, such that the range of
the operator is equal to the domain of the functional, this corresponds to
the functional
``(func * op)(x) == func(op(x))``.
"""
def __init__(self, func, op):
"""Initialize a new instance.
Parameters
----------
func : `Functional`
The left ("outer") operator
op : `Operator`
The right ("inner") operator. Its range must coincide with the
domain of ``func``.
"""
if not isinstance(func, Functional):
raise TypeError('`fun` {!r} is not a `Functional` instance'
''.format(func))
OperatorComp.__init__(self, left=func, right=op)
Functional.__init__(self, space=op.domain,
linear=(func.is_linear and op.is_linear),
grad_lipschitz=np.nan)
@property
def gradient(self):
"""Gradient of the compositon according to the chain rule."""
func = self.left
op = self.right
class FunctionalCompositionGradient(Operator):
"""Gradient of the compositon according to the chain rule."""
def __init__(self):
"""Initialize a new instance."""
super(FunctionalCompositionGradient, self).__init__(
op.domain, op.domain, linear=False)
def _call(self, x):
"""Apply the gradient operator to the given point."""
return op.derivative(x).adjoint(func.gradient(op(x)))
def derivative(self, x):
"""The derivative in point ``x``.
This is only defined
"""
if not op.is_linear:
raise NotImplementedError('derivative only implemented '
'for linear opertors.')
else:
return (op.adjoint * func.gradient * op).derivative(x)
return FunctionalCompositionGradient()
class FunctionalRightVectorMult(Functional, OperatorRightVectorMult):
"""Expression type for the functional right vector multiplication.
Given a functional ``func`` and a vector ``y`` in the domain of ``func``,
this corresponds to the functional
``(func * y)(x) == func(y * x)``.
"""
def __init__(self, func, vector):
"""Initialize a new instance.
Parameters
----------
func : `Functional`
The domain of ``func`` must be a ``vector.space``.
vector : `domain` element
The vector to multiply by.
"""
if not isinstance(func, Functional):
raise TypeError('`fun` {!r} is not a `Functional` instance'
''.format(func))
OperatorRightVectorMult.__init__(self, operator=func, vector=vector)
Functional.__init__(self, space=func.domain)
@property
def functional(self):
return self.operator
@property
def gradient(self):
"""Gradient operator of the functional."""
return self.vector * self.operator.gradient * self.vector
@property
def convex_conj(self):
"""Convex conjugate functional of the functional.
This is only defined for vectors with no zero-elements.
"""
return self.functional.convex_conj * (1.0 / self.vector)
class FunctionalSum(Functional, OperatorSum):
"""Expression type for the sum of functionals.
``FunctionalSum(func1, func2) == (x --> func1(x) + func2(x))``.
"""
def __init__(self, left, right):
"""Initialize a new instance.
Parameters
----------
left, right : `Functional`
The summands of the functional sum. Their `Functional.domain`
and `Functional.range` must coincide.
"""
if not isinstance(left, Functional):
raise TypeError('`left` {!r} is not a `Functional` instance'
''.format(left))
if not isinstance(right, Functional):
raise TypeError('`right` {!r} is not a `Functional` instance'
''.format(right))
Functional.__init__(
self, space=left.domain,
linear=(left.is_linear and right.is_linear),
grad_lipschitz=left.grad_lipschitz + right.grad_lipschitz)
OperatorSum.__init__(self, left, right)
@property
def gradient(self):
"""Gradient operator of functional sum."""
return self.left.gradient + self.right.gradient
class FunctionalScalarSum(FunctionalSum):
"""Expression type for the sum of a functional and a scalar.
``FunctionalScalarSum(func, scalar) == (x --> func(x) + scalar)``
"""
def __init__(self, func, scalar):
"""Initialize a new instance.
Parameters
----------
func : `Functional`
Functional to which the scalar is added.
scalar : `element` in the `field` of the ``domain``
The scalar to be added to the functional. The `field` of the
``domain`` is the range of the functional.
"""
from odl.solvers.functional.default_functionals import (
ConstantFunctional)
if not isinstance(func, Functional):
raise TypeError('`fun` {!r} is not a `Functional` instance'
''.format(func))
if scalar not in func.range:
raise TypeError('`scalar` {} is not in the range of '
'`func` {!r}'.format(scalar, func))
super(FunctionalScalarSum, self).__init__(
left=func,
right=ConstantFunctional(space=func.domain, constant=scalar))
@property
def scalar(self):
"""The scalar that is added to the functional"""
return self.right.constant
@property
def proximal(self):
"""Proximal factory of the FunctionalScalarSum."""
return self.left.proximal
@property
def convex_conj(self):
"""Convex conjugate functional of FunctionalScalarSum."""
return self.left.convex_conj - self.scalar
class FunctionalTranslation(Functional):
"""Implementation of the translated functional.
Given a functional ``f`` and an element ``translation`` in the domain of
``f``, this corresponds to the functional ``f(. - translation)``.
"""
def __init__(self, func, translation):
"""Initialize a new instance.
Given a functional ``f(.)`` and a vector ``translation`` in the domain
of ``f``, this corresponds to the functional ``f(. - translation)``.
Parameters
----------
func : `Functional`
Functional which is to be translated.
translation : `domain` element
The translation.
"""
if not isinstance(func, Functional):
raise TypeError('`func` {!r} not a `Functional` instance'
''.format(func))
translation = func.domain.element(translation)
super(FunctionalTranslation, self).__init__(
space=func.domain, linear=False,
grad_lipschitz=func.grad_lipschitz)
# TODO: Add case if we have translation -> scaling -> translation?
if isinstance(func, FunctionalTranslation):
self.__functional = func.functional
self.__translation = func.translation + translation
else:
self.__functional = func
self.__translation = translation
@property
def functional(self):
"""The original functional that has been translated."""
return self.__functional
@property
def translation(self):
"""The translation."""
return self.__translation
def _call(self, x):
"""Evaluate the functional in a point ``x``."""
return self.functional(x - self.translation)
@property
def gradient(self):
"""Gradient operator of the functional."""
return (self.functional.gradient *
(IdentityOperator(self.domain) - self.translation))
@property
def proximal(self):
"""Proximal factory of the translated functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_translation
"""
return proximal_translation(self.functional.proximal,
self.translation)
@property
def convex_conj(self):
r"""Convex conjugate functional of the translated functional.
Notes
-----
Given a functional :math:`f`, the convex conjugate of a translated
version :math:`f(\cdot - y)` is given by a linear pertubation of the
convex conjugate of :math:`f`:
.. math::
(f( . - y))^* (x) = f^*(x) + <y, x>.
For reference on the identity used, see [KP2015].
References
----------
[KP2015] Komodakis, N, and Pesquet, J-C. *Playing with Duality: An
overview of recent primal-dual approaches for solving large-scale
optimization problems*. IEEE Signal Processing Magazine, 32.6 (2015),
pp 31--54.
"""
return FunctionalQuadraticPerturb(
self.functional.convex_conj,
linear_term=self.translation)
def __repr__(self):
"""Return ``repr(self)``."""
return '{!r}.translated({!r})'.format(self.functional,
self.translation)
def __str__(self):
"""Return ``str(self)``."""
return '{}.translated({})'.format(self.functional,
self.translation)
class InfimalConvolution(Functional):
"""Functional representing ``h(x) = inf_y f(x-y) + g(y)``."""
def __init__(self, left, right):
"""Initialize a new instance.
Parameters
----------
left : `Functional`
Function corresponding to ``f``.
right : `Functional`
Function corresponding to ``g``.
Examples
--------
>>> space = odl.rn(3)
>>> l1 = odl.solvers.L1Norm(space)
>>> l2 = odl.solvers.L2Norm(space)
>>> f = odl.solvers.InfimalConvolution(l1.convex_conj, l2.convex_conj)
>>> x = f.domain.one()
>>> f.convex_conj(x) - (l1(x) + l2(x))
0.0
"""
if not isinstance(left, Functional):
raise TypeError('`func` {} is not a `Functional` instance'
''.format(left))
if not isinstance(right, Functional):
raise TypeError('`func` {} is not a `Functional` instance'
''.format(right))
super(InfimalConvolution, self).__init__(
space=left.domain, linear=False, grad_lipschitz=np.nan)
self.__left = left
self.__right = right
@property
def left(self):
"""Left functional."""
return self.__left
@property
def right(self):
"""Right functional."""
return self.__right
@property
def convex_conj(self):
"""Convex conjugate functional of the functional.
Notes
-----
The convex conjugate of the infimal convolution
.. math::
h(x) = inf_y f(x-y) + g(y)
is the sum of it:
.. math::
h^*(x) = f^*(x) + g^*(x)
"""
return self.left.convex_conj + self.right.convex_conj
def __repr__(self):
"""Return ``repr(self)``."""
posargs = [self.left, self.right]
inner_str = signature_string(posargs, [], sep=',\n')
return '{}(\n{}\n)'.format(self.__class__.__name__, indent(inner_str))
def __str__(self):
"""Return ``str(self)``."""
return repr(self)
class FunctionalQuadraticPerturb(Functional):
"""The functional representing ``F(.) + a * <., .> + <., u> + c``."""
def __init__(self, func, quadratic_coeff=0, linear_term=None,
constant=0):
"""Initialize a new instance.
Parameters
----------
func : `Functional`
Function corresponding to ``f``.
quadratic_coeff : ``domain.field`` element, optional
Coefficient of the quadratic term. Default: 0.
linear_term : `domain` element, optional
Element in domain of ``func``, corresponding to the translation.
Default: Zero element.
constant : ``domain.field`` element, optional
The constant coefficient. Default: 0.
"""
if not isinstance(func, Functional):
raise TypeError('`func` {} is not a `Functional` instance'
''.format(func))
self.__functional = func
quadratic_coeff = func.domain.field.element(quadratic_coeff)
if quadratic_coeff.imag != 0:
raise ValueError(