Coverage for picos/expressions/exp_powtrace.py : 71.35%

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# ------------------------------------------------------------------------------
20"""Implements :class:`PowerTrace`."""
22import operator
23from collections import namedtuple
25import cvxopt
26import numpy
28from .. import glyphs
29from ..apidoc import api_end, api_start
30from ..constraints import Constraint, PowerTraceConstraint
31from .data import (convert_and_refine_arguments, convert_operands, cvx2np,
32 cvxopt_hpsd, make_fraction)
33from .exp_affine import AffineExpression, ComplexAffineExpression, Constant
34from .expression import Expression, refine_operands, validate_prediction
36_API_START = api_start(globals())
37# -------------------------------
40class PowerTrace(Expression):
41 r"""The trace of the :math:`p`-th power of a hermitian matrix.
43 :Definition:
45 Let :math:`p \in \mathbb{Q}`.
47 1. If the base expressions is a real scalar :math:`x` and no additional
48 constant :math:`m` is given, then this is the power :math:`x^p`.
50 2. If the base expressions is a real scalar :math:`x`,
51 :math:`p \in [0, 1]`, and a positive scalar constant :math:`m` is given,
52 then this is the scaled power :math:`m x^p`.
54 3. If the base expression is a hermitian matrix :math:`X` and no additional
55 constant :math:`M` is given, then this is the trace of power
56 :math:`\operatorname{tr}(X^p)`.
58 4. If the base expression is a hermitian matrix :math:`X`,
59 :math:`p \in [0, 1]`, and a hermitian positive semidefinite constant
60 matrix :math:`M` of same shape as :math:`X` is given, then this is the
61 trace of a scaled power :math:`\operatorname{tr}(M X^p)`.
63 No other case is supported. In particular, if :math:`p \not\in [0, 1]`, then
64 :math:`m`/:math:`M` must be undefined (:obj:`None`).
66 .. warning::
68 1. For a constraint of the form :math:`x^p \leq t` with :math:`p < 1`
69 and :math:`p \neq 0`, PICOS enforces :math:`x \geq 0` during solution
70 search.
72 2. For a constraint of the form :math:`\operatorname{tr}(X^p) \leq t` or
73 :math:`\operatorname{tr}(M X^p) \leq t` with :math:`p < 1` and
74 :math:`p \neq 0`, PICOS enforces :math:`X \succeq 0` during solution
75 search.
77 3. For a constraint of the form :math:`\operatorname{tr}(X^p) \leq t`
78 or :math:`\operatorname{tr}(M X^p) \leq t` with :math:`p > 1`, PICOS
79 enforces :math:`t \geq 0` during solution search.
80 """
82 # --------------------------------------------------------------------------
83 # Initialization and factory methods.
84 # --------------------------------------------------------------------------
86 @convert_and_refine_arguments("x")
87 def __init__(self, x, p, m=None, denominator_limit=1000):
88 """Construct a :class:`PowerTrace`.
90 :param x: The scalar or symmetric matrix to form a power of.
91 :type x: ~picos.expressions.AffineExpression
92 :param float p: The value for :math:`p`, which is cast to a limited
93 precision fraction.
94 :param m: An additional positive semidefinite constant to multiply the
95 power with.
96 :type m: :class:`~picos.expressions.AffineExpression` or anything
97 recognized by :func:`~picos.expressions.data.load_data`
98 :param int denominator_limit: The largest allowed denominator when
99 casting :math:`p` to a fraction. Higher values can yield a greater
100 precision at reduced performance.
101 """
102 # Validate x.
103 if not isinstance(x, ComplexAffineExpression):
104 raise TypeError("Can only form the power of an affine expression, "
105 "not of {}.".format(x.string))
106 elif not x.square:
107 raise TypeError(
108 "Can't form the power of non-square {}.".format(x.string))
109 elif not x.hermitian:
110 raise NotImplementedError("Taking {} to a power is not supported "
111 "as it is not necessarily hermitian.".format(x.string))
113 # Load p.
114 pNum, pDen, p, pStr = make_fraction(p, denominator_limit)
116 # Load m.
117 if m is not None:
118 mStr = "m" if len(x) == 1 else "M"
120 if p < 0 or p > 1:
121 raise ValueError(
122 "p-th power with an additional factor {} requires {}."
123 .format(mStr, glyphs.le(0, glyphs.le("p", 1))))
125 if not isinstance(m, ComplexAffineExpression):
126 try:
127 m = Constant(mStr, m, x.shape)
128 except Exception as error:
129 raise TypeError(
130 "Failed to load the additional factor {} as a matrix of"
131 " same shape as {}.".format(mStr, x.string)) from error
132 else:
133 m = m.refined
135 if not m.constant:
136 raise TypeError("The additional factor {} is not constant."
137 .format(m.string))
138 elif not cvxopt_hpsd(m.value):
139 raise ValueError("The additional factor {} is not hermitian "
140 "positive semidefinite.".format(m.string))
142 self._x = x
143 self._num = pNum
144 self._den = pDen
145 self._m = m
146 self._limit = denominator_limit
148 if m is None:
149 if len(x) == 1:
150 typeStr = "Power"
151 if p == 2:
152 symbStr = glyphs.squared(x.string)
153 elif p == 3:
154 symbStr = glyphs.cubed(x.string)
155 else:
156 symbStr = glyphs.power(x.string, pStr)
157 else:
158 typeStr = "Trace of Power"
159 symbStr = glyphs.trace(glyphs.power(x.string, pStr))
160 else:
161 if len(x) == 1:
162 typeStr = "Scaled Power"
163 symbStr = glyphs.mul(m.string, glyphs.power(x.string, pStr))
164 else:
165 typeStr = "Trace of Scaled Power"
166 symbStr = glyphs.trace(glyphs.mul(
167 m.string, glyphs.power(x.string, pStr)))
169 Expression.__init__(self, typeStr, symbStr)
171 # --------------------------------------------------------------------------
172 # Abstract method implementations and method overridings, except _predict.
173 # --------------------------------------------------------------------------
175 def _get_refined(self):
176 if self._x.constant:
177 return Constant(self._symbStr, self.value)
178 elif self.p == 0:
179 if self._m is not None:
180 return self._m.tr
181 else:
182 return Constant(
183 glyphs.Fn("diaglen({})")(self._x.string), self._x.shape[0])
184 elif self.p == 1:
185 if self._m is not None:
186 # NOTE: No hermitian transpose as both m and x are hermitian.
187 return (self._m | self._x)
188 else:
189 return self._x.tr
190 elif self.p == 2 and self._x.scalar and self._m is None:
191 return (self._x | self._x)
192 else:
193 return self
195 Subtype = namedtuple("Subtype", ("diag", "num", "den", "hasM", "complex"))
197 def _get_subtype(self):
198 return self.Subtype(
199 self._x.shape[0], self._num, self._den, self._m is not None,
200 self._x.complex)
202 def _get_value(self):
203 x = cvx2np(self._x._get_value())
204 p = self.p
206 eigenvalues = numpy.linalg.eigvalsh(x)
208 if p != int(p) and any(value < 0 for value in eigenvalues):
209 raise ArithmeticError("Cannot evaluate {}: {} is not positive "
210 "semidefinite and the exponent is fractional."
211 .format(self.string, self._x.string))
213 if self._m is None:
214 trace = sum([value**p for value in eigenvalues])
215 else:
216 m = cvx2np(self._m._get_value())
218 U, S, V = numpy.linalg.svd(x)
219 power = U*numpy.diag(S**p)*V
220 trace = numpy.trace(m * power)
222 return cvxopt.matrix(trace)
224 def _get_mutables(self):
225 return self._x._get_mutables()
227 def _is_convex(self):
228 return self.p >= 1 or self.p <= 0
230 def _is_concave(self):
231 return self.p >= 0 and self.p <= 1
233 def _replace_mutables(self, mapping):
234 return self.__class__(
235 self._x._replace_mutables(mapping), self.p, self._m, self._limit)
237 def _freeze_mutables(self, freeze):
238 return self.__class__(
239 self._x._freeze_mutables(freeze), self.p, self._m, self._limit)
241 # --------------------------------------------------------------------------
242 # Python special method implementations, except constraint-creating ones.
243 # --------------------------------------------------------------------------
245 @convert_operands(scalarRHS=True)
246 @refine_operands()
247 def __mul__(self, other):
248 if isinstance(other, AffineExpression):
249 if not other.constant:
250 raise NotImplementedError("You may only multiply a nonconstant "
251 "PICOS trace of a power with a constant term.")
253 value = other.value
255 if value < 0:
256 raise NotImplementedError("You may only multiply a nonconstant "
257 "PICOS trace of a power with a nonnegative term.")
259 if value == 1:
260 return self
262 if self._m is None:
263 m = other.dupdiag(self.n).renamed(other.string)
264 else:
265 m = other*self._m
267 return PowerTrace(self._x, self.p, m, self._limit)
268 else:
269 return NotImplemented
271 @convert_operands(scalarRHS=True)
272 @refine_operands()
273 def __rmul__(self, other):
274 if isinstance(other, AffineExpression):
275 return self.__mul__(other)
276 else:
277 return NotImplemented
279 # --------------------------------------------------------------------------
280 # Methods and properties that return expressions.
281 # --------------------------------------------------------------------------
283 @property
284 def x(self):
285 """The matrix concerned."""
286 return self._x
288 # --------------------------------------------------------------------------
289 # Methods and properties that describe the expression.
290 # --------------------------------------------------------------------------
292 @property
293 def n(self):
294 """Diagonal length of :attr:`x`."""
295 return self._x.shape[0]
297 @property
298 def p(self):
299 """The parameter :math:`p`.
301 This is a limited precision version of the parameter used when the
302 expression was constructed.
303 """
304 return float(self._num) / float(self._den)
306 @property
307 def num(self):
308 """The limited precision fraction numerator of :math:`p`."""
309 return self._num
311 @property
312 def den(self):
313 """The limited precision fraction denominator of :math:`p`."""
314 return self._den
316 @property
317 def m(self):
318 """An additional factor to multiply the power with."""
319 return self._m
321 # --------------------------------------------------------------------------
322 # Constraint-creating operators, and _predict.
323 # --------------------------------------------------------------------------
325 @classmethod
326 def _predict(cls, subtype, relation, other):
327 assert isinstance(subtype, cls.Subtype)
329 p = float(subtype.num) / float(subtype.den)
331 if relation == operator.__le__:
332 if p > 0 and p < 1: # Not convex.
333 return NotImplemented
335 if issubclass(other.clstype, AffineExpression) \
336 and other.subtype.dim == 1:
337 return PowerTraceConstraint.make_type(*subtype)
338 elif relation == operator.__ge__:
339 if p < 0 or p > 1: # Not concave.
340 return NotImplemented
342 if issubclass(other.clstype, AffineExpression) \
343 and other.subtype.dim == 1:
344 return PowerTraceConstraint.make_type(*subtype)
346 return NotImplemented
348 @convert_operands(scalarRHS=True)
349 @validate_prediction
350 @refine_operands()
351 def __le__(self, other):
352 if not self.convex:
353 raise TypeError("Cannot upper-bound a nonconvex (trace of) power.")
355 if isinstance(other, AffineExpression):
356 return PowerTraceConstraint(self, Constraint.LE, other)
357 else:
358 return NotImplemented
360 @convert_operands(scalarRHS=True)
361 @validate_prediction
362 @refine_operands()
363 def __ge__(self, other):
364 if not self.concave:
365 raise TypeError("Cannot lower-bound a nonconcave (trace of) power.")
367 if isinstance(other, AffineExpression):
368 return PowerTraceConstraint(self, Constraint.GE, other)
369 else:
370 return NotImplemented
373# --------------------------------------
374__all__ = api_end(_API_START, globals())