Glossary

For an alphabetical listing of all commands, check out the Index

The GPkit Package

Lightweight GP Modeling Package

For examples please see the examples folder.

Requirements

numpy MOSEK or CVXOPT scipy(optional): for complete sparse matrix support sympy(optional): for latex printing in iPython Notebook

Attributes

settings : dict
Contains settings loaded from ./env/settings
class gpkit.SignomialsEnabled

Bases: object

Class to put up and tear down signomial support in an instance of GPkit.

>>> import gpkit
>>> x = gpkit.Variable("x")
>>> y = gpkit.Variable("y", 0.1)
>>> with SignomialsEnabled():
>>>     constraints = [x >= 1-y]
>>> gpkit.Model(x, constraints).localsolve()
gpkit.disable_signomials()

Disables signomial support in a particular instance of GPkit.

gpkit.disable_units()

Disables units support in a particular instance of GPkit.

Posynomials created after calling this are incompatible with those created before.

If gpkit is imported multiple times, this needs to be run each time.

The correct way to call this is:
import gpkit gpkit.disable_units()
The following will not have the intended effect:
from gpkit import disable_units disable_units()
gpkit.enable_signomials()

Enables signomial support in a particular instance of GPkit.

gpkit.enable_units()

Enables units support in a particular instance of GPkit.

Posynomials created after calling this are incompatible with those created before.

If gpkit is imported multiple times, this needs to be run each time.

Submodules

gpkit.model

Module for creating Model instances.

Example

>>> gp = gpkit.Model(cost, constraints, substitutions)
class gpkit.model.Model(cost=None, constraints=None, substitutions=None, *args, **kwargs)

Bases: object

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 : Signomial (optional)
If this is undeclared, the Model will get its cost and constraints from its “setup” method. This allows for easy inheritance.
constraints : 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.

*args, **kwargs : Passed to the setup method for inheritance.

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

allsubs

All substitutions currently in the Model.

constants

All constants (non-sweep substitutions) currently in the Model.

feasibility(search=['overall', 'constraints', 'constants'], constvars=None, verbosity=0)

Searches for feasibile versions of the Model.

search : list of strings or string
The search(es) to perform. Details on each type below.
constvars : iterable
If declared, only constants in constvars will be changed. Otherwise, all constants can be changed in a constants search.
verbosity : int
If greater than 0, will print a report. Decremented by 1 and passed to solvers.
feasibilities : dict, float, or list

Has an entry for each search; if only one, returns that directly.

“overall” : float
The smallest number each constraint’s less-than side would have to be divided by to make the program feasible.
“constraints” : array of floats
Similar to “overall”, but contains a number for each constraint, and minimizes the product of those numbers.
“constants” : dict of varkeys: floats
A substitution dictionary that would make the program feasible, chosen to minimize the product of new_values/old_values.
>>> from gpkit import Variable, Model, PosyArray
>>> x = Variable("x")
>>> x_min = Variable("x_min", 2)
>>> x_max = Variable("x_max", 1)
>>> m = Model(x, [x <= x_max, x >= x_min])
>>> # m.solve()  # RuntimeWarning!
>>> feas = m.feasibility()
>>>
>>> # USING OVERALL
>>> m.constraints = PosyArray(m.signomials)/feas["overall"]
>>> m.solve()
>>>
>>> # USING CONSTRAINTS
>>> m = Model(x, [x <= x_max, x >= x_min])
>>> m.constraints = PosyArray(m.signomials)/feas["constraints"]
>>> m.solve()
>>>
>>> # USING CONSTANTS
>>> m = Model(x, [x <= x_max, x >= x_min])
>>> m.substitutions.update(feas["constants"])
>>> m.solve()
gp(verbosity=2)
localsolve(solver=None, verbosity=2, skipfailures=True, *args, **kwargs)

Forms a SignomialProgram and attempts to locally 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.
skipfailures : 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 called on a model without Signomials. RuntimeWarning if an error occurs in solving or parsing the solution.

model_nums = defaultdict(<type 'int'>, {})
signomials
signomials_et_al

Get signomials, unsubbed, allsubs in one pass.

solve(solver=None, verbosity=2, skipfailures=True, *args, **kwargs)

Forms a GeometricProgram 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.
skipfailures : 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 called on a model with Signomials. RuntimeWarning if an error occurs in solving or parsing the solution.

sp(verbosity=2)
unsubbed
gpkit.model.form_program(programType, signomials, verbosity=2)

Generates a program and returns it and its solve function.

gpkit.solution_array module

class gpkit.solution_array.SolutionArray

Bases: gpkit.small_classes.DictOfLists

A dictionary (of dictionaries) of lists, with convenience methods.

