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)
17DEFAULT_SOLVER_KWARGS = {"cvxopt": {"kktsolver": "ldl"}}
18SOLUTION_TOL = {"cvxopt": 1e-3, "mosek_cli": 1e-4, "mosek_conif": 1e-3}
21class MonoEqualityIndexes:
22 "Class to hold MonoEqualityIndexes"
24 def __init__(self):
25 self.all = set()
26 self.first_half = set()
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
52class GeometricProgram:
53 # pylint: disable=too-many-instance-attributes
54 """Standard mathematical representation of a GP.
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
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 choicevaridxs = integersolve = None
74 def __init__(self, cost, constraints, substitutions, *, checkbounds=True):
75 self.cost, self.substitutions = cost, substitutions
76 for key, sub in self.substitutions.items():
77 if isinstance(sub, FixedScalar):
78 sub = sub.value
79 if hasattr(sub, "units"):
80 sub = sub.to(key.units or "dimensionless").magnitude
81 self.substitutions[key] = sub
82 if not isinstance(sub, (Numbers, np.ndarray)):
83 raise TypeError("substitution {%s: %s} has invalid value type"
84 " %s." % (key, sub, type(sub)))
85 cost_hmap = cost.hmap.sub(self.substitutions, cost.vks)
86 if any(c <= 0 for c in cost_hmap.values()):
87 raise InvalidPosynomial("a GP's cost must be Posynomial")
88 hmapgen = ConstraintSet.as_hmapslt1(constraints, self.substitutions)
89 self.hmaps = [cost_hmap] + list(hmapgen)
90 self.gen() # Generate various maps into the posy- and monomials
91 if checkbounds:
92 self.check_bounds(err_on_missing_bounds=True)
94 def check_bounds(self, *, err_on_missing_bounds=False):
95 "Checks if any variables are unbounded, through equality constraints."
96 missingbounds = {}
97 for var, locs in self.varlocs.items():
98 upperbound, lowerbound = False, False
99 for i in locs:
100 if i not in self.meq_idxs.all:
101 if self.exps[i][var] > 0: # pylint:disable=simplifiable-if-statement
102 upperbound = True
103 else:
104 lowerbound = True
105 if upperbound and lowerbound:
106 break
107 if not upperbound:
108 missingbounds[(var, "upper")] = "."
109 if not lowerbound:
110 missingbounds[(var, "lower")] = "."
111 if not missingbounds:
112 return {} # all bounds found in inequalities
113 meq_bounds = gen_meq_bounds(missingbounds, self.exps, self.meq_idxs)
114 fulfill_meq_bounds(missingbounds, meq_bounds)
115 if missingbounds and err_on_missing_bounds:
116 raise UnboundedGP(
117 "\n\n".join("%s has no %s bound%s" % (v, b, x)
118 for (v, b), x in missingbounds.items()))
119 return missingbounds
121 def gen(self):
122 """Generates nomial and solve data (A, p_idxs) from posynomials.
124 k [posys]: number of monomials (rows of A) present in each constraint
125 m_idxs [mons]: monomial indices of each posynomial
126 p_idxs [mons]: posynomial index of each monomial
127 cs, exps [mons]: coefficient and exponents of each monomial
128 varlocs: {vk: monomial indices of each variables' location}
129 meq_idxs: {all indices of equality mons} and {the first index of each}
130 varidxs: {vk: which column corresponds to it in A}
131 A [mons, vks]: sparse array of each monomials' variables' exponents
133 """
134 self.k = [len(hmap) for hmap in self.hmaps]
135 self.m_idxs, self.p_idxs, self.cs, self.exps = [], [], [], []
136 self.varkeys = self.varlocs = defaultdict(list)
137 self.meq_idxs = MonoEqualityIndexes()
138 m_idx = 0
139 row, col, data = [], [], []
140 for p_idx, (N_mons, hmap) in enumerate(zip(self.k, self.hmaps)):
141 self.p_idxs.extend([p_idx]*N_mons)
142 self.m_idxs.append(slice(m_idx, m_idx+N_mons))
143 if getattr(self.hmaps[p_idx], "from_meq", False):
144 self.meq_idxs.all.add(m_idx)
145 if len(self.meq_idxs.all) > 2*len(self.meq_idxs.first_half):
146 self.meq_idxs.first_half.add(m_idx)
147 self.exps.extend(hmap)
148 self.cs.extend(hmap.values())
149 for exp in hmap:
150 if not exp: # space out A matrix with constants for mosek
151 row.append(m_idx)
152 col.append(0)
153 data.append(0)
154 for var in exp:
155 self.varlocs[var].append(m_idx)
156 m_idx += 1
157 self.p_idxs = np.array(self.p_idxs, "int32") # to use array equalities
158 self.varidxs = {vk: i for i, vk in enumerate(self.varlocs)}
159 self.choicevaridxs = {vk: i for i, vk in enumerate(self.varlocs)
160 if vk.choices}
161 for j, (var, locs) in enumerate(self.varlocs.items()):
162 row.extend(locs)
163 col.extend([j]*len(locs))
164 data.extend(self.exps[i][var] for i in locs)
165 self.A = CootMatrix(row, col, data)
167 # pylint: disable=too-many-statements, too-many-locals
168 def solve(self, solver=None, *, verbosity=1, gen_result=True, **kwargs):
169 """Solves a GeometricProgram and returns the solution.
171 Arguments
172 ---------
173 solver : str or function (optional)
174 By default uses a solver found during installation.
175 If "mosek_conif", "mosek_cli", or "cvxopt", uses that solver.
176 If a function, passes that function cs, A, p_idxs, and k.
177 verbosity : int (default 1)
178 If greater than 0, prints solver name and solve time.
179 gen_result : bool (default True)
180 If True, makes a human-readable SolutionArray from solver output.
181 **kwargs :
182 Passed to solver constructor and solver function.
185 Returns
186 -------
187 SolutionArray (or dict if gen_result is False)
188 """
189 solvername, solverfn = _get_solver(solver, kwargs)
190 if verbosity > 0:
191 print("Using solver '%s'" % solvername)
192 print(" for %i free variables" % len(self.varlocs))
193 print(" in %i posynomial inequalities." % len(self.k))
195 solverargs = DEFAULT_SOLVER_KWARGS.get(solvername, {})
196 solverargs.update(kwargs)
197 if self.choicevaridxs and solvername == "mosek_conif":
198 solverargs["choicevaridxs"] = self.choicevaridxs
199 self.integersolve = True
200 starttime = time()
201 solver_out, infeasibility, original_stdout = {}, None, sys.stdout
202 try:
203 sys.stdout = SolverLog(original_stdout, verbosity=verbosity-2)
204 solver_out = solverfn(c=self.cs, A=self.A, meq_idxs=self.meq_idxs,
205 k=self.k, p_idxs=self.p_idxs, **solverargs)
206 except Infeasible as e:
207 infeasibility = e
208 except InvalidLicense as e:
209 raise InvalidLicense("license for solver \"%s\" is invalid."
210 % solvername) from e
211 except Exception as e:
212 raise UnknownInfeasible("Something unexpected went wrong.") from e
213 finally:
214 self.solve_log = "\n".join(sys.stdout)
215 sys.stdout = original_stdout
216 self.solver_out = solver_out
218 solver_out["solver"] = solvername
219 solver_out["soltime"] = time() - starttime
220 if verbosity > 0:
221 print("Solving took %.3g seconds." % solver_out["soltime"])
223 if infeasibility:
224 if isinstance(infeasibility, PrimalInfeasible):
225 msg = ("The model had no feasible points; "
226 "you may wish to relax some constraints or constants.")
227 elif isinstance(infeasibility, DualInfeasible):
228 msg = ("The model ran to an infinitely low cost;"
229 " bounding the right variables would prevent this.")
230 elif isinstance(infeasibility, UnknownInfeasible):
231 msg = ("Solver failed for an unknown reason. Relaxing"
232 " constraints/constants, bounding variables, or"
233 " using a different solver might fix it.")
234 if (verbosity > 0 and solver_out["soltime"] < 1
235 and hasattr(self, "model")): # fast, top-level model
236 print(msg + "\nSince the model solved in less than a second,"
237 " let's run `.debug()` to analyze what happened.\n`")
238 return self.model.debug(solver=solver)
239 # else, raise a clarifying error
240 msg += (" Running `.debug()` or increasing verbosity may pinpoint"
241 " the trouble.")
242 raise infeasibility.__class__(msg) from infeasibility
244 if not gen_result:
245 return solver_out
246 # else, generate a human-readable SolutionArray
247 self._result = self.generate_result(solver_out, verbosity=verbosity-2)
248 return self.result
250 @property
251 def result(self):
252 "Creates and caches a result from the raw solver_out"
253 if not self._result:
254 self._result = self.generate_result(self.solver_out)
255 return self._result
257 def generate_result(self, solver_out, *, verbosity=0, dual_check=True):
258 "Generates a full SolutionArray and checks it."
259 if verbosity > 0:
260 soltime = solver_out["soltime"]
261 tic = time()
262 # result packing #
263 result = self._compile_result(solver_out) # NOTE: SIDE EFFECTS
264 if verbosity > 0:
265 print("Result packing took %.2g%% of solve time." %
266 ((time() - tic) / soltime * 100))
267 tic = time()
268 # solution checking #
269 try:
270 tol = SOLUTION_TOL.get(solver_out["solver"], 1e-5)
271 self.check_solution(result["cost"], solver_out['primal'],
272 solver_out["nu"], solver_out["la"], tol)
273 except Infeasible as chkerror:
274 chkwarn = str(chkerror)
275 if not ("Dual" in chkwarn and not dual_check):
276 print("Solution check warning: %s" % chkwarn)
277 if verbosity > 0:
278 print("Solution checking took %.2g%% of solve time." %
279 ((time() - tic) / soltime * 100))
280 return result
282 def _generate_nula(self, solver_out):
283 if "nu" in solver_out:
284 # solver gave us monomial sensitivities, generate posynomial ones
285 solver_out["nu"] = nu = np.ravel(solver_out["nu"])
286 nu_by_posy = [nu[mi] for mi in self.m_idxs]
287 solver_out["la"] = la = np.array([sum(nup) for nup in nu_by_posy])
288 elif "la" in solver_out:
289 la = np.ravel(solver_out["la"])
290 if len(la) == len(self.hmaps) - 1:
291 # assume solver dropped the cost's sensitivity (always 1.0)
292 la = np.hstack(([1.0], la))
293 # solver gave us posynomial sensitivities, generate monomial ones
294 solver_out["la"] = la
295 z = np.log(self.cs) + self.A.dot(solver_out["primal"])
296 m_iss = [self.p_idxs == i for i in range(len(la))]
297 nu_by_posy = [la[p_i]*np.exp(z[m_is])/sum(np.exp(z[m_is]))
298 for p_i, m_is in enumerate(m_iss)]
299 solver_out["nu"] = np.hstack(nu_by_posy)
300 else:
301 raise RuntimeWarning("The dual solution was not returned.")
302 return la, nu_by_posy
304 def _compile_result(self, solver_out):
305 result = {"cost": float(solver_out["objective"])}
306 primal = solver_out["primal"]
307 if len(self.varlocs) != len(primal):
308 raise RuntimeWarning("The primal solution was not returned.")
309 result["freevariables"] = KeyDict(zip(self.varlocs, np.exp(primal)))
310 result["constants"] = KeyDict(self.substitutions)
311 result["variables"] = KeyDict(result["freevariables"])
312 result["variables"].update(result["constants"])
313 result["soltime"] = solver_out["soltime"]
314 if self.integersolve:
315 result["choicevariables"] = KeyDict( \
316 {k: v for k, v in result["freevariables"].items()
317 if k in self.choicevaridxs})
318 result["warnings"] = {"No Dual Solution": [(\
319 "This model has the discretized choice variables"
320 " %s and hence no dual solution. You can fix those variables"
321 " to their optimal value and get sensitivities to the resulting"
322 " continuous problem by updating your model's substitions with"
323 " `sol[\"choicevariables\"]`."
324 % sorted(self.choicevaridxs.keys()), self.choicevaridxs)]}
325 return SolutionArray(result)
326 elif self.choicevaridxs:
327 result["warnings"] = {"Freed Choice Variables": [(\
328 "This model has the discretized choice variables"
329 " %s, but since the '%s' solver doesn't support discretization"
330 " they were treated as continuous variables."
331 % (sorted(self.choicevaridxs.keys()), solver_out["solver"]),
332 self.choicevaridxs)]}
334 result["sensitivities"] = {"constraints": {}}
335 la, self.nu_by_posy = self._generate_nula(solver_out)
336 cost_senss = sum(nu_i*exp for (nu_i, exp) in zip(self.nu_by_posy[0],
337 self.cost.hmap))
338 gpv_ss = cost_senss.copy()
339 m_senss = defaultdict(float)
340 for las, nus, c in zip(la[1:], self.nu_by_posy[1:], self.hmaps[1:]):
341 while getattr(c, "parent", None) is not None:
342 c = c.parent
343 v_ss, c_senss = c.sens_from_dual(las, nus, result)
344 for vk, x in v_ss.items():
345 gpv_ss[vk] = x + gpv_ss.get(vk, 0)
346 while getattr(c, "generated_by", None):
347 c = c.generated_by
348 result["sensitivities"]["constraints"][c] = abs(c_senss)
349 m_senss[lineagestr(c)] += abs(c_senss)
350 # add fixed variables sensitivities to models
351 for vk, senss in gpv_ss.items():
352 m_senss[lineagestr(vk)] += abs(senss)
353 result["sensitivities"]["models"] = dict(m_senss)
354 # carry linked sensitivities over to their constants
355 for v in list(v for v in gpv_ss if v.gradients):
356 dlogcost_dlogv = gpv_ss.pop(v)
357 val = np.array(result["constants"][v])
358 for c, dv_dc in v.gradients.items():
359 with warnings.catch_warnings(): # skip pesky divide-by-zeros
360 warnings.simplefilter("ignore")
361 dlogv_dlogc = dv_dc * result["constants"][c]/val
362 gpv_ss[c] = gpv_ss.get(c, 0) + dlogcost_dlogv*dlogv_dlogc
363 if v in cost_senss:
364 if c in self.cost.vks:
365 dlogcost_dlogv = cost_senss.pop(v)
366 before = cost_senss.get(c, 0)
367 cost_senss[c] = before + dlogcost_dlogv*dlogv_dlogc
368 result["sensitivities"]["cost"] = cost_senss
369 result["sensitivities"]["variables"] = KeyDict(gpv_ss)
370 result["sensitivities"]["constants"] = \
371 result["sensitivities"]["variables"] # NOTE: backwards compat.
372 return SolutionArray(result)
374 def check_solution(self, cost, primal, nu, la, tol, abstol=1e-20):
375 """Run checks to mathematically confirm solution solves this GP
377 Arguments
378 ---------
379 cost: float
380 cost returned by solver
381 primal: list
382 primal solution returned by solver
383 nu: numpy.ndarray
384 monomial lagrange multiplier
385 la: numpy.ndarray
386 posynomial lagrange multiplier
388 Raises
389 ------
390 Infeasible if any problems are found
391 """
392 A = self.A.tocsr()
393 def almost_equal(num1, num2):
394 "local almost equal test"
395 return (num1 == num2 or abs((num1 - num2) / (num1 + num2)) < tol
396 or abs(num1 - num2) < abstol)
397 # check primal sol #
398 primal_exp_vals = self.cs * np.exp(A.dot(primal)) # c*e^Ax
399 if not almost_equal(primal_exp_vals[self.m_idxs[0]].sum(), cost):
400 raise Infeasible("Primal solution computed cost did not match"
401 " solver-returned cost: %s vs %s." %
402 (primal_exp_vals[self.m_idxs[0]].sum(), cost))
403 for mi in self.m_idxs[1:]:
404 if primal_exp_vals[mi].sum() > 1 + tol:
405 raise Infeasible("Primal solution violates constraint: %s is "
406 "greater than 1" % primal_exp_vals[mi].sum())
407 # check dual sol #
408 if self.integersolve:
409 return
410 # note: follows dual formulation in section 3.1 of
411 # http://web.mit.edu/~whoburg/www/papers/hoburg_phd_thesis.pdf
412 if not almost_equal(self.nu_by_posy[0].sum(), 1):
413 raise Infeasible("Dual variables associated with objective sum"
414 " to %s, not 1" % self.nu_by_posy[0].sum())
415 if any(nu < 0):
416 minnu = min(nu)
417 if minnu < -tol/1000:
418 raise Infeasible("Dual solution has negative entries as"
419 " large as %s." % minnu)
420 if any(np.abs(A.T.dot(nu)) > tol):
421 raise Infeasible("Dual: sum of nu^T * A did not vanish.")
422 b = np.log(self.cs)
423 dual_cost = sum(
424 self.nu_by_posy[i].dot(
425 b[mi] - np.log(self.nu_by_posy[i]/la[i]))
426 for i, mi in enumerate(self.m_idxs) if la[i])
427 if not almost_equal(np.exp(dual_cost), cost):
428 raise Infeasible("Dual cost %s does not match primal cost %s"
429 % (np.exp(dual_cost), cost))
432def gen_meq_bounds(missingbounds, exps, meq_idxs): # pylint: disable=too-many-locals,too-many-branches
433 "Generate conditional monomial equality bounds"
434 meq_bounds = defaultdict(set)
435 for i in meq_idxs.first_half:
436 p_upper, p_lower, n_upper, n_lower = set(), set(), set(), set()
437 for key, x in exps[i].items():
438 if (key, "upper") in missingbounds:
439 if x > 0:
440 p_upper.add((key, "upper"))
441 else:
442 n_upper.add((key, "upper"))
443 if (key, "lower") in missingbounds:
444 if x > 0:
445 p_lower.add((key, "lower"))
446 else:
447 n_lower.add((key, "lower"))
448 # (consider x*y/z == 1)
449 # for a var (e.g. x) to be upper bounded by this monomial equality,
450 # - vars of the same sign (y) must be lower bounded
451 # - AND vars of the opposite sign (z) must be upper bounded
452 p_ub = n_lb = frozenset(n_upper).union(p_lower)
453 n_ub = p_lb = frozenset(p_upper).union(n_lower)
454 for keys, ub in ((p_upper, p_ub), (n_upper, n_ub)):
455 for key, _ in keys:
456 needed = ub.difference([(key, "lower")])
457 if needed:
458 meq_bounds[(key, "upper")].add(needed)
459 else:
460 del missingbounds[(key, "upper")]
461 for keys, lb in ((p_lower, p_lb), (n_lower, n_lb)):
462 for key, _ in keys:
463 needed = lb.difference([(key, "upper")])
464 if needed:
465 meq_bounds[(key, "lower")].add(needed)
466 else:
467 del missingbounds[(key, "lower")]
468 return meq_bounds
471def fulfill_meq_bounds(missingbounds, meq_bounds):
472 "Bounds variables with monomial equalities"
473 still_alive = True
474 while still_alive:
475 still_alive = False # if no changes are made, the loop exits
476 for bound in set(meq_bounds):
477 if bound not in missingbounds:
478 del meq_bounds[bound]
479 continue
480 for condition in meq_bounds[bound]:
481 if not any(bound in missingbounds for bound in condition):
482 del meq_bounds[bound]
483 del missingbounds[bound]
484 still_alive = True
485 break
486 for (var, bound) in meq_bounds:
487 boundstr = (", but would gain it from any of these sets: ")
488 for condition in list(meq_bounds[(var, bound)]):
489 meq_bounds[(var, bound)].remove(condition)
490 newcond = condition.intersection(missingbounds)
491 if newcond and not any(c.issubset(newcond)
492 for c in meq_bounds[(var, bound)]):
493 meq_bounds[(var, bound)].add(newcond)
494 boundstr += " or ".join(str(list(condition))
495 for condition in meq_bounds[(var, bound)])
496 missingbounds[(var, bound)] = boundstr