Hide keyboard shortcuts

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"""Implement the GeometricProgram class""" 

2import sys 

3import warnings 

4from time import time 

5from collections import defaultdict 

6import numpy as np 

7from ..repr_conventions import lineagestr 

8from ..small_classes import CootMatrix, SolverLog, Numbers, FixedScalar 

9from ..keydict import KeyDict 

10from ..solution_array import SolutionArray 

11from .set import ConstraintSet 

12from ..exceptions import (InvalidPosynomial, Infeasible, UnknownInfeasible, 

13 PrimalInfeasible, DualInfeasible, UnboundedGP, 

14 InvalidLicense) 

15 

16 

17DEFAULT_SOLVER_KWARGS = {"cvxopt": {"kktsolver": "ldl"}} 

18SOLUTION_TOL = {"cvxopt": 1e-3, "mosek_cli": 1e-4, "mosek_conif": 1e-3} 

19 

20 

21class MonoEqualityIndexes: 

22 "Class to hold MonoEqualityIndexes" 

23 

24 def __init__(self): 

25 self.all = set() 

26 self.first_half = set() 

27 

28 

29def _get_solver(solver, kwargs): 

30 """Get the solverfn and solvername associated with solver""" 

31 if solver is None: 

32 from .. import settings 

33 try: 

34 solver = settings["default_solver"] 

35 except KeyError: 

36 raise ValueError("No default solver was set during build, so" 

37 " solvers must be manually specified.") 

38 if solver == "cvxopt": 

39 from ..solvers.cvxopt import optimize 

40 elif solver == "mosek_cli": 

41 from ..solvers.mosek_cli import optimize_generator 

42 optimize = optimize_generator(**kwargs) 

43 elif solver == "mosek_conif": 

44 from ..solvers.mosek_conif import optimize 

45 elif hasattr(solver, "__call__"): 

46 solver, optimize = solver.__name__, solver 

47 else: 

48 raise ValueError("Unknown solver '%s'." % solver) 

49 return solver, optimize 

50 

51 

52class GeometricProgram: 

53 # pylint: disable=too-many-instance-attributes 

54 """Standard mathematical representation of a GP. 

55 

56 Attributes with side effects 

57 ---------------------------- 

58 `solver_out` and `solve_log` are set during a solve 

59 `result` is set at the end of a solve if solution status is optimal 

60 

61 Examples 

62 -------- 

63 >>> gp = gpkit.constraints.gp.GeometricProgram( 

64 # minimize 

65 x, 

66 [ # subject to 

67 x >= 1, 

68 ], {}) 

69 >>> gp.solve() 

70 """ 

71 _result = solve_log = solver_out = model = v_ss = nu_by_posy = None 

72 

73 def __init__(self, cost, constraints, substitutions, *, checkbounds=True): 

74 self.cost, self.substitutions = cost, substitutions 

75 for key, sub in self.substitutions.items(): 

76 if isinstance(sub, FixedScalar): 

77 sub = sub.value 

78 if hasattr(sub, "units"): 

79 sub = sub.to(key.units or "dimensionless").magnitude 

80 self.substitutions[key] = sub 

81 if not isinstance(sub, (Numbers, np.ndarray)): 

82 raise TypeError("substitution {%s: %s} has invalid value type" 

83 " %s." % (key, sub, type(sub))) 

84 cost_hmap = cost.hmap.sub(self.substitutions, cost.vks) 

85 if any(c <= 0 for c in cost_hmap.values()): 

86 raise InvalidPosynomial("a GP's cost must be Posynomial") 

87 hmapgen = ConstraintSet.as_hmapslt1(constraints, self.substitutions) 

88 self.hmaps = [cost_hmap] + list(hmapgen) 

89 self.gen() # Generate various maps into the posy- and monomials 

90 if checkbounds: 

91 self.check_bounds(err_on_missing_bounds=True) 

92 

93 def check_bounds(self, *, err_on_missing_bounds=False): 

94 "Checks if any variables are unbounded, through equality constraints." 

95 missingbounds = {} 

96 for var, locs in self.varlocs.items(): 

97 upperbound, lowerbound = False, False 

98 for i in locs: 

99 if i not in self.meq_idxs.all: 

100 if self.exps[i][var] > 0: # pylint:disable=simplifiable-if-statement 

101 upperbound = True 

102 else: 

103 lowerbound = True 

104 if upperbound and lowerbound: 

105 break 

106 if not upperbound: 

107 missingbounds[(var, "upper")] = "." 

108 if not lowerbound: 