cost : array variables: dict of arrays sensitivities: dict containing:

monomials : array posynomials : array variables: dict of arrays
localmodels : PosyArray
Local power-law fits (small sensitivities are cut off)
>>> import gpkit
>>> import numpy as np
>>> x = gpkit.Variable("x")
>>> x_min = gpkit.Variable("x_{min}", 2)
>>> sol = gpkit.Model(x, [x >= x_min]).solve(verbosity=0)
>>>
>>> # VALUES
>>> values = [sol(x), sol.subinto(x), sol["variables"]["x"]]
>>> assert all(np.array(values) == 2)
>>>
>>> # SENSITIVITIES
>>> senss = [sol.sens(x_min), sol.senssubinto(x_min)]
>>> senss.append(sol["sensitivities"]["variables"]["x_{min}"])
>>> assert all(np.array(senss) == 1)
getvars(*args)
sens(p)
senssubinto(p)

Returns array of each solution’s sensitivity substituted into p

Returns only scalar values.

subinto(p)

Returns PosyArray of each solution substituted into p.

table(tables=['cost', 'freevariables', 'sweepvariables', 'constants', 'sensitivities'], fixedcols=True)
gpkit.solution_array.parse_result(result, constants, unsubbed, sweep={}, linkedsweep={}, freevar_sensitivity_tolerance=0.0001, localmodel_sensitivity_requirement=0.1)

Parses a GP-like result dict into a SolutionArray-like dict.

gpkit.solution_array.results_table(data, title, minval=0, printunits=True, fixedcols=True, varfmt='%s : ', valfmt='%-.4g ', vecfmt='%-8.3g')

Pretty string representation of a dict of VarKeys Iterable values are handled specially (partial printing)

data: dict whose keys are VarKey’s
data to represent in table

title: string minval: float

skip values with all(abs(value)) < minval

printunits: bool fixedcols: bool

if True, print rhs (val, units, label) in fixed-width cols
varfmt: string
format for variable names
valfmt: string
format for scalar values
vecfmt: string
format for vector values

gpkit.geometric_program

Implement the GeometricProgram class

class gpkit.geometric_program.GeometricProgram(cost, constraints, verbosity=1)

Bases: gpkit.nomial_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

>>> gp = gpkit.geometric_program.GeometricProgram(
                    # minimize
                    x,
                    [   # subject to
                        1/x  # <= 1, implicitly
                    ])
>>> gp.solve()
check_solution(sol, tol=1e-05)

Run a series of checks to mathematically confirm sol solves this GP

sol: dict
solution dict, same format as return type of solve()

RuntimeWarning, if any problems are found

Returns a new GP for the closest feasible point of the current GP.

flavour : str

Specifies the objective function minimized in the search:

“max” (default) : Apply the same slack to all constraints and
minimize that slack. Described in Eqn. 10 of [Boyd2007].
“product” : Apply a unique slack to all constraints and minimize
the product of those slacks. Useful for identifying the most problematic constraints. Described in Eqn. 11 of [Boyd2007]
varname : str
LaTeX name of slack variables.
*args, **kwargs
Passed on to GP initialization.

[Boyd2007] : “A tutorial on geometric programming”, Optim Eng 8:67-122

