r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# ------------------------------------------------------------------------------

2# Copyright (C) 2019 Maximilian Stahlberg

3# Based on the original picos.expressions module by Guillaume Sagnol.

4#

5# This file is part of PICOS.

6#

7# PICOS is free software: you can redistribute it and/or modify it under the

9# Foundation, either version 3 of the License, or (at your option) any later

10# version.

11#

12# PICOS is distributed in the hope that it will be useful, but WITHOUT ANY

13# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR

14# A PARTICULAR PURPOSE. See the GNU General Public License for more details.

15#

16# You should have received a copy of the GNU General Public License along with

17# this program. If not, see <http://www.gnu.org/licenses/>.

18# ------------------------------------------------------------------------------

20"""Implements :class:LogSumExp."""

22import operator

23from collections import namedtuple

25import cvxopt

26import numpy

28from .. import glyphs

29from ..apidoc import api_end, api_start

30from ..caching import cached_property

31from ..constraints import LogSumExpConstraint

32from .data import convert_and_refine_arguments, convert_operands, cvx2np

33from .exp_affine import AffineExpression

34from .expression import Expression, refine_operands, validate_prediction

36_API_START = api_start(globals())

37# -------------------------------

40class LogSumExp(Expression):

41 r"""Logarithm of the sum of elementwise exponentials of an expression.

43 :Definition:

45 For an :math:n-dimensional real affine expression :math:x, this is the

46 logarithm of the sum of elementwise exponentials

48 .. math::

50 \log\sum_{i = 1}^n \exp(\operatorname{vec}(x)_i).

51 """

53 # --------------------------------------------------------------------------

54 # Initialization and factory methods.

55 # --------------------------------------------------------------------------

57 @convert_and_refine_arguments("x")

58 def __init__(self, x):

59 """Construct a :class:LogSumExp.

61 :param x: The affine expression :math:x.

62 :type x: ~picos.expressions.AffineExpression

63 """

64 if not isinstance(x, AffineExpression):

65 raise TypeError("Can only form the logarithm of the sum of "

66 "elementwise exponentials of a real affine expression, not of "

67 "{}.".format(type(x).__name__))

69 self._x = x

71 typeStr = "Logarithm of Sum of Exponentials"

72 symbStr = glyphs.make_function("log", "sum", "exp")(x.string)

74 Expression.__init__(self, typeStr, symbStr)

76 # --------------------------------------------------------------------------

77 # Abstract method implementations and method overridings, except _predict.

78 # --------------------------------------------------------------------------

80 def _get_refined(self):

81 if self._x.constant:

82 return AffineExpression.from_constant(self.value, 1, self._symbStr)

83 elif len(self._x) == 1:

84 return self._x # Don't carry the string for an identity.

85 else:

86 return self

88 Subtype = namedtuple("Subtype", ("argdim"))

90 def _get_subtype(self):

91 return self.Subtype(len(self._x))

93 def _get_value(self):

94 x = numpy.ravel(cvx2np(self._x._get_value()))

95 s = numpy.log(numpy.sum(numpy.exp(x)))

96 return cvxopt.matrix(s)

98 def _get_mutables(self):

99 return self._x._get_mutables()

101 def _is_convex(self):

102 return True

104 def _is_concave(self):

105 return False

107 def _replace_mutables(self, mapping):

108 return self.__class__(self._x._replace_mutables(mapping))

110 def _freeze_mutables(self, freeze):

111 return self.__class__(self._x._freeze_mutables(freeze))

113 # --------------------------------------------------------------------------

114 # Python special method implementations, except constraint-creating ones.

115 # --------------------------------------------------------------------------

117 @convert_operands(scalarRHS=True)

118 @refine_operands()

120 if isinstance(other, AffineExpression):

121 log = LogSumExp(self._x + other)

123 return log

124 else:

125 return NotImplemented

127 @convert_operands(scalarRHS=True)

128 @refine_operands()

130 if isinstance(other, AffineExpression):

132 # NOTE: __add__ always creates a fresh expression.

134 return log

135 else:

136 return NotImplemented

138 @convert_operands(scalarRHS=True)

139 @refine_operands()

140 def __sub__(self, other):

141 if isinstance(other, AffineExpression):

142 log = LogSumExp(self._x - other)

143 log._symbStr = glyphs.clever_sub(self.string, other.string)

144 return log

145 else:

146 return NotImplemented

148 # --------------------------------------------------------------------------

149 # Methods and properties that return expressions.

150 # --------------------------------------------------------------------------

152 @property

153 def x(self):

154 """The expression :math:x."""

155 return self._x

157 @cached_property

158 def exp(self):

159 """The elementwise sum of exponentials of :math:x."""

160 from . import SumExponentials

161 return SumExponentials(self._x)

163 # --------------------------------------------------------------------------

164 # Methods and properties that describe the expression.

165 # --------------------------------------------------------------------------

167 @property

168 def n(self):

169 """Length of :attr:x."""

170 return len(self._x)

172 # --------------------------------------------------------------------------

173 # Constraint-creating operators, and _predict.

174 # --------------------------------------------------------------------------

176 @classmethod

177 def _predict(cls, subtype, relation, other):

178 assert isinstance(subtype, cls.Subtype)

180 if relation == operator.__le__:

181 if issubclass(other.clstype, AffineExpression) \

182 and other.subtype.dim == 1:

183 return LogSumExpConstraint.make_type(subtype.argdim)

185 return NotImplemented

187 @convert_operands(scalarRHS=True)

188 @validate_prediction

189 @refine_operands()

190 def __le__(self, other):

191 if isinstance(other, AffineExpression):

192 return LogSumExpConstraint(self, other)

193 else:

194 return NotImplemented

197# --------------------------------------

198__all__ = api_end(_API_START, globals())