gpkit.constraints package¶
Submodules¶
gpkit.constraints.array module¶
Implements ArrayConstraint
-
class
gpkit.constraints.array.
ArrayConstraint
(constraints, left, oper, right)¶ Bases:
gpkit.constraints.single_equation.SingleEquationConstraint
,gpkit.constraints.set.ConstraintSet
A ConstraintSet for prettier array-constraint printing.
ArrayConstraint gets its sub method from ConstrainSet, and so left and right are only used for printing.
When created by NomialArray left and right are likely to be be either NomialArrays or Varkeys of VectorVariables.
gpkit.constraints.bounded module¶
Implements Bounded
-
class
gpkit.constraints.bounded.
Bounded
(constraints, verbosity=1, eps=1e-30, lower=None, upper=None)¶ Bases:
gpkit.constraints.set.ConstraintSet
Bounds contained variables so as to ensure dual feasibility.
- constraints : iterable
- constraints whose varkeys will be bounded
- verbosity : int (default 1)
- how detailed of a warning to print
- 0: nothing 1: print warnings
- eps : float (default 1e-30)
- default lower bound is eps, upper bound is 1/eps
- lower : float (default None)
- lower bound for all varkeys, replaces eps
- upper : float (default None)
- upper bound for all varkeys, replaces 1/eps
-
check_boundaries
(result)¶ Creates (and potentially prints) a dictionary of unbounded variables.
-
logtol_threshold
= 3¶
-
process_result
(result)¶ Add boundedness to the model’s solution
-
sens_from_dual
(las, nus, result)¶ Return sensitivities while capturing the relevant lambdas
-
sens_threshold
= 1e-07¶
-
gpkit.constraints.bounded.
varkey_bounds
(varkeys, lower, upper)¶ Returns constraints list bounding all varkeys.
- varkeys : iterable
- list of varkeys to create bounds for
- lower : float
- lower bound for all varkeys
- upper : float
- upper bound for all varkeys
gpkit.constraints.costed module¶
Implement CostedConstraintSet
-
class
gpkit.constraints.costed.
CostedConstraintSet
(cost, constraints, substitutions=None)¶ Bases:
gpkit.constraints.set.ConstraintSet
A ConstraintSet with a cost
cost : gpkit.Posynomial constraints : Iterable substitutions : dict (None)
-
constrained_varkeys
()¶ Return all varkeys in the cost and non-ConstraintSet constraints
-
reset_varkeys
()¶ Resets varkeys to what is in the cost and constraints
-
rootconstr_latex
(excluded=None)¶ Latex showing cost, to be used when this is the top constraint
-
rootconstr_str
(excluded=None)¶ String showing cost, to be used when this is the top constraint
-
gpkit.constraints.gp module¶
Implement the GeometricProgram class
-
class
gpkit.constraints.gp.
GeometricProgram
(cost, constraints, substitutions, allow_missingbounds=False)¶ Bases:
gpkit.constraints.costed.CostedConstraintSet
,gpkit.nomials.data.NomialData
Standard mathematical representation of a GP.
solver_out and solver_log are set during a solve result is set at the end of a solve if solution status is optimal
>>> gp = gpkit.geometric_program.GeometricProgram( # minimize x, [ # subject to 1/x # <= 1, implicitly ], {}) >>> gp.solve()
-
check_solution
(cost, primal, nu, la, tol, abstol=1e-20)¶ Run a series of checks to mathematically confirm sol solves this GP
- cost: float
- cost returned by solver
- primal: list
- primal solution returned by solver
- nu: numpy.ndarray
- monomial lagrange multiplier
- la: numpy.ndarray
- posynomial lagrange multiplier
RuntimeWarning, if any problems are found
-
gen
()¶ Generates nomial and solve data (A, p_idxs) from posynomials
-
generate_result
(solver_out, warn_on_check=True, verbosity=0, process_result=True, dual_check=True)¶ Generates a full SolutionArray and checks it.
-
result
¶ Creates and caches a result from the raw solver_out
-
solve
(solver=None, verbosity=1, warn_on_check=False, process_result=True, gen_result=True, **kwargs)¶ Solves a GeometricProgram and returns the solution.
- solver : str or function (optional)
- By default uses one of the solvers found during installation. If set to “mosek”, “mosek_cli”, or “cvxopt”, uses that solver. If set to a function, passes that function cs, A, p_idxs, and k.
- verbosity : int (default 1)
- If greater than 0, prints solver name and solve time.
- **kwargs :
- Passed to solver constructor and solver function.
result : SolutionArray
-
-
gpkit.constraints.gp.
check_mono_eq_bounds
(missingbounds, meq_bounds)¶ Bounds variables with monomial equalities
-
gpkit.constraints.gp.
genA
(exps, varlocs, meq_idxs)¶ Generates A matrix
- A : sparse Cootmatrix
- Exponents of the various free variables for each monomial: rows of A are monomials, columns of A are variables.
- missingbounds : dict
- Keys: variables that lack bounds. Values: which bounds are missed.
gpkit.constraints.model module¶
Implements Model
-
class
gpkit.constraints.model.
Model
(cost=None, constraints=None, *args, **kwargs)¶ Bases:
gpkit.constraints.costed.CostedConstraintSet
Symbolic representation of an optimization problem.
The Model class is used both directly to create models with constants and sweeps, and indirectly inherited to create custom model classes.
- cost : Posynomial (optional)
- Defaults to Monomial(1).
- constraints : ConstraintSet or list of constraints (optional)
- Defaults to an empty list.
- substitutions : dict (optional)
- This dictionary will be substituted into the problem before solving, and also allows the declaration of sweeps and linked sweeps.
program is set during a solve solution is set at the end of a solve
-
as_gpconstr
(x0)¶ Returns approximating constraint, keeping name and num
-
autosweep
(sweeps, tol=0.01, samplepoints=100, **solveargs)¶ Autosweeps {var: (start, end)} pairs in sweeps to tol.
Returns swept and sampled solutions. The original simplex tree can be accessed at sol.bst
-
debug
(solver=None, verbosity=1, **solveargs)¶ Attempts to diagnose infeasible models.
If a model debugs but errors in a process_result call, debug again with process_results=False
-
gp
(constants=None, **kwargs)¶ Return program version of self
-
lineage
= None¶
-
localsolve
(solver=None, verbosity=1, skipsweepfailures=False, **kwargs)¶ Forms a mathematical program and attempts to solve it.
- solver : string or function (default None)
- If None, uses the default solver found in installation.
- verbosity : int (default 1)
- If greater than 0 prints runtime messages. Is decremented by one and then passed to programs.
- skipsweepfailures : bool (default False)
- If True, when a solve errors during a sweep, skip it.
**kwargs : Passed to solver
- sol : SolutionArray
- See the SolutionArray documentation for details.
ValueError if the program is invalid. RuntimeWarning if an error occurs in solving or parsing the solution.
-
program
= None¶
-
solution
= None¶
-
solve
(solver=None, verbosity=1, skipsweepfailures=False, **kwargs)¶ Forms a mathematical program and attempts to solve it.
- solver : string or function (default None)
- If None, uses the default solver found in installation.
- verbosity : int (default 1)
- If greater than 0 prints runtime messages. Is decremented by one and then passed to programs.
- skipsweepfailures : bool (default False)
- If True, when a solve errors during a sweep, skip it.
**kwargs : Passed to solver
- sol : SolutionArray
- See the SolutionArray documentation for details.
ValueError if the program is invalid. RuntimeWarning if an error occurs in solving or parsing the solution.
-
sp
(constants=None, **kwargs)¶ Return program version of self
-
subconstr_latex
(excluded=None)¶ The collapsed appearance of a Model
-
subconstr_str
(excluded=None)¶ The collapsed appearance of a Model
-
sweep
(sweeps, **solveargs)¶ Sweeps {var: values} pairs in sweeps. Returns swept solutions.
-
verify_docstring
()¶ Verifies docstring bounds are sufficient but not excessive.
-
gpkit.constraints.model.
get_relaxed
(relaxvals, mapped_list, min_return=1)¶ Determines which relaxvars are considered ‘relaxed’
gpkit.constraints.prog_factories module¶
Scripts for generating, solving and sweeping programs
-
gpkit.constraints.prog_factories.
evaluate_linked
(constants, linked)¶ Evaluates the values and gradients of linked variables.
-
gpkit.constraints.prog_factories.
run_sweep
(genfunction, self, solution, skipsweepfailures, constants, sweep, linked, solver, verbosity, **kwargs)¶ Runs through a sweep.
gpkit.constraints.relax module¶
Models for assessing primal feasibility
-
class
gpkit.constraints.relax.
ConstantsRelaxed
(constraints, include_only=None, exclude=None)¶ Bases:
gpkit.constraints.set.ConstraintSet
Relax constants in a constraintset.
- constraints : iterable
- Constraints which will be relaxed (made easier).
- include_only : set (optional)
- variable names must be in this set to be relaxed
- exclude : set (optional)
- variable names in this set will never be relaxed
- relaxvars : Variable
- The variables controlling the relaxation. A solved value of 1 means no relaxation was necessary or optimal for a particular constant. Higher values indicate the amount by which that constant has been made easier: e.g., a value of 1.5 means it was made 50 percent easier in the final solution than in the original problem. Of course, this can also be determined by looking at the constant’s new value directly.
-
process_result
(result)¶ Does arbitrary computation / manipulation of a program’s result
There’s no guarantee what order different constraints will process results in, so any changes made to the program’s result should be careful not to step on other constraint’s toes.
- check that an inequality was tight
- add values computed from solved variables
-
class
gpkit.constraints.relax.
ConstraintsRelaxed
(constraints)¶ Bases:
gpkit.constraints.set.ConstraintSet
Relax constraints, as in Eqn. 11 of [Boyd2007].
- constraints : iterable
- Constraints which will be relaxed (made easier).
- relaxvars : Variable
- The variables controlling the relaxation. A solved value of 1 means no relaxation was necessary or optimal for a particular constraint. Higher values indicate the amount by which that constraint has been made easier: e.g., a value of 1.5 means it was made 50 percent easier in the final solution than in the original problem.
[Boyd2007] : “A tutorial on geometric programming”, Optim Eng 8:67-122
-
class
gpkit.constraints.relax.
ConstraintsRelaxedEqually
(constraints)¶ Bases:
gpkit.constraints.set.ConstraintSet
Relax constraints the same amount, as in Eqn. 10 of [Boyd2007].
- constraints : iterable
- Constraints which will be relaxed (made easier).
- relaxvar : Variable
- The variable controlling the relaxation. A solved value of 1 means no relaxation. Higher values indicate the amount by which all constraints have been made easier: e.g., a value of 1.5 means all constraints were 50 percent easier in the final solution than in the original problem.
[Boyd2007] : “A tutorial on geometric programming”, Optim Eng 8:67-122
gpkit.constraints.set module¶
Implements ConstraintSet
-
class
gpkit.constraints.set.
ConstraintSet
(constraints, substitutions=None)¶ Bases:
list
,gpkit.repr_conventions.GPkitObject
Recursive container for ConstraintSets and Inequalities
-
as_gpconstr
(x0)¶ Returns GPConstraint approximating this constraint at x0
When x0 is none, may return a default guess.
-
as_posyslt1
(substitutions=None)¶ Returns list of posynomials which must be kept <= 1
-
as_view
()¶ Return a ConstraintSetView of this ConstraintSet.
-
constrained_varkeys
()¶ Return all varkeys in non-ConstraintSet constraints
-
flat
(constraintsets=False)¶ Yields contained constraints, optionally including constraintsets.
-
idxlookup
= None¶
-
latex
(excluded=None)¶ LaTeX representation of a ConstraintSet.
-
process_result
(result)¶ Does arbitrary computation / manipulation of a program’s result
There’s no guarantee what order different constraints will process results in, so any changes made to the program’s result should be careful not to step on other constraint’s toes.
- check that an inequality was tight
- add values computed from solved variables
-
reset_varkeys
()¶ Goes through constraints and collects their varkeys.
-
sens_from_dual
(las, nus, result)¶ Computes constraint and variable sensitivities from dual solution
- las : list
- Sensitivity of each posynomial returned by self.as_posyslt1
- nus: list of lists
- Each posynomial’s monomial sensitivities
- constraint_sens : dict
- The interesting and computable sensitivities of this constraint
- var_senss : dict
- The variable sensitivities of this constraint
-
str_without
(excluded=None)¶ String representation of a ConstraintSet.
-
unique_varkeys
= frozenset([])¶
-
variables_byname
(key)¶ Get all variables with a given name
-
varkeys
= None¶
-
-
class
gpkit.constraints.set.
ConstraintSetView
(constraintset, index=())¶ Bases:
object
Class to access particular views on a set’s variables
-
gpkit.constraints.set.
add_meq_bounds
(bounded, meq_bounded)¶ Iterates through meq_bounds until convergence
-
gpkit.constraints.set.
raise_badelement
(cns, i, constraint)¶ Identify the bad element and raise a ValueError
-
gpkit.constraints.set.
raise_elementhasnumpybools
(constraint)¶ Identify the bad subconstraint array and raise a ValueError
gpkit.constraints.sgp module¶
Implement the SequentialGeometricProgram class
-
class
gpkit.constraints.sgp.
SequentialGeometricProgram
(cost, constraints, substitutions)¶ Bases:
gpkit.constraints.costed.CostedConstraintSet
Prepares a collection of signomials for a SP solve.
- cost : Posynomial
- Objective to minimize when solving
- constraints : list of Constraint or SignomialConstraint objects
- Constraints to maintain when solving (implicitly Signomials <= 1)
- verbosity : int (optional)
- Currently has no effect: SequentialGeometricPrograms don’t know anything new after being created, unlike GeometricPrograms.
gps is set during a solve result is set at the end of a solve
>>> gp = gpkit.geometric_program.SequentialGeometricProgram( # minimize x, [ # subject to 1/x - y/x, # <= 1, implicitly y/10 # <= 1 ]) >>> gp.solve()
-
gp
(x0=None, mutategp=False)¶ The GP approximation of this SP at x0.
-
init_gp
(substitutions, x0=None)¶ Generates a simplified GP representation for later modification
-
localsolve
(solver=None, verbosity=1, x0=None, reltol=0.0001, iteration_limit=50, mutategp=True, **kwargs)¶ Locally solves a SequentialGeometricProgram and returns the solution.
- solver : str or function (optional)
- By default uses one of the solvers found during installation. If set to “mosek”, “mosek_cli”, or “cvxopt”, uses that solver. If set to a function, passes that function cs, A, p_idxs, and k.
- verbosity : int (optional)
- If greater than 0, prints solve time and number of iterations. Each GP is created and solved with verbosity one less than this, so if greater than 1, prints solver name and time for each GP.
- x0 : dict (optional)
- Initial location to approximate signomials about.
- reltol : float
- Iteration ends when this is greater than the distance between two consecutive solve’s objective values.
- iteration_limit : int
- Maximum GP iterations allowed.
- *args, **kwargs :
- Passed to solver function.
- result : dict
- A dictionary containing the translated solver result.
-
results
¶ Creates and caches results from the raw solver_outs
gpkit.constraints.sigeq module¶
Implements SignomialEquality
-
class
gpkit.constraints.sigeq.
SignomialEquality
(left, right)¶ Bases:
gpkit.constraints.set.ConstraintSet
A constraint of the general form posynomial == posynomial
gpkit.constraints.single_equation module¶
Implements SingleEquationConstraint
-
class
gpkit.constraints.single_equation.
SingleEquationConstraint
(left, oper, right)¶ Bases:
gpkit.repr_conventions.GPkitObject
Constraint expressible in a single equation.
-
func_opers
= {'<=': <built-in function le>, '=': <built-in function eq>, '>=': <built-in function ge>}¶
-
latex
(excluded='units')¶ Latex representation without attributes in excluded list
-
latex_opers
= {'<=': '\\leq', '=': '=', '>=': '\\geq'}¶
-
str_without
(excluded='units')¶ String representation without attributes in excluded list
-
gpkit.constraints.tight module¶
Implements Tight
-
class
gpkit.constraints.tight.
Tight
(constraints, reltol=None, raiseerror=False, **kwargs)¶ Bases:
gpkit.constraints.set.ConstraintSet
ConstraintSet whose inequalities must result in an equality.
-
process_result
(result)¶ Checks that all constraints are satisfied with equality
-
reltol
= 1e-06¶
-
Module contents¶
Contains ConstraintSet and related classes and objects