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, list

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.

lines_without(excluded)

Returns lines for indentation in hierarchical printing.

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, *, verbosity=0)

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

logtol_threshold = 3
process_result(result)

Add boundedness to the model’s solution

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

lineage = None

gpkit.constraints.gp module

Implement the GeometricProgram class

class gpkit.constraints.gp.GeometricProgram(cost, constraints, substitutions, *, checkbounds=True)

Bases: object

Standard mathematical representation of a GP.

solver_out and solve_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_bounds(*, err_on_missing_bounds=False)

Checks if any variables are unbounded, through equality constraints.

check_solution(cost, primal, nu, la, tol, abstol=1e-20)

Run checks to mathematically confirm solution 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

Infeasible if any problems are found

gen()

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

generate_result(solver_out, *, verbosity=0, dual_check=True)

Generates a full SolutionArray and checks it.

model = None
nu_by_posy = None
result

Creates and caches a result from the raw solver_out

solve(solver=None, *, verbosity=1, gen_result=True, **kwargs)

Solves a GeometricProgram and returns the solution.

solver : str or function (optional)
By default uses a solver found during installation. If “mosek_conif”, “mosek_cli”, or “cvxopt”, uses that solver. If 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

solve_log = None
solver_out = None
v_ss = None
class gpkit.constraints.gp.MonoEqualityIndexes

Bases: object

Class to hold MonoEqualityIndexes

gpkit.constraints.gp.fulfill_meq_bounds(missingbounds, meq_bounds)

Bounds variables with monomial equalities

gpkit.constraints.gp.gen_meq_bounds(missingbounds, exps, meq_idxs)

Generate conditional monomial equality bounds

gpkit.constraints.loose module

Implements Loose

class gpkit.constraints.loose.Loose(constraints, *, senstol=None)

Bases: gpkit.constraints.set.ConstraintSet

ConstraintSet whose inequalities must result in an equality.

process_result(result)

Checks that all constraints are satisfied with equality

raiseerror = False
senstol = 1e-05

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

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.

gp(constants=None, **initargs)

Return program version of self

localsolve(solver=None, *, verbosity=1, skipsweepfailures=False, **solveargs)

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.

**solveargs : Passed to solve() call

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, **solveargs)

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.

**solveargs : Passed to solve() call

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, **initargs)

Return program version of self

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.progify(program, return_attr=None)

Generates function that returns a program() and optionally an attribute.

program: NomialData
Class to return, e.g. GeometricProgram or SequentialGeometricProgram
return_attr: string
attribute to return in addition to the program
gpkit.constraints.prog_factories.run_sweep(genfunction, self, solution, skipsweepfailures, constants, sweep, linked, solver, verbosity, **solveargs)

Runs through a sweep.

gpkit.constraints.prog_factories.solvify(genfunction)

Returns function for making/solving/sweeping a program.

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)

Transfers the constant sensitivities back to the original constants

class gpkit.constraints.relax.ConstraintsRelaxed(original_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(original_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.ReprMixin

Recursive container for ConstraintSets and Inequalities

as_hmapslt1(subs)

Yields hmaps<=1 from self.flat()

as_view()

Return a ConstraintSetView of this ConstraintSet.

constrained_varkeys()

Return all varkeys in non-ConstraintSet constraints

flat(yield_if_hasattr=None)

Yields contained constraints, optionally including constraintsets.

idxlookup = {}
latex(excluded=('units', ))

LaTeX representation of a ConstraintSet.

lines_without(excluded)

Lines representation of a ConstraintSet.

name_collision_varkeys()

Returns the set of contained varkeys whose names are not unique

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
str_without(excluded=('unnecessary lineage', 'units'))

String representation of a ConstraintSet.

unique_varkeys = frozenset()
variables_byname(key)

Get all variables with a given name

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.badelement(cns, i, constraint, cause='')

Identify the bad element and raise a ValueError

gpkit.constraints.set.flatiter(iterable, yield_if_hasattr=None)

Yields contained constraints, optionally including constraintsets.

gpkit.constraints.set.recursively_line(iterable, excluded)

Generates lines in a recursive tree-like fashion, the better to indent.

gpkit.constraints.set.sort_constraints_dict(iterable)

Sort a dictionary of {k: constraint} and return its keys and values

gpkit.constraints.sgp module

Implement the SequentialGeometricProgram class

class gpkit.constraints.sgp.SequentialGeometricProgram(cost, model, substitutions, *, use_pccp=True, pccp_penalty=200.0, checkbounds=True)

Bases: object

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, *, cleanx0=False)

Update self._gp for x0 and return it.

gps = None
localsolve(solver=None, *, verbosity=1, x0=None, reltol=0.0001, iteration_limit=50, **solveargs)

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.
mutategp: boolean
Prescribes whether to mutate the previously generated GP or to create a new GP with every solve.
**solveargs :
Passed to solver function.
result : dict
A dictionary containing the translated solver result.
model = None
result = None
results

Creates and caches results from the raw solver_outs

slack = gpkit.Variable(SGP.PCCPslack)
solver_outs = None

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.ReprMixin

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

unicode_opers = {'<=': '≤', '=': '=', '>=': '≥'}

gpkit.constraints.tight module

Implements Tight

class gpkit.constraints.tight.Tight(constraints, *, reltol=None, **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 = 0.001

Module contents

Contains ConstraintSet and related classes and objects