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.

subinplace(subs)

Substitutes in place, updating self.substitutions accordingly.

Keys substituted with subinplace are no longer present, so if such a key is also in self.substitutions that substitution is now orphaned. If subs[key] describes some key in the ConstraintSet (i.e. one key has been substituted for another), then a substitution is added, mapping the orphaned value to this new key; otherwise, an error is raised.

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
substitutions : dict
as in ConstraintSet.__init__
verbosity : int
how detailed of a warning to print
0: nothing 1: print warnings
eps : float
default lower bound is eps, upper bound is 1/eps
lower : float
lower bound for all varkeys, replaces eps
upper : float
upper bound for all varkeys, replaces 1/eps
check_boundaries(result)

Creates (and potentially prints) a dictionary of unbounded variables.

process_result(result)

Add boundedness to the model’s solution

sens_from_dual(las, nus)

Return sensitivities while capturing the relevant lambdas

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

controlpanel(*args, **kwargs)

Easy model control in IPython / Jupyter

Like interact(), but with the ability to control sliders and their ranges live. args and kwargs are passed on to interact()

interact(ranges=None, fn_of_sol=None, **solvekwargs)

Easy model interaction in IPython / Jupyter

By default, this creates a model with sliders for every constant which prints a new solution table whenever the sliders are changed.

fn_of_sol : function
The function called with the solution after each solve that displays the result. By default prints a table.
ranges : dictionary {str: Slider object or tuple}
Determines which sliders get created. Tuple values may contain two or three floats: two correspond to (min, max), while three correspond to (min, step, max)
**solvekwargs
kwargs which get passed to the solve()/localsolve() method.
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

subinplace(subs)

Substitutes in place.

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.

cost : Constraint
Posynomial to minimize when solving
constraints : list of Posynomials

Constraints to maintain when solving (implicitly Posynomials <= 1) GeometricProgram does not accept equality constraints (e.g. x == 1);

instead use two inequality constraints (e.g. x <= 1, 1/x <= 1)
verbosity : int (optional)
If verbosity is greater than zero, warns about missing bounds on creation.

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=0.001, 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

solve(solver=None, verbosity=1, warn_on_check=False, process_result=True, *args, **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 (optional)
If greater than 0, prints solver name and solve time.
*args, **kwargs :
Passed to solver constructor and solver function.
result : dict

A dictionary containing the translated solver result; keys below.

cost : float
The value of the objective at the solution.
variables : dict
The value of each variable at the solution.
sensitivities : dict
monomials : array of floats
Each monomial’s dual variable value at the solution.
posynomials : array of floats
Each posynomials’s dual variable value at the solution.
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 from exps and varidxs

exps : list of Hashvectors
Exponents for each monomial in a GP
varidxs : dict
Locations of each variable in exps
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.
name : str (optional)
Allows “naming” a model in a way similar to inherited instances, and overrides the inherited name if there is one.

program is set during a solve solution is set at the end of a solve

as_gpconstr(x0, substitutions=None)

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

program: NomialData
Class to return, e.g. GeometricProgram or SequentialGeometricProgram
return_attr: string
attribute to return in addition to the program
localsolve(solver=None, verbosity=1, skipsweepfailures=False, *args, **kwargs)

Forms a mathematical program and attempts to solve it.

solver : string or function (optional)
If None, uses the default solver found in installation.
verbosity : int (optional)
If greater than 0 prints runtime messages. Is decremented by one and then passed to programs.
skipsweepfailures : bool (optional)
If True, when a solve errors during a sweep, skip it.

*args, **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.

name = None
naming = None
num = None
program = None
solution = None
solve(solver=None, verbosity=1, skipsweepfailures=False, *args, **kwargs)

Forms a mathematical program and attempts to solve it.

solver : string or function (optional)
If None, uses the default solver found in installation.
verbosity : int (optional)
If greater than 0 prints runtime messages. Is decremented by one and then passed to programs.
skipsweepfailures : bool (optional)
If True, when a solve errors during a sweep, skip it.

*args, **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

program: NomialData
Class to return, e.g. GeometricProgram or SequentialGeometricProgram
return_attr: string
attribute to return in addition to the program
subconstr_latex(excluded=None)

The collapsed appearance of a ConstraintBase

subconstr_str(excluded=None)

The collapsed appearance of a ConstraintBase

sweep(sweeps, **solveargs)

Sweeps {var: values} pairs in sweeps. Returns swept solutions.

zero_lower_unbounded_variables()

Recursively substitutes 0 for variables that lack a lower bound

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.run_sweep(genfunction, self, solution, skipsweepfailures, constants, sweep, linked, solver, verbosity, *args, **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
if declared, variable names must be on this list to be relaxed
exclude : set
if declared, variable names on this list 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)
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

Recursive container for ConstraintSets and Inequalities

append(value)
as_gpconstr(x0, substitutions=None)

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

flat(constraintsets=True)

Yields contained constraints, optionally including constraintsets.

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.

rootconstr_latex(excluded=None)

The appearance of a ConstraintSet in addition to its contents

rootconstr_str(excluded=None)

The appearance of a ConstraintSet in addition to its contents

sens_from_dual(las, nus)

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.

subconstr_latex(excluded=None)

The collapsed appearance of a ConstraintSet

subconstr_str(excluded=None)

The collapsed appearance of a ConstraintSet

subinplace(subs)

Substitutes in place, updating self.substitutions accordingly.

Keys substituted with subinplace are no longer present, so if such a key is also in self.substitutions that substitution is now orphaned. If subs[key] describes some key in the ConstraintSet (i.e. one key has been substituted for another), then a substitution is added, mapping the orphaned value to this new key; otherwise, an error is raised.

topvar(key)

If a variable by a given name exists in the top model, return it

unique_varkeys = frozenset([])
variables_byname(key)

Get all variables with a given name

varkeys = None
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.

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

Constraint expressible in a single equation.

func_opers = {'<=': <built-in function le>, '=': <built-in function eq>, '>=': <built-in function ge>}
latex(excluded=None)

Latex representation without attributes in excluded list

latex_opers = {'<=': '\\leq', '=': '=', '>=': '\\geq'}
process_result(result)

Process solver results

str_without(excluded=None)

String representation without attributes in excluded list

sub(subs)

Returns a substituted version of this constraint.

subconstr_latex(excluded)

The collapsed latex of a constraint

subconstr_str(excluded)

The collapsed string of a constraint

gpkit.constraints.single_equation.trycall(obj, attr, arg, default)

Try to call method of an object, returning default if it does not exist

gpkit.constraints.tight module

Implements Tight

class gpkit.constraints.tight.Tight(constraints, substitutions=None, reltol=None, raiseerror=False)

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