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

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

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

35 

36_API_START = api_start(globals()) 

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

38 

39 

40class PowerTrace(Expression): 

41 r"""The trace of the :math:`p`-th power of a hermitian matrix. 

42 

43 :Definition: 

44 

45 Let :math:`p \in \mathbb{Q}`. 

46 

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`. 

49 

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`. 

53 

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)`. 

57 

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)`. 

62 

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`). 

65 

66 .. warning:: 

67 

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. 

71 

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. 

76 

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

81 

82 # -------------------------------------------------------------------------- 

83 # Initialization and factory methods. 

84 # -------------------------------------------------------------------------- 

85 

86 @convert_and_refine_arguments("x") 

87 def __init__(self, x, p, m=None, denominator_limit=1000): 

88 """Construct a :class:`PowerTrace`. 

89 

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

112 

113 # Load p. 

114 pNum, pDen, p, pStr = make_fraction(p, denominator_limit) 

115 

116 # Load m. 

117 if m is not None: 

118 mStr = "m" if len(x) == 1 else "M" 

119 

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

124 

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 

134 

135 if not m.constant: 

136 raise TypeError("The additional factor {} is not constant." 

137 .format(m.string)) 

138 elif not cvxopt_hpsd(m.safe_value_as_matrix): 

139 raise ValueError("The additional factor {} is not hermitian " 

140 "positive semidefinite.".format(m.string)) 

141 

142 self._x = x 

143 self._num = pNum 

144 self._den = pDen 

145 self._m = m 

146 self._limit = denominator_limit 

147 

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

168 

169 Expression.__init__(self, typeStr, symbStr) 

170 

171 # -------------------------------------------------------------------------- 

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

173 # -------------------------------------------------------------------------- 

174 

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 

194 

195 Subtype = namedtuple("Subtype", ("diag", "num", "den", "hasM", "complex")) 

196 

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) 

201 

202 def _get_value(self): 

203 x = cvx2np(self._x._get_value()) 

204 p = self.p 

205 

206 eigenvalues = numpy.linalg.eigvalsh(x) 

207 

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

212 

213 if self._m is None: 

214 trace = sum([value**p for value in eigenvalues]) 

215 else: 

216 m = cvx2np(self._m._get_value()) 

217 

218 U, S, V = numpy.linalg.svd(x) 

219 power = U*numpy.diag(S**p)*V 

220 trace = numpy.trace(m * power) 

221 

222 return cvxopt.matrix(trace) 

223 

224 def _get_mutables(self): 

225 return self._x._get_mutables() 

226 

227 def _is_convex(self): 

228 return self.p >= 1 or self.p <= 0 

229 

230 def _is_concave(self): 

231 return self.p >= 0 and self.p <= 1 

232 

233 def _replace_mutables(self, mapping): 

234 return self.__class__( 

235 self._x._replace_mutables(mapping), self.p, self._m, self._limit) 

236 

237 def _freeze_mutables(self, freeze): 

238 return self.__class__( 

239 self._x._freeze_mutables(freeze), self.p, self._m, self._limit) 

240 

241 # -------------------------------------------------------------------------- 

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

243 # -------------------------------------------------------------------------- 

244 

245 @classmethod 

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

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

248 factor = other.safe_value 

249 

250 if not factor: 

251 return AffineExpression.zero() 

252 elif factor == 1: 

253 return self 

254 elif factor > 0 and self.p >= 0 and self.p <= 1: 

255 if self._m is None: 

256 m = other.dupdiag(self.n).renamed(other.string) 

257 else: 

258 m = other*self._m 

259 

260 return cls(self._x, self.p, m, self._limit) 

261 

262 if forward: 

263 return Expression.__mul__(self, other) 

264 else: 

265 return Expression.__rmul__(self, other) 

266 

267 @convert_operands(scalarRHS=True) 

268 @refine_operands() 

269 def __mul__(self, other): 

270 return PowerTrace._mul(self, other, True) 

271 

272 @convert_operands(scalarRHS=True) 

273 @refine_operands() 

274 def __rmul__(self, other): 

275 return PowerTrace._mul(self, other, False) 

276 

277 # -------------------------------------------------------------------------- 

278 # Methods and properties that return expressions. 

279 # -------------------------------------------------------------------------- 

280 

281 @property 

282 def x(self): 

283 """The matrix concerned.""" 

284 return self._x 

285 

286 # -------------------------------------------------------------------------- 

287 # Methods and properties that describe the expression. 

288 # -------------------------------------------------------------------------- 

289 

290 @property 

291 def n(self): 

292 """Diagonal length of :attr:`x`.""" 

293 return self._x.shape[0] 

294 

295 @property 

296 def p(self): 

297 """The parameter :math:`p`. 

298 

299 This is a limited precision version of the parameter used when the 

300 expression was constructed. 

301 """ 

302 return float(self._num) / float(self._den) 

303 

304 @property 

305 def num(self): 

306 """The limited precision fraction numerator of :math:`p`.""" 

307 return self._num 

308 

309 @property 

310 def den(self): 

311 """The limited precision fraction denominator of :math:`p`.""" 

312 return self._den 

313 

314 @property 

315 def m(self): 

316 """An additional factor to multiply the power with.""" 

317 return self._m 

318 

319 # -------------------------------------------------------------------------- 

320 # Constraint-creating operators, and _predict. 

321 # -------------------------------------------------------------------------- 

322 

323 @classmethod 

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

325 assert isinstance(subtype, cls.Subtype) 

326 

327 p = float(subtype.num) / float(subtype.den) 

328 

329 if relation == operator.__le__: 

330 if p > 0 and p < 1: # Not convex. 

331 return NotImplemented 

332 

333 if issubclass(other.clstype, AffineExpression) \ 

334 and other.subtype.dim == 1: 

335 return PowerTraceConstraint.make_type(*subtype) 

336 elif relation == operator.__ge__: 

337 if p < 0 or p > 1: # Not concave. 

338 return NotImplemented 

339 

340 if issubclass(other.clstype, AffineExpression) \ 

341 and other.subtype.dim == 1: 

342 return PowerTraceConstraint.make_type(*subtype) 

343 

344 return NotImplemented 

345 

346 @convert_operands(scalarRHS=True) 

347 @validate_prediction 

348 @refine_operands() 

349 def __le__(self, other): 

350 if not self.convex: 

351 raise TypeError("Cannot upper-bound a nonconvex (trace of) power.") 

352 

353 if isinstance(other, AffineExpression): 

354 return PowerTraceConstraint(self, Constraint.LE, other) 

355 else: 

356 return NotImplemented 

357 

358 @convert_operands(scalarRHS=True) 

359 @validate_prediction 

360 @refine_operands() 

361 def __ge__(self, other): 

362 if not self.concave: 

363 raise TypeError("Cannot lower-bound a nonconcave (trace of) power.") 

364 

365 if isinstance(other, AffineExpression): 

366 return PowerTraceConstraint(self, Constraint.GE, other) 

367 else: 

368 return NotImplemented 

369 

370 

371# -------------------------------------- 

372__all__ = api_end(_API_START, globals())