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:GeometricMean."""

22import operator

23from collections import namedtuple

25import cvxopt

26import numpy

28from .. import glyphs

29from ..apidoc import api_end, api_start

30from ..constraints import GeometricMeanConstraint

31from .data import convert_and_refine_arguments, convert_operands, cvx2np

32from .exp_affine import AffineExpression

33from .expression import Expression, refine_operands, validate_prediction

35_API_START = api_start(globals())

36# -------------------------------

39class GeometricMean(Expression):

40 r"""Geometric mean of an affine expression.

42 :Definition:

44 For an :math:n-dimensional affine expression :math:x with

45 :math:x \geq 0, the geometric mean is given as

47 .. math::

49 \left(\prod_{i = 1}^n x_i \right)^{\frac{1}{n}}.

51 .. warning::

53 When you pose a lower bound on a geometric mean, then PICOS enforces

54 :math:x \geq 0 through an auxiliary constraint during solution search.

55 """

57 # --------------------------------------------------------------------------

58 # Initialization and factory methods.

59 # --------------------------------------------------------------------------

61 @convert_and_refine_arguments("x")

62 def __init__(self, x):

63 """Construct a :class:GeometricMean.

65 :param x: The affine expression to form the geometric mean of.

66 :type x: ~picos.expressions.AffineExpression

67 """

68 if not isinstance(x, AffineExpression):

69 raise TypeError("Can only form the geometrtic mean of a real affine"

70 " expression, not of {}.".format(type(x).__name__))

72 self._x = x

74 Expression.__init__(

75 self, "Geometric Mean", glyphs.make_function("geomean")(x.string))

77 # --------------------------------------------------------------------------

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

79 # --------------------------------------------------------------------------

81 def _get_refined(self):

82 if self._x.constant:

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

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

85 return self._x.renamed(self._symbStr)

86 else:

87 return self

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

91 def _get_subtype(self):

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

94 def _get_value(self):

95 value = self._x._get_value()

96 value = numpy.prod(cvx2np(value))**(1.0 / len(self._x))

97 return cvxopt.matrix(value)

99 def _get_mutables(self):

100 return self._x._get_mutables()

102 def _is_convex(self):

103 return False

105 def _is_concave(self):

106 return True # Only for nonnegative x.

108 def _replace_mutables(self, mapping):

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

111 def _freeze_mutables(self, freeze):

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

114 # --------------------------------------------------------------------------

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

116 # --------------------------------------------------------------------------

118 @convert_operands(scalarRHS=True)

119 @refine_operands()

120 def __mul__(self, other):

121 if isinstance(other, AffineExpression):

122 if not other.constant:

123 raise NotImplementedError("You may only multiply a nonconstant "

124 "PICOS geometric mean with a constant term.")

126 if other.value < 0:

127 raise NotImplementedError("You may only multiply a nonconstant "

128 "PICOS geometric mean with a nonnegative term.")

130 mean = GeometricMean(other.value * self._x)

131 mean._typeStr = "Scaled " + mean._typeStr

132 mean._symbStr = glyphs.clever_mul(self.string, other.string)

133 return mean

134 else:

135 return NotImplemented

137 @convert_operands(scalarRHS=True)

138 @refine_operands()

139 def __rmul__(self, other):

140 if isinstance(other, AffineExpression):

141 mean = self.__mul__(other)

142 # NOTE: __mul__ always creates a fresh expression.

143 mean._symbStr = glyphs.clever_mul(other.string, self.string)

144 return mean

145 else:

146 return NotImplemented

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

149 # Methods and properties that return modified copies.

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

152 @property

153 def x(self):

154 """The expression under the mean."""

155 return self._x

157 # --------------------------------------------------------------------------

158 # Constraint-creating operators, and _predict.

159 # --------------------------------------------------------------------------

161 @classmethod

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

163 assert isinstance(subtype, cls.Subtype)

165 if relation == operator.__ge__:

166 if issubclass(other.clstype, AffineExpression) \

167 and other.subtype.dim == 1:

168 return GeometricMeanConstraint.make_type(subtype.argdim)

170 return NotImplemented

172 @convert_operands(scalarRHS=True)

173 @validate_prediction

174 @refine_operands()

175 def __ge__(self, other):

176 if isinstance(other, AffineExpression):

177 return GeometricMeanConstraint(self, other)

178 else:

179 return NotImplemented

182# --------------------------------------

183__all__ = api_end(_API_START, globals())