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 = "The solver failed for an unknown reason." 

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

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

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

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

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

231 # else, raise a clarifying error 

232 msg += (" Running `.debug()` may pinpoint the trouble. You can" 

233 " also try another solver, or increase the verbosity.") 

234 raise infeasibility.__class__(msg) from infeasibility 

235 

236 if not gen_result: 

237 return solver_out 

238 # else, generate a human-readable SolutionArray 

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

240 return self.result 

241 

242 @property 

243 def result(self): 

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

245 if not self._result: 

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

247 return self._result 

248 

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

250 "Generates a full SolutionArray and checks it." 

251 if verbosity > 0: 

252 soltime = solver_out["soltime"] 

253 tic = time() 

254 # result packing # 

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

256 if verbosity > 0: 

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

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

259 tic = time() 

260 # solution checking # 

261 try: 

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

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

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

265 except Infeasible as chkerror: 

266 chkwarn = str(chkerror) 

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

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

269 if verbosity > 0: 

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

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

272 return result 

273 

274 def _generate_nula(self, solver_out): 

275 if "nu" in solver_out: 

276 # solver gave us monomial sensitivities, generate posynomial ones 

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

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

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

280 elif "la" in solver_out: 

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

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

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

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

285 # solver gave us posynomial sensitivities, generate monomial ones 

286 solver_out["la"] = la 

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

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

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

290 for p_i, m_is in enumerate(m_iss)] 

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

292 else: 

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

294 return la, nu_by_posy 

295 

296 def _compile_result(self, solver_out): 

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

298 primal = solver_out["primal"] 

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

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

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

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

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

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

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

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

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

308 self.cost.hmap)) 

309 gpv_ss = cost_senss.copy() 

310 m_senss = defaultdict(float) 

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

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

313 c = c.parent 

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

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

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

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

318 c = c.generated_by 

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

320 m_senss[lineagestr(c)] += c_senss 

321 # add fixed variables sensitivities to models 

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

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

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

325 # carry linked sensitivities over to their constants 

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

327 dlogcost_dlogv = gpv_ss.pop(v) 

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

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

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

331 warnings.simplefilter("ignore") 

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

333 before = gpv_ss.get(c, 0) 

334 gpv_ss[c] = before + dlogcost_dlogv*dlogv_dlogc 

335 if v in cost_senss: 

336 if c in self.cost.vks: 

337 dlogcost_dlogv = cost_senss.pop(v) 

338 before = cost_senss.get(c, 0) 

339 cost_senss[c] = before + dlogcost_dlogv*dlogv_dlogc 

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

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

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

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

344 result["soltime"] = solver_out["soltime"] 

345 return SolutionArray(result) 

346 

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

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

349 

350 Arguments 

351 --------- 

352 cost: float 

353 cost returned by solver 

354 primal: list 

355 primal solution returned by solver 

356 nu: numpy.ndarray 

357 monomial lagrange multiplier 

358 la: numpy.ndarray 

359 posynomial lagrange multiplier 

360 

361 Raises 

362 ------ 

363 Infeasible if any problems are found 

364 """ 

365 A = self.A.tocsr() 

366 def almost_equal(num1, num2): 

367 "local almost equal test" 

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

369 or abs(num1 - num2) < abstol) 

370 # check primal sol # 

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

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

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

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

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

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

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

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

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

380 # check dual sol # 

381 # note: follows dual formulation in section 3.1 of 

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

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

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

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

386 if any(nu < 0): 

387 minnu = min(nu) 

388 if minnu < -tol/1000: 

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

390 " large as %s." % minnu) 

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

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

393 b = np.log(self.cs) 

394 dual_cost = sum( 

395 self.nu_by_posy[i].dot( 

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

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

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

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

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

401 

402 

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

404 "Generate conditional monomial equality bounds" 

405 meq_bounds = defaultdict(set) 

406 for i in meq_idxs.first_half: 

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

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

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

410 if x > 0: 

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

412 else: 

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

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

415 if x > 0: 

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

417 else: 

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

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

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

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

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

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

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

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

426 for key, _ in keys: 

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

428 if needed: 

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

430 else: 

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

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

433 for key, _ in keys: 

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

435 if needed: 

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

437 else: 

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

439 return meq_bounds 

440 

441 

442def fulfill_meq_bounds(missingbounds, meq_bounds): 

443 "Bounds variables with monomial equalities" 

444 still_alive = True 

445 while still_alive: 

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

447 for bound in set(meq_bounds): 

448 if bound not in missingbounds: 

449 del meq_bounds[bound] 

450 continue 

451 for condition in meq_bounds[bound]: 

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

453 del meq_bounds[bound] 

454 del missingbounds[bound] 

455 still_alive = True 

456 break 

457 for (var, bound) in meq_bounds: 

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

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

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

461 newcond = condition.intersection(missingbounds) 

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

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

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

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

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

467 missingbounds[(var, bound)] = boundstr