-
Notifications
You must be signed in to change notification settings - Fork 2
/
default_functionals.py
2242 lines (1766 loc) · 71.3 KB
/
default_functionals.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
# Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL. If not, see <http://www.gnu.org/licenses/>.
"""Default functionals defined on any space similar to R^n or L^2."""
# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import super
import numpy as np
import scipy
from numbers import Integral
from odl.solvers.functional.functional import Functional
from odl.space import ProductSpace
from odl.operator import (Operator, ConstantOperator, ZeroOperator,
ScalingOperator, DiagonalOperator, PointwiseNorm)
from odl.solvers.functional.functional import (
Functional, FunctionalDefaultConvexConjugate)
from odl.solvers.nonsmooth.proximal_operators import (
proximal_l1, proximal_cconj_l1, proximal_l2, proximal_cconj_l2,
proximal_l2_squared, proximal_const_func, proximal_box_constraint,
proximal_cconj, proximal_cconj_kl, proximal_cconj_kl_cross_entropy,
combine_proximals)
from odl.util import conj_exponent
__all__ = ('LpNorm', 'L1Norm', 'L2Norm', 'L2NormSquared',
'ZeroFunctional', 'ConstantFunctional', 'IndicatorLpUnitBall',
'GroupL1Norm', 'IndicatorGroupL1UnitBall', 'IndicatorZero',
'IndicatorBox', 'IndicatorNonnegativity', 'KullbackLeibler',
'KullbackLeiblerCrossEntropy', 'SeparableSum',
'QuadraticForm',
'NuclearNorm', 'IndicatorNuclearNormUnitBall',
'ScalingFunctional', 'IdentityFunctional',
'MoreauEnvelope')
class LpNorm(Functional):
"""The functional corresponding to the Lp-norm.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^n`-like space, the
:math:`\| \cdot \|_p`-norm is defined as
.. math::
\| x \|_p = \\left(\\sum_{i=1}^n |x_i|^p \\right)^{1/p}.
If the functional is defined on an :math:`L_2`-like space, the
:math:`\| \cdot \|_p`-norm is defined as
.. math::
\| x \|_p = \\left(\\int_\Omega |x(t)|^p dt. \\right)^{1/p}
"""
def __init__(self, space, exponent):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `FnBase`
Domain of the functional.
exponent : float
Exponent for the norm (``p``).
"""
self.exponent = float(exponent)
super().__init__(space=space, linear=False, grad_lipschitz=np.nan)
# TODO: update when integration operator is in place: issue #440
def _call(self, x):
"""Return the Lp-norm of ``x``."""
if self.exponent == 0:
return self.domain.one().inner(np.not_equal(x, 0))
elif self.exponent == 1:
return x.ufuncs.absolute().inner(self.domain.one())
elif self.exponent == 2:
return np.sqrt(x.inner(x))
elif np.isfinite(self.exponent):
tmp = x.ufuncs.absolute()
tmp.ufuncs.power(self.exponent, out=tmp)
return np.power(tmp.inner(self.domain.one()), 1 / self.exponent)
elif self.exponent == np.inf:
return x.ufuncs.absolute().ufuncs.max()
elif self.exponent == -np.inf:
return x.ufuncs.absolute().ufuncs.min()
else:
raise RuntimeError('unknown exponent')
@property
def convex_conj(self):
"""The convex conjugate functional of the Lp-norm."""
return IndicatorLpUnitBall(self.domain,
exponent=conj_exponent(self.exponent))
@property
def proximal(self):
"""Return the proximal factory of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_l1 :
proximal factory for the L1-norm.
odl.solvers.nonsmooth.proximal_operators.proximal_l2 :
proximal factory for the L2-norm.
"""
if self.exponent == 1:
return proximal_l1(space=self.domain)
elif self.exponent == 2:
return proximal_l2(space=self.domain)
else:
raise NotImplementedError('`proximal` only implemented for p=1 or '
'p=2')
@property
def gradient(self):
"""Gradient operator of the functional.
The functional is not differentiable in ``x=0``. However, when
evaluating the gradient operator in this point it will return 0.
"""
functional = self
if self.exponent == 1:
class L1Gradient(Operator):
"""The gradient operator of this functional."""
def __init__(self):
"""Initialize a new instance."""
super().__init__(functional.domain, functional.domain,
linear=False)
def _call(self, x):
"""Apply the gradient operator to the given point."""
return x.ufuncs.sign()
return L1Gradient()
elif self.exponent == 2:
class L2Gradient(Operator):
"""The gradient operator of this functional."""
def __init__(self):
"""Initialize a new instance."""
super().__init__(functional.domain, functional.domain,
linear=False)
def _call(self, x):
"""Apply the gradient operator to the given point.
The gradient is not defined in 0.
"""
norm_of_x = x.norm()
if norm_of_x == 0:
return self.domain.zero()
else:
return x / norm_of_x
return L2Gradient()
else:
raise NotImplementedError('`gradient` only implemented for p=1 or '
'p=2')
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, {!r})'.format(self.__class__.__name__,
self.domain,
self.exponent)
class GroupL1Norm(Functional):
"""The functional corresponding to the mixed L1--Lp norm on `ProductSpace`.
The L1-norm, ``|| ||x||_p ||_1``, is defined as the integral/sum of
``||x||_p``, where ``||x||_p`` is the pointwise p-norm.
This is also known as the cross norm.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^{n \\times m}`-like
space, the group :math:`L_1`-norm, denoted
:math:`\| \\cdot \|_{\\times, p}` is defined as
.. math::
\|F\|_{\\times, p} =
\\sum_{i = 1}^n \\left(\\sum_{j=1}^m |F_{i,j}|^p\\right)^{1/p}
If the functional is defined on an :math:`(\\mathcal{L}^p)^m`-like space,
the group :math:`L_1`-norm is defined as
.. math::
\| F \|_{\\times, p} =
\\int_{\Omega} \\left(\\sum_{j = 1}^m |F_j(x)|^p\\right)^{1/p}
\mathrm{d}x.
"""
def __init__(self, vfspace, exponent=None):
"""Initialize a new instance.
Parameters
----------
vfspace : `ProductSpace`
Space of vector fields on which the operator acts.
It has to be a product space of identical spaces, i.e. a
power space.
exponent : non-zero float, optional
Exponent of the norm in each point. Values between
0 and 1 are currently not supported due to numerical
instability. Infinity gives the supremum norm.
Default: ``vfspace.exponent``, usually 2.
Examples
--------
>>> space = odl.rn(2)
>>> pspace = odl.ProductSpace(space, 2)
>>> op = GroupL1Norm(pspace)
>>> op([[3, 3], [4, 4]])
10.0
Set exponent of inner (p) norm:
>>> op2 = GroupL1Norm(pspace, exponent=1)
>>> op2([[3, 3], [4, 4]])
14.0
"""
if not isinstance(vfspace, ProductSpace):
raise TypeError('`space` must be a `ProductSpace`')
if not vfspace.is_power_space:
raise TypeError('`space.is_power_space` must be `True`')
self.pointwise_norm = PointwiseNorm(vfspace, exponent)
super().__init__(space=vfspace, linear=False, grad_lipschitz=np.nan)
def _call(self, x):
"""Return the group L1-norm of ``x``."""
# TODO: update when integration operator is in place: issue #440
pointwise_norm = self.pointwise_norm(x)
return pointwise_norm.inner(pointwise_norm.space.one())
@property
def gradient(self):
"""Gradient operator of the functional.
The functional is not differentiable in ``x=0``. However, when
evaluating the gradient operator in this point it will return 0.
Notes
-----
The gradient is given by
.. math::
\\left[ \\nabla \| \|f\|_1 \|_1 \\right]_i =
\\frac{f_i}{|f_i|}
.. math::
\\left[ \\nabla \| \|f\|_2 \|_1 \\right]_i =
\\frac{f_i}{\|f\|_2}
else:
.. math::
\\left[ \\nabla || ||f||_p ||_1 \\right]_i =
\\frac{| f_i |^{p-2} f_i}{||f||_p^{p-1}}
"""
functional = self
class GroupL1Gradient(Operator):
"""The gradient operator of the `GroupL1Norm` functional."""
def __init__(self):
"""Initialize a new instance."""
super().__init__(functional.domain, functional.domain,
linear=False)
def _call(self, x):
"""Return ``self(x)``."""
p = functional.pointwise_norm.exponent
if functional.pointwise_norm.exponent == 1:
result = np.abs(x)
np.divide(x, result, out=result, where=result != 0)
return result
elif functional.pointwise_norm.exponent == 2:
result = functional.pointwise_norm(x)
np.divide(x, result, out=result, where=result != 0)
return result
else:
dividend = np.power(np.abs(x), p - 2) * x
divisor = np.power(functional.pointwise_norm(x), p - 1)
np.divide(dividend, divisor, out=divisor,
where=divisor != 0)
return divisor
return GroupL1Gradient()
@property
def proximal(self):
"""Return the ``proximal factory`` of the functional.
See Also
--------
proximal_l1 : `proximal factory` for the L1-norm.
"""
if self.pointwise_norm.exponent == 1:
return proximal_l1(space=self.domain)
elif self.pointwise_norm.exponent == 2:
return proximal_l1(space=self.domain, isotropic=True)
else:
raise NotImplementedError('`proximal` only implemented for p = 1 '
'or 2')
@property
def convex_conj(self):
"""The convex conjugate functional of the group L1-norm."""
conj_exp = conj_exponent(self.pointwise_norm.exponent)
return IndicatorGroupL1UnitBall(self.domain, exponent=conj_exp)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, exponent={})'.format(self.__class__.__name__,
self.domain,
self.pointwise_norm.exponent)
class IndicatorGroupL1UnitBall(Functional):
"""The convex conjugate to the mixed L1--Lp norm on `ProductSpace`.
See Also
--------
GroupL1Norm
"""
def __init__(self, vfspace, exponent=None):
"""Initialize a new instance.
Parameters
----------
vfspace : `ProductSpace`
Space of vector fields on which the operator acts.
It has to be a product space of identical spaces, i.e. a
power space.
exponent : non-zero float, optional
Exponent of the norm in each point. Values between
0 and 1 are currently not supported due to numerical
instability. Infinity gives the supremum norm.
Default: ``vfspace.exponent``, usually 2.
Examples
--------
>>> space = odl.rn(2)
>>> pspace = odl.ProductSpace(space, 2)
>>> op = IndicatorGroupL1UnitBall(pspace)
>>> op([[0.1, 0.5], [0.2, 0.3]])
0
>>> op([[3, 3], [4, 4]])
inf
Set exponent of inner (p) norm:
>>> op2 = IndicatorGroupL1UnitBall(pspace, exponent=1)
"""
if not isinstance(vfspace, ProductSpace):
raise TypeError('`space` must be a `ProductSpace`')
if not vfspace.is_power_space:
raise TypeError('`space.is_power_space` must be `True`')
self.pointwise_norm = PointwiseNorm(vfspace, exponent)
super().__init__(space=vfspace, linear=False, grad_lipschitz=np.nan)
def _call(self, x):
"""Return ``self(x)``."""
x_norm = self.pointwise_norm(x).ufuncs.max()
if x_norm > 1:
return np.inf
else:
return 0
@property
def proximal(self):
"""Return the `proximal factory` of the functional.
See Also
--------
proximal_cconj_l1 : `proximal factory` for the L1-norms convex
conjugate.
"""
if self.pointwise_norm.exponent == np.inf:
return proximal_cconj_l1(space=self.domain)
elif self.pointwise_norm.exponent == 2:
return proximal_cconj_l1(space=self.domain, isotropic=True)
else:
raise NotImplementedError('`proximal` only implemented for p = 1 '
'or 2')
@property
def convex_conj(self):
"""Convex conjugate functional of IndicatorLpUnitBall.
Returns
-------
convex_conj : GroupL1Norm
The convex conjugate is the the group L1-norm.
"""
conj_exp = conj_exponent(self.pointwise_norm.exponent)
return GroupL1Norm(self.domain, exponent=conj_exp)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, exponent={})'.format(self.__class__.__name__,
self.domain,
self.pointwise_norm.exponent)
class IndicatorLpUnitBall(Functional):
"""The indicator function on the unit ball in given the ``Lp`` norm.
It does not implement `gradient` since it is not differentiable everywhere.
Notes
-----
This functional is defined as
.. math::
f(x) = \\left\{ \\begin{array}{ll}
0 & \\text{if } ||x||_{L_p} \\leq 1, \\\\
\\infty & \\text{else,}
\\end{array} \\right.
where :math:`||x||_{L_p}` is the :math:`L_p`-norm, which for finite values
of :math:`p` is defined as
.. math::
\| x \|_{L_p} = \\left( \\int_{\Omega} |x|^p dx \\right)^{1/p},
and for :math:`p = \\infty` it is defined as
.. math::
||x||_{\\infty} = \max_x (|x|).
The functional also allows noninteger and nonpositive values of the
exponent :math:`p`, however in this case :math:`\| x \|_{L_p}` is not a
norm.
"""
def __init__(self, space, exponent):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `FnBase`
Domain of the functional.
exponent : int or infinity
Specifies wich norm to use.
"""
super().__init__(space=space, linear=False)
self.__norm = LpNorm(space, exponent)
self.__exponent = float(exponent)
@property
def exponent(self):
"""Exponent corresponding to the norm."""
return self.__exponent
def _call(self, x):
"""Apply the functional to the given point."""
x_norm = self.__norm(x)
if x_norm > 1:
return np.inf
else:
return 0
@property
def convex_conj(self):
"""The conjugate functional of IndicatorLpUnitBall.
The convex conjugate functional of an ``Lp`` norm, ``p < infty`` is the
indicator function on the unit ball defined by the corresponding dual
norm ``q``, given by ``1/p + 1/q = 1`` and where ``q = infty`` if
``p = 1`` [Roc1970]_. By the Fenchel-Moreau theorem, the convex
conjugate functional of indicator function on the unit ball in ``Lq``
is the corresponding Lp-norm [BC2011]_.
"""
if self.exponent == np.inf:
return L1Norm(self.domain)
elif self.exponent == 2:
return L2Norm(self.domain)
else:
return LpNorm(self.domain, exponent=conj_exponent(self.exponent))
@property
def proximal(self):
"""Return the `proximal factory` of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_cconj_l1 :
`proximal factory` for convex conjuagte of L1-norm.
odl.solvers.nonsmooth.proximal_operators.proximal_cconj_l2 :
`proximal factory` for convex conjuagte of L2-norm.
"""
if self.exponent == np.inf:
return proximal_cconj_l1(space=self.domain)
elif self.exponent == 2:
return proximal_cconj_l2(space=self.domain)
else:
raise NotImplementedError('`gradient` only implemented for p=2 or '
'p=inf')
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r},{!r})'.format(self.__class__.__name__,
self.domain, self.exponent)
class L1Norm(LpNorm):
"""The functional corresponding to L1-norm.
The L1-norm, ``||x||_1``, is defined as the integral/sum of ``|x|``.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^n`-like space, the
:math:`\| \cdot \|_1`-norm is defined as
.. math::
\| x \|_1 = \\sum_{i=1}^n |x_i|.
If the functional is defined on an :math:`L_2`-like space, the
:math:`\| \cdot \|_1`-norm is defined as
.. math::
\| x \|_1 = \\int_\Omega |x(t)| dt.
"""
def __init__(self, space):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `FnBase`
Domain of the functional.
"""
super().__init__(space=space, exponent=1)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r})'.format(self.__class__.__name__,
self.domain)
class L2Norm(LpNorm):
"""The functional corresponding to the L2-norm.
The L2-norm, ``||x||_2``, is defined as the square-root out of the
integral/sum of ``x^2``.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^n`-like space, the
:math:`\| \cdot \|_2`-norm is defined as
.. math::
\| x \|_2 = \\sqrt{ \\sum_{i=1}^n |x_i|^2 }.
If the functional is defined on an :math:`L_2`-like space, the
:math:`\| \cdot \|_2`-norm is defined as
.. math::
\| x \|_2 = \\sqrt{ \\int_\Omega |x(t)|^2 dt. }
"""
def __init__(self, space):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `FnBase`
Domain of the functional.
"""
super().__init__(space=space, exponent=2)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r})'.format(self.__class__.__name__,
self.domain)
class L2NormSquared(Functional):
"""The functional corresponding to the squared L2-norm.
The squared L2-norm, ``||x||_2^2``, is defined as the integral/sum of
``x^2``.
Notes
-----
If the functional is defined on an :math:`\mathbb{R}^n`-like space, the
:math:`\| \cdot \|_2^2`-functional is defined as
.. math::
\| x \|_2^2 = \\sum_{i=1}^n |x_i|^2.
If the functional is defined on an :math:`L_2`-like space, the
:math:`\| \cdot \|_2^2`-functional is defined as
.. math::
\| x \|_2^2 = \\int_\Omega |x(t)|^2 dt.
"""
def __init__(self, space):
"""Initialize a new instance.
Parameters
----------
space : `DiscreteLp` or `FnBase`
Domain of the functional.
"""
super().__init__(space=space, linear=False, grad_lipschitz=2)
# TODO: update when integration operator is in place: issue #440
def _call(self, x):
"""Return the squared L2-norm of ``x``."""
return x.inner(x)
@property
def gradient(self):
"""Gradient operator of the functional."""
return ScalingOperator(self.domain, 2.0)
@property
def proximal(self):
"""Return the `proximal factory` of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_l2_squared :
`proximal factory` for the squared L2-norm.
"""
return proximal_l2_squared(space=self.domain)
@property
def convex_conj(self):
"""The convex conjugate functional of the squared L2-norm.
Notes
-----
The conjugate functional of :math:`\| \\cdot \|_2^2` is
:math:`\\frac{1}{4}\| \\cdot \|_2^2`
"""
return (1.0 / 4) * L2NormSquared(self.domain)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r})'.format(self.__class__.__name__, self.domain)
class ConstantFunctional(Functional):
"""The constant functional.
This functional maps all elements in the domain to a given, constant value.
"""
def __init__(self, space, constant):
"""Initialize a new instance.
Parameters
----------
space : `LinearSpace`
Domain of the functional.
constant : element in ``domain.field``
The constant value of the functional
"""
super().__init__(space=space, linear=(constant == 0), grad_lipschitz=0)
self.__constant = self.range.element(constant)
@property
def constant(self):
"""The constant value of the functional."""
return self.__constant
def _call(self, x):
"""Return a constant value."""
return self.constant
@property
def gradient(self):
"""Gradient operator of the functional."""
return ZeroOperator(self.domain)
@property
def proximal(self):
"""Return the `proximal factory` of the functional."""
return proximal_const_func(self.domain)
@property
def convex_conj(self):
"""Convex conjugate functional of the constant functional.
Notes
-----
This functional is defined as
.. math::
f^*(x) = \\left\{ \\begin{array}{ll}
-constant & \\text{if } x = 0, \\\\
\\infty & \\text{else}
\\end{array} \\right.
"""
return IndicatorZero(self.domain, -self.constant)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, {!r})'.format(self.__class__.__name__,
self.domain, self.constant)
class ZeroFunctional(ConstantFunctional):
"""Functional that maps all elements in the domain to zero."""
def __init__(self, space):
"""Initialize a new instance.
Parameters
----------
space : `LinearSpace`
Domain of the functional.
"""
super().__init__(space=space, constant=0)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r})'.format(self.__class__.__name__, self.domain)
class ScalingFunctional(Functional, ScalingOperator):
"""Functional that scales the input argument by a value.
Since the range of a functional is always a field, the domain of this
functional is also a field, i.e. real or complex numbers.
"""
def __init__(self, field, scale):
"""Initialize a new instance.
Parameters
----------
field : `Field`
Domain of the functional.
scale : element in ``domain``
The constant value to scale by.
Examples
--------
>>> import odl
>>> field = odl.RealNumbers()
>>> func = ScalingFunctional(field, 3)
>>> func(5)
15.0
"""
Functional.__init__(self, space=field, linear=True, grad_lipschitz=0)
ScalingOperator.__init__(self, field, scale)
@property
def gradient(self):
"""Gradient operator of the functional."""
return ConstantFunctional(self.domain, self.scalar)
class IdentityFunctional(ScalingFunctional):
"""Functional that maps a scalar to itself.
See Also
--------
IdentityOperator
"""
def __init__(self, field):
"""Initialize a new instance.
Parameters
----------
field : `Field`
Domain of the functional.
"""
ScalingFunctional.__init__(self, field, 1.0)
class IndicatorBox(Functional):
"""Indicator on some box shaped domain.
Notes
-----
The indicator :math:`F` with lower bound :math:`a` and upper bound
:math:`b` is defined as:
.. math::
F(x) = \\begin{cases}
0 & \\text{if } a \\leq x \\leq b \\text{ everywhere}, \\\\
\\infty & \\text{else}
\\end{cases}
"""
def __init__(self, space, lower=None, upper=None):
"""Initialize an instance.
Parameters
----------
space : `LinearSpace`
Domain of the functional.
lower : ``space.field`` element or ``space`` `element-like`, optional
The lower bound.
Default: ``None``, interpreted as -infinity
upper : ``space.field`` element or ``space`` `element-like`, optional
The upper bound.
Default: ``None``, interpreted as +infinity
Examples
--------
>>> space = odl.rn(3)
>>> func = IndicatorBox(space, 0, 2)
>>> func([0, 1, 2]) # all points inside
0
>>> func([0, 1, 3]) # one point outside
inf
"""
Functional.__init__(self, space, linear=False)
self.lower = lower
self.upper = upper
def _call(self, x):
"""Apply the functional to the given point."""
# Compute the projection of x onto the box, if this is equal to x we
# know x is inside the box.
tmp = self.domain.element()
if self.lower is not None and self.upper is None:
x.ufuncs.maximum(self.lower, out=tmp)
elif self.lower is None and self.upper is not None:
x.ufuncs.minimum(self.upper, out=tmp)
elif self.lower is not None and self.upper is not None:
x.ufuncs.maximum(self.lower, out=tmp)
tmp.ufuncs.minimum(self.upper, out=tmp)
else:
tmp.assign(x)
return np.inf if x.dist(tmp) > 0 else 0
@property
def proximal(self):
"""Return the `proximal factory` of the functional."""
return proximal_box_constraint(self.domain, self.lower, self.upper)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r}, {!r}, {!r})'.format(self.__class__.__name__,
self.domain,
self.lower, self.upper)
class IndicatorNonnegativity(IndicatorBox):
"""Indicator on the set of non-negative numbers.
Notes
-----
The nonnegativity indicator :math:`F` is defined as:
.. math::
F(x) = \\begin{cases}
0 & \\text{if } 0 \\leq x \\text{ everywhere}, \\\\
\\infty & \\text{else}
\\end{cases}
"""
def __init__(self, space):
"""Initialize an instance.
Parameters
----------
space : `LinearSpace`
Domain of the functional.
Examples
--------
>>> space = odl.rn(3)
>>> func = IndicatorNonnegativity(space)
>>> func([0, 1, 2]) # all points positive
0
>>> func([0, 1, -3]) # one point negative
inf
"""
IndicatorBox.__init__(self, space, lower=0, upper=None)
def __repr__(self):
"""Return ``repr(self)``."""
return '{}({!r})'.format(self.__class__.__name__, self.domain)
class IndicatorZero(Functional):
"""The indicator function of the singleton set {0}.
The function has a constant value if the input is zero, otherwise infinity.
"""
def __init__(self, space, constant=0):
"""Initialize a new instance.
Parameters
----------
space : `LinearSpace`
Domain of the functional.
constant : element in ``domain.field``, optional
The constant value of the functional
Examples
--------
>>> space = odl.rn(3)
>>> func = IndicatorZero(space)
>>> func([0, 0, 0])
0
>>> func([0, 0, 1])
inf
>>> func = IndicatorZero(space, constant=2)
>>> func([0, 0, 0])
2
"""
self.__constant = constant
super().__init__(space, linear=False)
@property
def constant(self):
"""The constant value of the functional if ``x=0``."""
return self.__constant
def _call(self, x):
"""Apply the functional to the given point."""
if x.norm() == 0:
# In this case x is the zero-element.
return self.constant
else:
return np.inf
@property
def convex_conj(self):
"""The convex conjugate functional.
Notes
-----
By the Fenchel-Moreau theorem the convex conjugate is the constant
functional [BC2011]_ with the constant value of -`constant`.
"""
return ConstantFunctional(self.domain, -self.constant)
@property
def proximal(self):
"""Return the proximal factory of the functional.
This is the zero operator.
"""
def zero_proximal(sigma=1.0):
"""Proximal factory for zero operator.
Parameters
----------
sigma : positive float, optional
Step size parameter.
"""
return ZeroOperator(self.domain)