109 missingbounds[(var, "lower")] = "." 

110 if not missingbounds: 

111 return {} # all bounds found in inequalities 

112 meq_bounds = gen_meq_bounds(missingbounds, self.exps, self.meq_idxs) 

113 fulfill_meq_bounds(missingbounds, meq_bounds) 

114 if missingbounds and err_on_missing_bounds: 

115 raise UnboundedGP( 

116 "\n\n".join("%s has no %s bound%s" % (v, b, x) 

117 for (v, b), x in missingbounds.items())) 

118 return missingbounds 

119 

120 def gen(self): 

121 """Generates nomial and solve data (A, p_idxs) from posynomials. 

122 

123 k [posys]: number of monomials (rows of A) present in each constraint 

124 m_idxs [mons]: monomial indices of each posynomial 

125 p_idxs [mons]: posynomial index of each monomial 

126 cs, exps [mons]: coefficient and exponents of each monomial 

127 varlocs: {vk: monomial indices of each variables' location} 

128 meq_idxs: {all indices of equality mons} and {the first index of each} 

129 varidxs: {vk: which column corresponds to it in A} 

130 A [mons, vks]: sparse array of each monomials' variables' exponents 

131 

132 """ 

133 self.k = [len(hmap) for hmap in self.hmaps] 

134 self.m_idxs, self.p_idxs, self.cs, self.exps = [], [], [], [] 

135 self.varkeys = self.varlocs = defaultdict(list) 

136 self.meq_idxs = MonoEqualityIndexes() 

137 m_idx = 0 

138 row, col, data = [], [], [] 

139 for p_idx, (N_mons, hmap) in enumerate(zip(self.k, self.hmaps)): 

140 self.p_idxs.extend([p_idx]*N_mons) 

141 self.m_idxs.append(slice(m_idx, m_idx+N_mons)) 

142 if getattr(self.hmaps[p_idx], "from_meq", False): 

143 self.meq_idxs.all.add(m_idx) 

144 if len(self.meq_idxs.all) > 2*len(self.meq_idxs.first_half): 

145 self.meq_idxs.first_half.add(m_idx) 

146 self.exps.extend(hmap) 

147 self.cs.extend(hmap.values()) 

148 for exp in hmap: 

149 if not exp: # space out A matrix with constants for mosek 

150 row.append(m_idx) 

151 col.append(0) 

152 data.append(0) 

153 for var in exp: 

154 self.varlocs[var].append(m_idx) 

155 m_idx += 1 

156 self.p_idxs = np.array(self.p_idxs, "int32") # to use array equalities 

157 self.varidxs = {vk: i for i, vk in enumerate(self.varlocs)} 

158 for j, (var, locs) in enumerate(self.varlocs.items()): 

159 row.extend(locs) 

160 col.extend([j]*len(locs)) 

161 data.extend(self.exps[i][var] for i in locs) 

162 self.A = CootMatrix(row, col, data) 

163 

164 # pylint: disable=too-many-statements, too-many-locals 

165 def solve(self, solver=None, *, verbosity=1, gen_result=True, **kwargs): 

166 """Solves a GeometricProgram and returns the solution. 

167 

168 Arguments 

169 --------- 

170 solver : str or function (optional) 

171 By default uses a solver found during installation. 

172 If "mosek_conif", "mosek_cli", or "cvxopt", uses that solver. 

173 If a function, passes that function cs, A, p_idxs, and k. 

174 verbosity : int (default 1) 

175 If greater than 0, prints solver name and solve time. 

176 gen_result : bool (default True) 

177 If True, makes a human-readable SolutionArray from solver output. 

178 **kwargs : 

179 Passed to solver constructor and solver function. 

180 

181 

182 Returns 

183 ------- 

184 SolutionArray (or dict if gen_result is False) 

185 """ 

186 solvername, solverfn = _get_solver(solver, kwargs) 

187 if verbosity > 0: 

188 print("Using solver '%s'" % solvername) 

189 print(" for %i free variables" % len(self.varlocs)) 

190 print(" in %i posynomial inequalities." % len(self.k)) 

191 

192 solverargs = DEFAULT_SOLVER_KWARGS.get(solvername, {}) 

193 solverargs.update(kwargs) 

194 starttime = time() 

195 solver_out, infeasibility, original_stdout = {}, None, sys.stdout 

196 try: 

197 sys.stdout = SolverLog(original_stdout, verbosity=verbosity-2) 

