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
« 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# ------------------------------------------------------------------------------
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 @classmethod
119 def _mul(cls, self, other, forward):
120 if isinstance(other, AffineExpression) and other.constant:
121 factor = other.safe_value
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)
133 product = cls(other*self._x)
134 product._typeStr = "Scaled " + product._typeStr
135 product._symbStr = string
137 return product
139 if forward:
140 return Expression.__mul__(self, other)
141 else:
142 return Expression.__rmul__(self, other)
144 @convert_operands(scalarRHS=True)
145 @refine_operands()
146 def __mul__(self, other):
147 return GeometricMean._mul(self, other, True)
149 @convert_operands(scalarRHS=True)
150 @refine_operands()
151 def __rmul__(self, other):
152 return GeometricMean._mul(self, other, False)
154 # --------------------------------------------------------------------------
155 # Methods and properties that return modified copies.
156 # --------------------------------------------------------------------------
158 @property
159 def x(self):
160 """The expression under the mean."""
161 return self._x
163 # --------------------------------------------------------------------------
164 # Constraint-creating operators, and _predict.
165 # --------------------------------------------------------------------------
167 @classmethod
168 def _predict(cls, subtype, relation, other):
169 assert isinstance(subtype, cls.Subtype)
171 if relation == operator.__ge__:
172 if issubclass(other.clstype, AffineExpression) \
173 and other.subtype.dim == 1:
174 return GeometricMeanConstraint.make_type(subtype.argdim)
176 return NotImplemented
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
188# --------------------------------------
189__all__ = api_end(_API_START, globals())