Hide keyboard shortcuts

Hot-keys on this page

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 

8# terms of the GNU General Public License as published by the Free Software 

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# ------------------------------------------------------------------------------ 

19 

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

21 

22import operator 

23from collections import namedtuple 

24 

25import cvxopt 

26import numpy 

27 

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 

35 

36_API_START = api_start(globals()) 

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

38 

39 

40class LogSumExp(Expression): 

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

42 

43 :Definition: 

44 

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

46 logarithm of the sum of elementwise exponentials 

47 

48 .. math:: 

49 

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

51 """ 

52 

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

54 # Initialization and factory methods. 

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

56 

57 @convert_and_refine_arguments("x") 

58 def __init__(self, x): 

59 """Construct a :class:`LogSumExp`. 

60 

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

68 

69 self._x = x 

70 

71 typeStr = "Logarithm of Sum of Exponentials" 

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

73 

74 Expression.__init__(self, typeStr, symbStr) 

75 

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

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

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

79 

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 

87 

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

89 

90 def _get_subtype(self): 

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

92 

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) 

97 

98 def _get_mutables(self): 

99 return self._x._get_mutables() 

100 

101 def _is_convex(self): 

102 return True 

103 

104 def _is_concave(self): 

105 return False 

106 

107 def _replace_mutables(self, mapping): 

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

109 

110 def _freeze_mutables(self, freeze): 

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

112 

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

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

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

116 

117 @convert_operands(scalarRHS=True) 

118 @refine_operands() 

119 def __add__(self, other): 

120 if isinstance(other, AffineExpression): 

121 log = LogSumExp(self._x + other) 

122 log._symbStr = glyphs.clever_add(self.string, other.string) 

123 return log 

124 else: 

125 return NotImplemented 

126 

127 @convert_operands(scalarRHS=True) 

128 @refine_operands() 

129 def __radd__(self, other): 

130 if isinstance(other, AffineExpression): 

131 log = self.__add__(other) 

132 # NOTE: __add__ always creates a fresh expression. 

133 log._symbStr = glyphs.clever_add(other.string, self.string) 

134 return log 

135 else: 

136 return NotImplemented 

137 

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 

147 

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

149 # Methods and properties that return expressions. 

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

151 

152 @property 

153 def x(self): 

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

155 return self._x 

156 

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) 

162 

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

164 # Methods and properties that describe the expression. 

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

166 

167 @property 

168 def n(self): 

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

170 return len(self._x) 

171 

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

173 # Constraint-creating operators, and _predict. 

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

175 

176 @classmethod 

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

178 assert isinstance(subtype, cls.Subtype) 

179 

180 if relation == operator.__le__: 

181 if issubclass(other.clstype, AffineExpression) \ 

182 and other.subtype.dim == 1: 

183 return LogSumExpConstraint.make_type(subtype.argdim) 

184 

185 return NotImplemented 

186 

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 

195 

196 

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

198__all__ = api_end(_API_START, globals())