198 solver_out = solverfn(c=self.cs, A=self.A, meq_idxs=self.meq_idxs, 

199 k=self.k, p_idxs=self.p_idxs, **solverargs) 

200 except Infeasible as e: 

201 infeasibility = e 

202 except InvalidLicense as e: 

203 raise InvalidLicense("license for solver \"%s\" is invalid." 

204 % solvername) from e 

205 except Exception as e: 

206 raise UnknownInfeasible("Something unexpected went wrong.") from e 

207 finally: 

208 self.solve_log = "\n".join(sys.stdout) 

209 sys.stdout = original_stdout 

210 self.solver_out = solver_out 

211 

212 solver_out["solver"] = solvername 

213 solver_out["soltime"] = time() - starttime 

214 if verbosity > 0: 

215 print("Solving took %.3g seconds." % solver_out["soltime"]) 

216 

217 if infeasibility: 

218 if isinstance(infeasibility, PrimalInfeasible): 

219 msg = ("The model had no feasible points; " 

220 "you may wish to relax some constraints or constants.") 

221 elif isinstance(infeasibility, DualInfeasible): 

222 msg = ("The model ran to an infinitely low cost;" 

223 " bounding the right variables would prevent this.") 

224 elif isinstance(infeasibility, UnknownInfeasible): 

225 msg = ("Solver failed for an unknown reason. Relaxing" 

226 " constraints/constants, bounding variables, or" 

227 " using a different solver might fix it.") 

228 if (verbosity > 0 and solver_out["soltime"] < 1 

229 and hasattr(self, "model")): # fast, top-level model 

230 print(msg + "\nSince the model solved in less than a second," 

231 " let's run `.debug()` to analyze what happened.\n`") 

232 return self.model.debug(solver=solver) 

233 # else, raise a clarifying error 

234 msg += (" Running `.debug()` or increasing verbosity may pinpoint" 

235 " the trouble.") 

236 raise infeasibility.__class__(msg) from infeasibility 

237 

238 if not gen_result: 

239 return solver_out 

240 # else, generate a human-readable SolutionArray 

241 self._result = self.generate_result(solver_out, verbosity=verbosity-2) 

242 return self.result 

243 

244 @property 

245 def result(self): 

246 "Creates and caches a result from the raw solver_out" 

247 if not self._result: 

248 self._result = self.generate_result(self.solver_out) 

249 return self._result 

250 

251 def generate_result(self, solver_out, *, verbosity=0, dual_check=True): 

252 "Generates a full SolutionArray and checks it." 

253 if verbosity > 0: 

254 soltime = solver_out["soltime"] 

255 tic = time() 

256 # result packing # 

257 result = self._compile_result(solver_out) # NOTE: SIDE EFFECTS 

258 if verbosity > 0: 

259 print("Result packing took %.2g%% of solve time." % 

260 ((time() - tic) / soltime * 100)) 

261 tic = time() 

262 # solution checking # 

263 try: 

264 tol = SOLUTION_TOL.get(solver_out["solver"], 1e-5) 

265 self.check_solution(result["cost"], solver_out['primal'], 

266 solver_out["nu"], solver_out["la"], tol) 

267 except Infeasible as chkerror: 

268 chkwarn = str(chkerror) 

269 if not ("Dual" in chkwarn and not dual_check): 

270 print("Solution check warning: %s" % chkwarn) 

271 if verbosity > 0: 

272 print("Solution checking took %.2g%% of solve time." % 

273 ((time() - tic) / soltime * 100)) 

274 return result 

275 

276 def _generate_nula(self, solver_out): 

277 if "nu" in solver_out: 

278 # solver gave us monomial sensitivities, generate posynomial ones 

279 solver_out["nu"] = nu = np.ravel(solver_out["nu"]) 

280 nu_by_posy = [nu[mi] for mi in self.m_idxs] 

281 solver_out["la"] = la = np.array([sum(nup) for nup in nu_by_posy]) 

282 elif "la" in solver_out: 

283 la = np.ravel(solver_out["la"]) 

284 if len(la) == len(self.hmaps) - 1: 

285 # assume solver dropped the cost's sensitivity (always 1.0) 

286 la = np.hstack(([1.0], la)) 

287 # solver gave us posynomial sensitivities, generate monomial ones 

288 solver_out["la"] = la 

289 z = np.log(self.cs) + self.A.dot(solver_out["primal"]) 

290 m_iss = [self.p_idxs == i for i in range(len(la))] 

291 nu_by_posy = [la[p_i]*np.exp(z[m_is])/sum(np.exp(z[m_is])) 

292 for p_i, m_is in enumerate(m_iss)] 