solve(solver=None, verbosity=1, *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.geometric_program.genA(exps, varlocs)

Generates A matrix from exps and varlocs

exps : list of Hashvectors
Exponents for each monomial in a GP
varlocs : 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.signomial_program

Implement the SignomialProgram class

class gpkit.signomial_program.SignomialProgram(cost, constraints, verbosity=2)

Bases: object

Prepares a collection of signomials for a SP solve.

cost : Constraint
Signomial to minimize when solving
constraints : list of Signomials
Constraints to maintain when solving (implicitly Signomials <= 1)
verbosity : int (optional)
Currently has no effect: SignomialPrograms 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.SignomialProgram(
                    # minimize
                    x,
                    [   # subject to
                        1/x - y/x,  # <= 1, implicitly
                        y/10  # <= 1
                    ])
>>> gp.solve()
localsolve(solver=None, verbosity=1, x0=None, rel_tol=0.0001, iteration_limit=50, *args, **kwargs)

Locally solves a SignomialProgram 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.
rel_tol : 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.
step(x0=None, verbosity=1)

gpkit.nomials

Signomial, Posynomial, Monomial, Constraint, & MonoEQCOnstraint classes

class gpkit.nomials.Constraint(left, right, oper_ge=True)

Bases: gpkit.nomials.Posynomial

A constraint of the general form posynomial <= monomial Stored internally (exps, cs) as a single Posynomial (self <= 1) Usually initialized via operator overloading, e.g. cc = y**2 >= 1 + x Additionally stores input format (lhs vs rhs) in self.left and self.right Form is self.left <= self.right.

TODO: this documentation needs to address Signomial Constraints.

class gpkit.nomials.MonoEQConstraint(m1, m2)

Bases: gpkit.nomials.Constraint

A Constraint of the form Monomial == Monomial. Stored internally as a Monomial Constraint, (1 == self).

class gpkit.nomials.Monomial(exps=None, cs=1, require_positive=True, simplify=True, **descr)

Bases: gpkit.nomials.Posynomial

A Posynomial with only one term

Same as Signomial. Note: Monomial historically supported several different init formats

These will be deprecated in the future, replaced with a single __init__ syntax, same as Signomial.
class gpkit.nomials.Posynomial(exps=None, cs=1, require_positive=True, simplify=True, **descr)

Bases: gpkit.nomials.Signomial

A Signomial with strictly positive cs

Same as Signomial. Note: Posynomial historically supported several different init formats

These will be deprecated in the future, replaced with a single __init__ syntax, same as Signomial.
class gpkit.nomials.Signomial(exps=None, cs=1, require_positive=True, simplify=True, **descr)

Bases: gpkit.nomial_data.NomialData

A representation of a signomial.

exps: tuple of dicts
Exponent dicts for each monomial term
cs: tuple
Coefficient values for each monomial term
require_positive: bool
If True and signomials not enabled, c <= 0 will raise ValueError

Signomial Posynomial (if the input has only positive cs) Monomial (if the input has one term and only positive cs)

diff(wrt)

Derivative of this with respect to a Variable

wrt (Variable):
Variable to take derivative with respect to

Signomial (or Posynomial or Monomial)

mono_approximation(x0)
prod()
sub(substitutions, val=None, require_positive=True)

Returns a nomial with substitued values.

3 == (x**2 + y).sub({‘x’: 1, y: 2}) 3 == (x).gp.sub(x, 3)

substitutions : dict or key
Either a dictionary whose keys are strings, Variables, or VarKeys, and whose values are numbers, or a string, Variable or Varkey.
val : number (optional)
If the substitutions entry is a single key, val holds the value
require_positive : boolean (optional, default is True)
Controls whether the returned value can be a signomial.

Returns substituted nomial.

subsummag(substitutions, val=None)

Returns the sum of the magnitudes of the substituted Signomial.

sum()
to(arg)
value

Self, with values substituted for variables that have values

float, if no symbolic variables remain after substitution (Monomial, Posynomial, or Signomial), otherwise.

gpkit.posyarray

Module for creating PosyArray instances.

Example

>>> x = gpkit.Monomial('x')
>>> px = gpkit.PosyArray([1, x, x**2])
class gpkit.posyarray.PosyArray

Bases: numpy.ndarray

A Numpy array with elementwise inequalities and substitutions.

input_array : array-like

>>> px = gpkit.PosyArray([1, x, x**2])
c
left

Self, sampled one index down, with zeropad

outer(other)

Returns the array and argument’s outer product.

right

Self, sampled one index up, with zeropad

sub(subs, val=None, require_positive=True)

Substitutes into the array

gpkit.small_classes

Miscellaneous small classes

class gpkit.small_classes.CootMatrix

Bases: gpkit.small_classes.CootMatrix

A very simple sparse matrix representation.

append(row, col, data)
dot(arg)
shape = (None, None)
tocoo()
tocsc()
tocsr()

Converts to a Scipy sparse csr_matrix

todense()
todia()
todok()
update_shape()
gpkit.small_classes.CootMatrixTuple

alias of CootMatrix

class gpkit.small_classes.Counter

Bases: object

class gpkit.small_classes.DictOfLists

Bases: dict

A hierarchy of dicionaries, with lists at the bottom.

append(sol)

Appends a dict (of dicts) of lists to all held lists.

atindex(i)

Indexes into each list independently.

toarray(shape=None)

Converts all lists into arrays.

class gpkit.small_classes.HashVector(*args, **kwargs)

Bases: dict

A simple, sparse, string-indexed vector. Inherits from dict.

The HashVector class supports element-wise arithmetic: any undeclared variables are assumed to have a value of zero.

arg : iterable

>>> x = gpkit.nomials.Monomial('x')
>>> exp = gpkit.small_classes.HashVector({x: 2})
class gpkit.small_classes.PosyTuple(exps, cs, varlocs, substitutions)

Bases: tuple

cs

Alias for field number 1

exps

Alias for field number 0

substitutions

Alias for field number 3

varlocs

Alias for field number 2

class gpkit.small_classes.SolverLog(verbosity=0, output=None, *args, **kwargs)

Bases: list

Adds a write method to list so it’s file-like and can replace stdout.

write(writ)
gpkit.small_classes.append_dict(i, o)

Recursviely travels dict o and appends items found in i.

gpkit.small_classes.enlist_dict(i, o)

Recursviely copies dict i into o, placing non-dict items into lists.

gpkit.small_classes.enray_dict(i, o)

Recursively turns lists into numpy arrays.

gpkit.small_classes.index_dict(idx, i, o)

Recursviely travels dict i, placing items at idx into dict o.

gpkit.small_scripts

gpkit.small_scripts.diff(p, vk)
gpkit.small_scripts.flatten(ible, classes)

Flatten an iterable that contains other iterables

l : Iterable
Top-level container
out : list
List of all objects found in the nested iterables
TypeError
If an object is found whose class was not in classes
gpkit.small_scripts.invalid_types_for_oper(oper, a, b)

Raises TypeError for unsupported operations.

gpkit.small_scripts.is_sweepvar(sub)

Determines if a given substitution indicates a sweep.

gpkit.small_scripts.isequal(a, b)
gpkit.small_scripts.latex_num(c)
gpkit.small_scripts.mag(c)

Return magnitude of a Number or Quantity

gpkit.small_scripts.mono_approx(p, x0)
gpkit.small_scripts.unitstr(units, into='%s', options='~', dimless='-')

gpkit.substitution

Module containing the substitution function

gpkit.substitution.get_constants(nomial, substitutions)
gpkit.substitution.separate_subs(nomial, substitutions)

Separate substitutions by type.

gpkit.substitution.simplify_and_mmap(signomials, subs)

Simplifies a list of signomials and returns them with their mmaps.

signomials : list of Signomials

subs : dict
Substitutions to do before simplifying.
signomials : list of simplified Signomials
Signomials with cs that are solely nans and/or zeroes are removed.
mmaps : Map from initial monomials to substitued and simplified one.
See small_scripts.sort_and_simplify for more details.
gpkit.substitution.substitution(nomial, substitutions, val=None)

Efficient substituton into a list of monomials.

varlocs : dict
Dictionary mapping variables to lists of monomial indices.
exps : Iterable of dicts
Dictionary mapping variables to exponents, for each monomial.
cs : list
Coefficient for each monomial.
substitutions : dict
Substitutions to apply to the above.
val : number (optional)
Used to substitute singlet variables.
varlocs_ : dict
Dictionary of monomial indexes for each variable.
exps_ : dict
Dictionary of variable exponents for each monomial.
cs_ : list
Coefficients each monomial.
subs_ : dict
Substitutions to apply to the above.
gpkit.substitution.vectorsub(subs, var, sub, varset)

Vectorized substitution

gpkit.tools module

Non-application-specific convenience methods for GPkit

gpkit.tools.composite_objective(*objectives, **kwargs)
gpkit.tools.getvarkey(var)
gpkit.tools.getvarstr(var)
gpkit.tools.te_exp_minus1(posy, nterm)

Taylor expansion of e^{posy} - 1

posy : gpkit.Posynomial
Variable or expression to exponentiate
nterm : int
Number of terms in resulting Taylor expansion
gpkit.Posynomial
Taylor expansion of e^{posy} - 1, carried to nterm terms
gpkit.tools.zero_lower_unbounded(model)

Recursively substitutes 0 for a Model’s variables that lack a lower bound

gpkit.variables module

gpkit.variables.ArrayVariable

alias of VectorVariable

class gpkit.variables.Variable(*args, **descr)

Bases: gpkit.nomials.Monomial

descr
sub(*args, **kwargs)

Same as nomial substitution, but also allows single-argument calls

x = Variable(‘x’) assert x.sub(3) == Variable(‘x’, value=3)

varkey

Get the VarKey associated with this Variable

class gpkit.variables.VectorVariable

Bases: gpkit.posyarray.PosyArray

A described vector of singlet Monomials.

shape : int or tuple
length or shape of resulting array
*args :
may contain “name” (Strings)
“value” (Iterable) “units” (Strings + Quantity)

and/or “label” (Strings)

**descr :
VarKey description

PosyArray of Monomials, each containing a VarKey with name ‘$name_{i}’, where $name is the vector’s name and i is the VarKey’s index.

gpkit.varkey module

Defines the VarKey class

class gpkit.varkey.VarKey(name=None, **kwargs)

Bases: object

An object to correspond to each ‘variable name’.

name : str, VarKey, or Monomial
Name of this Variable, or object to derive this Variable from.
**kwargs :
Any additional attributes, which become the descr attribute (a dict).

VarKey with the given name and descr.

name

name of this VarKey

new_unnamed_id = <gpkit.small_classes.Counter object>
units

units of this VarKey