Coverage for picos/expressions/exp_geomean.py: 89.66%

87 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-03-26 07:46 +0000

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

21 

22import operator 

23from collections import namedtuple 

24 

25import cvxopt 

26import numpy 

27 

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 

34 

35_API_START = api_start(globals()) 

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

37 

38 

39class GeometricMean(Expression): 

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

41 

42 :Definition: 

43 

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

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

46 

47 .. math:: 

48 

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

50 

51 .. warning:: 

52 

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

56 

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

58 # Initialization and factory methods. 

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

60 

61 @convert_and_refine_arguments("x") 

62 def __init__(self, x): 

63 """Construct a :class:`GeometricMean`. 

64 

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

71 

72 self._x = x 

73 

74 Expression.__init__( 

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

76 

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

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

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

80 

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 

88 

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

90 

91 def _get_subtype(self): 

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

93 

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) 

98 

99 def _get_mutables(self): 

100 return self._x._get_mutables() 

101 

102 def _is_convex(self): 

103 return False 

104 

105 def _is_concave(self): 

106 return True # Only for nonnegative x. 

107 

108 def _replace_mutables(self, mapping): 

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

110 

111 def _freeze_mutables(self, freeze): 

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

113 

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

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

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

117 

118 @classmethod 

119 def _mul(cls, self, other, forward): 

120 if isinstance(other, AffineExpression) and other.constant: 

121 factor = other.safe_value 

122 

123 if not factor: 

124 return AffineExpression.zero() 

125 elif factor == 1: 

126 return self 

127 elif factor > 0: 

128 if forward: 

129 string = glyphs.clever_mul(self.string, other.string) 

130 else: 

131 string = glyphs.clever_mul(other.string, self.string) 

132 

133 product = cls(other*self._x) 

134 product._typeStr = "Scaled " + product._typeStr 

135 product._symbStr = string 

136 

137 return product 

138 

139 if forward: 

140 return Expression.__mul__(self, other) 

141 else: 

142 return Expression.__rmul__(self, other) 

143 

144 @convert_operands(scalarRHS=True) 

145 @refine_operands() 

146 def __mul__(self, other): 

147 return GeometricMean._mul(self, other, True) 

148 

149 @convert_operands(scalarRHS=True) 

150 @refine_operands() 

151 def __rmul__(self, other): 

152 return GeometricMean._mul(self, other, False) 

153 

154 # -------------------------------------------------------------------------- 

155 # Methods and properties that return modified copies. 

156 # -------------------------------------------------------------------------- 

157 

158 @property 

159 def x(self): 

160 """The expression under the mean.""" 

161 return self._x 

162 

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

164 # Constraint-creating operators, and _predict. 

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

166 

167 @classmethod 

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

169 assert isinstance(subtype, cls.Subtype) 

170 

171 if relation == operator.__ge__: 

172 if issubclass(other.clstype, AffineExpression) \ 

173 and other.subtype.dim == 1: 

174 return GeometricMeanConstraint.make_type(subtype.argdim) 

175 

176 return NotImplemented 

177 

178 @convert_operands(scalarRHS=True) 

179 @validate_prediction 

180 @refine_operands() 

181 def __ge__(self, other): 

182 if isinstance(other, AffineExpression): 

183 return GeometricMeanConstraint(self, other) 

184 else: 

185 return NotImplemented 

186 

187 

188# -------------------------------------- 

189__all__ = api_end(_API_START, globals())