293 solver_out["nu"] = np.hstack(nu_by_posy) 

294 else: 

295 raise RuntimeWarning("The dual solution was not returned.") 

296 return la, nu_by_posy 

297 

298 def _compile_result(self, solver_out): 

299 result = {"cost": float(solver_out["objective"])} 

300 primal = solver_out["primal"] 

301 if len(self.varlocs) != len(primal): 

302 raise RuntimeWarning("The primal solution was not returned.") 

303 result["freevariables"] = KeyDict(zip(self.varlocs, np.exp(primal))) 

304 result["constants"] = KeyDict(self.substitutions) 

305 result["variables"] = KeyDict(result["freevariables"]) 

306 result["variables"].update(result["constants"]) 

307 result["sensitivities"] = {"constraints": {}} 

308 la, self.nu_by_posy = self._generate_nula(solver_out) 

309 cost_senss = sum(nu_i*exp for (nu_i, exp) in zip(self.nu_by_posy[0], 

310 self.cost.hmap)) 

311 gpv_ss = cost_senss.copy() 

312 m_senss = defaultdict(float) 

313 for las, nus, c in zip(la[1:], self.nu_by_posy[1:], self.hmaps[1:]): 

314 while getattr(c, "parent", None) is not None: 

315 c = c.parent 

316 v_ss, c_senss = c.sens_from_dual(las, nus, result) 

317 for vk, x in v_ss.items(): 

318 gpv_ss[vk] = x + gpv_ss.get(vk, 0) 

319 while getattr(c, "generated_by", None): 

320 c = c.generated_by 

321 result["sensitivities"]["constraints"][c] = abs(c_senss) 

322 m_senss[lineagestr(c)] += abs(c_senss) 

323 # add fixed variables sensitivities to models 

324 for vk, senss in gpv_ss.items(): 

325 m_senss[lineagestr(vk)] += abs(senss) 

326 result["sensitivities"]["models"] = dict(m_senss) 

327 # carry linked sensitivities over to their constants 

328 for v in list(v for v in gpv_ss if v.gradients): 

329 dlogcost_dlogv = gpv_ss.pop(v) 

330 val = np.array(result["constants"][v]) 

331 for c, dv_dc in v.gradients.items(): 

332 with warnings.catch_warnings(): # skip pesky divide-by-zeros 

333 warnings.simplefilter("ignore") 

334 dlogv_dlogc = dv_dc * result["constants"][c]/val 

335 gpv_ss[c] = gpv_ss.get(c, 0) + dlogcost_dlogv*dlogv_dlogc 

336 if v in cost_senss: 

337 if c in self.cost.vks: 

338 dlogcost_dlogv = cost_senss.pop(v) 

339 before = cost_senss.get(c, 0) 

340 cost_senss[c] = before + dlogcost_dlogv*dlogv_dlogc 

341 result["sensitivities"]["cost"] = cost_senss 

342 result["sensitivities"]["variables"] = KeyDict(gpv_ss) 

343 result["sensitivities"]["constants"] = \ 

344 result["sensitivities"]["variables"] # NOTE: backwards compat. 

345 result["soltime"] = solver_out["soltime"] 

346 return SolutionArray(result) 

347 

348 def check_solution(self, cost, primal, nu, la, tol, abstol=1e-20): 

349 """Run checks to mathematically confirm solution solves this GP 

350 

351 Arguments 

352 --------- 

353 cost: float 

354 cost returned by solver 

355 primal: list 

356 primal solution returned by solver 

357 nu: numpy.ndarray 

358 monomial lagrange multiplier 

359 la: numpy.ndarray 

360 posynomial lagrange multiplier 

361 

362 Raises 

363 ------ 

364 Infeasible if any problems are found 

365 """ 

366 A = self.A.tocsr() 

367 def almost_equal(num1, num2): 

368 "local almost equal test" 

369 return (num1 == num2 or abs((num1 - num2) / (num1 + num2)) < tol 

370 or abs(num1 - num2) < abstol) 

371 # check primal sol # 

372 primal_exp_vals = self.cs * np.exp(A.dot(primal)) # c*e^Ax 

373 if not almost_equal(primal_exp_vals[self.m_idxs[0]].sum(), cost): 

374 raise Infeasible("Primal solution computed cost did not match" 

375 " solver-returned cost: %s vs %s." % 

376 (primal_exp_vals[self.m_idxs[0]].sum(), cost)) 

377 for mi in self.m_idxs[1:]: 

378 if primal_exp_vals[mi].sum() > 1 + tol: 

379 raise Infeasible("Primal solution violates constraint: %s is " 

380 "greater than 1" % primal_exp_vals[mi].sum()) 

381 # check dual sol # 

382 # note: follows dual formulation in section 3.1 of 

383 # http://web.mit.edu/~whoburg/www/papers/hoburg_phd_thesis.pdf 

384 if not almost_equal(self.nu_by_posy[0].sum(), 1): 

385 raise Infeasible("Dual variables associated with objective sum" 

386 " to %s, not 1" % self.nu_by_posy[0].sum()) 

387 if any(nu < 0): 

388 minnu = min(nu) 

389 if minnu < -tol/1000: 

390 raise Infeasible("Dual solution has negative entries as" 

391 " large as %s." % minnu) 

392 if any(np.abs(A.T.dot(nu)) > tol): 

393 raise Infeasible("Dual: sum of nu^T * A did not vanish.") 

394 b = np.log(self.cs) 

395 dual_cost = sum( 

396 self.nu_by_posy[i].dot( 

397 b[mi] - np.log(self.nu_by_posy[i]/la[i])) 

398 for i, mi in enumerate(self.m_idxs) if la[i]) 

399 if not almost_equal(np.exp(dual_cost), cost): 

400 raise Infeasible("Dual cost %s does not match primal cost %s" 

401 % (np.exp(dual_cost), cost)) 

402 

403 

404def gen_meq_bounds(missingbounds, exps, meq_idxs): # pylint: disable=too-many-locals,too-many-branches 

405 "Generate conditional monomial equality bounds" 

406 meq_bounds = defaultdict(set) 

407 for i in meq_idxs.first_half: 

408 p_upper, p_lower, n_upper, n_lower = set(), set(), set(), set() 

409 for key, x in exps[i].items(): 

410 if (key, "upper") in missingbounds: 

411 if x > 0: 

412 p_upper.add((key, "upper")) 

413 else: 

414 n_upper.add((key, "upper")) 

415 if (key, "lower") in missingbounds: 

416 if x > 0: 

417 p_lower.add((key, "lower")) 

418 else: 

419 n_lower.add((key, "lower")) 

420 # (consider x*y/z == 1) 

421 # for a var (e.g. x) to be upper bounded by this monomial equality, 

422 # - vars of the same sign (y) must be lower bounded 

423 # - AND vars of the opposite sign (z) must be upper bounded 

424 p_ub = n_lb = frozenset(n_upper).union(p_lower) 

425 n_ub = p_lb = frozenset(p_upper).union(n_lower) 

426 for keys, ub in ((p_upper, p_ub), (n_upper, n_ub)): 

427 for key, _ in keys: 

428 needed = ub.difference([(key, "lower")]) 

429 if needed: 

430 meq_bounds[(key, "upper")].add(needed) 

431 else: 

432 del missingbounds[(key, "upper")] 

433 for keys, lb in ((p_lower, p_lb), (n_lower, n_lb)): 

434 for key, _ in keys: 

435 needed = lb.difference([(key, "upper")]) 

436 if needed: 

437 meq_bounds[(key, "lower")].add(needed) 

438 else: 

439 del missingbounds[(key, "lower")] 

440 return meq_bounds 

441 

442 

443def fulfill_meq_bounds(missingbounds, meq_bounds): 

444 "Bounds variables with monomial equalities" 

445 still_alive = True 

446 while still_alive: 

447 still_alive = False # if no changes are made, the loop exits 

448 for bound in set(meq_bounds): 

449 if bound not in missingbounds: 

450 del meq_bounds[bound] 

451 continue 

452 for condition in meq_bounds[bound]: 

453 if not any(bound in missingbounds for bound in condition): 

454 del meq_bounds[bound] 

455 del missingbounds[bound] 

456 still_alive = True 

457 break 

458 for (var, bound) in meq_bounds: 

459 boundstr = (", but would gain it from any of these sets: ") 

460 for condition in list(meq_bounds[(var, bound)]): 

461 meq_bounds[(var, bound)].remove(condition) 

462 newcond = condition.intersection(missingbounds) 

463 if newcond and not any(c.issubset(newcond) 

464 for c in meq_bounds[(var, bound)]): 

465 meq_bounds[(var, bound)].add(newcond) 

466 boundstr += " or ".join(str(list(condition)) 

467 for condition in meq_bounds[(var, bound)]) 

468 missingbounds[(var, bound)] = boundstr