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

gpkit package

Submodules module

Finds solvers, sets gpkit settings, and builds gpkit



CVXopt finder.


Attempts to import cvxopt.

name = 'cvxopt'


MOSEK command line interface finder.


Looks in default install locations for a mosek before version 9.

name = 'mosek_cli'
run(where='in the default PATH')

Attempts to run mskexpopt.



MOSEK exponential cone solver finder.


Attempts to import a mosek supporting exponential cones.

name = 'mosek_conif'

Bases: object

Inheritable class for finding solvers. Logs.

look = None
name = None

Builds GPkit

Calls subprocess. Logs., diff_dict)

Applies a simple diff to a file. Logs.

Returns true if there’s a file at $path. Logs.*args)

Print a line and append it to the log string.*args)

Join paths, collating multiple arguments.

Replaces directory at $path. Logs.

gpkit.exceptions module

GPkit-specific Exception classes

exception gpkit.exceptions.DualInfeasible

Bases: gpkit.exceptions.Infeasible

Raised if a model returns a certificate of dual infeasibility

exception gpkit.exceptions.Infeasible

Bases: RuntimeWarning

Raised if a model does not solve

exception gpkit.exceptions.InvalidGPConstraint

Bases: gpkit.exceptions.MathematicallyInvalid

Raised if a non-GP-compatible constraint is used in a GP

exception gpkit.exceptions.InvalidLicense

Bases: RuntimeWarning

Raised if a solver’s license is missing, invalid, or expired.

exception gpkit.exceptions.InvalidPosynomial

Bases: gpkit.exceptions.MathematicallyInvalid

Raised if a Posynomial would be created with a negative coefficient

exception gpkit.exceptions.InvalidSGPConstraint

Bases: gpkit.exceptions.MathematicallyInvalid

Raised if a non-SGP-compatible constraint is used in an SGP

exception gpkit.exceptions.MathematicallyInvalid

Bases: TypeError

Raised whenever something violates a mathematical definition.

exception gpkit.exceptions.PrimalInfeasible

Bases: gpkit.exceptions.Infeasible

Raised if a model returns a certificate of primal infeasibility

exception gpkit.exceptions.UnboundedGP

Bases: ValueError

Raise if a GP is not fully bounded

exception gpkit.exceptions.UnknownInfeasible

Bases: gpkit.exceptions.Infeasible

Raised if a model does not solve for unknown reasons

exception gpkit.exceptions.UnnecessarySGP

Bases: ValueError

Raised if an SGP is fully GP-compatible

gpkit.globals module

global mutable variables

class gpkit.globals.NamedVariables(name)

Bases: object

Creates an environment in which all variables have a model name and num appended to their varkeys.

lineage = ()
modelnums = {((), 'RelaxPCCP'): 1}
namedvars = {}
classmethod reset_modelnumbers()

Clear all model number counters

class gpkit.globals.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()
class gpkit.globals.SignomialsEnabledMeta

Bases: type

Metaclass to implement falsiness for SignomialsEnabled

class gpkit.globals.Vectorize(dimension_length)

Bases: object

Creates an environment in which all variables are exended in an additional dimension.

vectorization = ()
gpkit.globals.load_settings(path=None, trybuild=True)

Load the settings file at SETTINGS_PATH; return settings dict

gpkit.keydict module

Implements KeyDict and KeySet classes

class gpkit.keydict.KeyDict(*args, **kwargs)

Bases: gpkit.keydict.KeyMap, dict

KeyDicts do two things over a dict: map keys and collapse arrays.

>>>> kd = gpkit.keydict.KeyDict()

For mapping keys, see KeyMapper.__doc__

If .collapse_arrays is True then VarKeys which have a shape parameter (indicating they are part of an array) are stored as numpy arrays, and automatically de-indexed when a matching VarKey with a particular idx parameter is used as a key.

See also: gpkit/tests/

collapse_arrays = True
get(key, *alternative)

Return the value for key if key is in the dictionary, else default.

update(*args, **kwargs)

Iterates through the dictionary created by args and kwargs

class gpkit.keydict.KeyMap(*args, **kwargs)

Bases: object

Helper class to provide KeyMapping to interfaces.

A KeyMap keeps an internal list of VarKeys as canonical keys, and their values can be accessed with any object whose key attribute matches one of those VarKeys, or with strings matching any of the multiple possible string interpretations of each key:

For example, after creating the KeyDict kd and setting kd[x] = v (where x is a Variable or VarKey), v can be accessed with by the following keys:

  • x
  • x.key
  • (a string)
  • “x_modelname” (x’s name including modelname)

Note that if a item is set using a key that does not have a .key attribute, that key can be set and accessed normally.

collapse_arrays = False
keymap = []
log_gets = False

Returns key if key had one, and veckey/idx for indexed veckeys.


Updates the keymap with the keys in _unmapped_keys

varkeys = None
vks = None
class gpkit.keydict.KeySet(*args, **kwargs)

Bases: gpkit.keydict.KeyMap, set

KeyMaps that don’t collapse arrays or store values.

collapse_arrays = False

Iterates through the dictionary created by args and kwargs

gpkit.keydict.clean_value(key, value)

Gets the value of variable-less monomials, so that x.sub({x: gpkit.units.m}) and x.sub({x: gpkit.ureg.m}) are equivalent.

Also converts any quantities to the key’s units, because quantities can’t/shouldn’t be stored as elements of numpy arrays.

gpkit.repr_conventions module

Repository for representation standards

class gpkit.repr_conventions.ReprMixin

Bases: object

This class combines various printing methods for easier adoption.

ast = None
cached_strs = None

Returns latex unitstr


Returns properly formatted lineage string


Turns the AST of this object’s construction into a faithful string

unitstr(into='%s', options=':P~', dimless='')

Returns the string corresponding to an object’s units.


Returns latex unitstr

gpkit.repr_conventions.lineagestr(lineage, modelnums=True)

Returns properly formatted lineage string

gpkit.repr_conventions.parenthesize(string, addi=True, mult=True)

Parenthesizes a string if it needs it and isn’t already.

gpkit.repr_conventions.strify(val, excluded)

Turns a value into as pretty a string as possible.

gpkit.repr_conventions.unitstr(units, into='%s', options=':P~', dimless='')

Returns the string corresponding to an object’s units.

gpkit.small_classes module

Miscellaneous small classes

class gpkit.small_classes.CootMatrix(row, col, data)

Bases: object

A very simple sparse matrix representation.


Returns dot product with arg.


Converts to another type of matrix.


Converts to another type of matrix.


Converts to a Scipy sparse csr_matrix


Converts to another type of matrix.


Converts to another type of matrix.


Converts to another type of matrix.

class gpkit.small_classes.Count

Bases: object

Like python 2’s itertools.count, for Python 3 compatibility.


Increment self.count and return it

class gpkit.small_classes.DictOfLists

Bases: dict

A hierarchy of dicionaries, with lists at the bottom.


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


Indexes into each list independently.


Converts all lists into array.

class gpkit.small_classes.FixedScalar

Bases: object

Instances of this class are scalar Nomials with no variables

class gpkit.small_classes.FixedScalarMeta

Bases: type

Metaclass to implement instance checking for fixed scalars

class gpkit.small_classes.HashVector

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})

Return a copy of this

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

Bases: list

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


Append and potentially write the new line.


Generates conversion function.

gpkit.small_scripts module

Assorted helper methods

gpkit.small_scripts.appendsolwarning(msg, data, result, category='uncategorized')

Append a particular category of warnings to a solution.

gpkit.small_scripts.broadcast_substitution(key, array)

Broadcasts input into the shape of a given key

gpkit.small_scripts.initsolwarning(result, category='uncategorized')

Creates a results dictionary for a particular category of warning.


Determines if a given substitution indicates a sweep.


Return magnitude of a Number or Quantity


Extract values from 0-d numpy arrays, if necessary


Splits a substitution into (is_sweepvar, sweepval)

gpkit.small_scripts.try_str_without(item, excluded, *, latex=False)

Try to call item.str_without(excluded); fall back to str(item)

gpkit.small_scripts.veclinkedfn(linkedfn, i)

Generate an indexed linking function.

gpkit.solution_array module

Defines SolutionArray class

class gpkit.solution_array.SolSavingEnvironment(solarray, saveconstraints)

Bases: object

Temporarily removes construction/solve attributes from constraints.

This approximately halves the size of the pickled solution.

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 : NomialArray
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)
>>> senss = [sol.sens(x_min), sol.sens(x_min)]
>>> senss.append(sol["sensitivities"]["variables"]["x_{min}"])
>>> assert all(np.array(senss) == 1)
almost_equal(other, reltol=0.001, sens_abstol=0.01)

Checks for almost-equality between two solutions

static decompress_file(file)

Load a gzip-compressed pickle file

diff(other, showvars=None, *, constraintsdiff=True, senssdiff=False, sensstol=0.1, absdiff=False, abstol=0.1, reldiff=True, reltol=1.0, sortmodelsbysenss=True, **tableargs)

Outputs differences between this solution and another

other : solution or string
strings will be treated as paths to pickled solutions
senssdiff : boolean
if True, show sensitivity differences
sensstol : float
the smallest sensitivity difference worth showing
absdiff : boolean
if True, show absolute differences
abstol : float
the smallest absolute difference worth showing
reldiff : boolean
if True, show relative differences
reltol : float
the smallest relative difference worth showing


modelstr = ''

Returns the set of contained varkeys whose names are not unique

plot(posys=None, axes=None)

Plots a sweep for each posy

save(filename='solution.pkl', *, saveconstraints=True, **pickleargs)

Pickles the solution and saves it to a file.

Solution can then be loaded with e.g.: >>> import pickle >>> pickle.load(open(“solution.pkl”))

save_compressed(filename='solution.pgz', *, saveconstraints=True, **cpickleargs)

Pickle a file and then compress it into a file with extension.

savecsv(filename='solution.csv', *, valcols=5, showvars=None)

Saves primal solution as a CSV sorted by modelname, like the tables.

savejson(filename='solution.json', showvars=None)

Saves solution table as a json file

savemat(filename='solution.mat', *, showvars=None, excluded=('unnecessary lineage', 'vec'))

Saves primal solution as matlab file

savetxt(filename='solution.txt', *, printmodel=True, **kwargs)

Saves solution table as a text file


Returns NomialArray of each solution substituted into posy.

summary(showvars=(), ntopsenss=5, **kwargs)

Print summary table, showing top sensitivities and no constants

table(showvars=(), tables=('cost', 'warnings', 'model sensitivities', 'sweepvariables', 'freevariables', 'constants', 'sensitivities', 'tightest constraints'), sortmodelsbysenss=True, **kwargs)

A table representation of this SolutionArray

tables: Iterable
Which to print of (“cost”, “sweepvariables”, “freevariables”,
“constants”, “sensitivities”)

fixedcols: If true, print vectors in fixed-width format latex: int

If > 0, return latex format (options 1-3); otherwise plain text
included_models: Iterable of strings
If specified, the models (by name) to include
excluded_models: Iterable of strings
If specified, model names to exclude


table_titles = {'choicevariables': 'Choice Variables', 'constants': 'Fixed Variables', 'freevariables': 'Free Variables', 'sweepvariables': 'Swept Variables', 'variables': 'Variables'}
todataframe(showvars=None, excluded=('unnecessary lineage', 'vec'))

Returns primal solution as pandas dataframe

varnames(showvars, exclude)

Returns list of variables, optionally with minimal unique names

gpkit.solution_array.cast(function, val1, val2)

Relative difference between val1 and val2 (positive if val2 is larger)

gpkit.solution_array.constraint_table(data, title, sortbymodel=True, showmodels=True, **_)

Creates lines for tables where the right side is a constraint.

gpkit.solution_array.insenss_table(data, _, maxval=0.1, **kwargs)

Returns insensitivity table lines

gpkit.solution_array.loose_table(self, _, min_senss=1e-05, **kwargs)

Return constraint tightness lines

gpkit.solution_array.msenss_table(data, _, **kwargs)

Returns model sensitivity table lines

gpkit.solution_array.senss_table(data, showvars=(), title='Variable Sensitivities', **kwargs)

Returns sensitivity table lines

gpkit.solution_array.tight_table(self, _, ntightconstrs=5, tight_senss=0.01, **kwargs)

Return constraint tightness lines

gpkit.solution_array.topsenss_filter(data, showvars, nvars=5)

Filters sensitivities down to top N vars

gpkit.solution_array.topsenss_table(data, showvars, nvars=5, **kwargs)

Returns top sensitivity table lines


From an iterable of numbers and arrays, returns the largest magnitude

gpkit.solution_array.var_table(data, title, *, printunits=True, latex=False, rawlines=False, varfmt='%s : ', valfmt='%-.4g ', vecfmt='%-8.3g', minval=0, sortbyvals=False, hidebelowminval=False, included_models=None, excluded_models=None, sortbymodel=True, maxcolumns=5, skipifempty=True, sortmodelsbysenss=None, **_)

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 printunits : bool latex : int

If > 0, return latex format (options 1-3); otherwise plain text
varfmt : string
format for variable names
valfmt : string
format for scalar values
vecfmt : string
format for vector values
minval : float
skip values with all(abs(value)) < minval
sortbyvals : boolean
If true, rows are sorted by their average value instead of by name.
included_models : Iterable of strings
If specified, the models (by name) to include
excluded_models : Iterable of strings
If specified, model names to exclude
gpkit.solution_array.warnings_table(self, _, **kwargs)

Makes a table for all warnings in the solution.

gpkit.units module

wraps pint in gpkit monomials

class gpkit.units.GPkitUnits

Bases: object

Return Monomials instead of Quantitites

division_cache = {}
monomial_cache = {}
multiplication_cache = {}
of_division(numerator, denominator)

Cached unit division. Requires Quantity inputs.

of_product(thing1, thing2)

Cached unit division. Requires united inputs.


Returns a Quantity, caching the result for future retrievals

gpkit.varkey module

Defines the VarKey class

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

Bases: gpkit.repr_conventions.ReprMixin

An object to correspond to each ‘variable name’.

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

VarKey with the given name and descr.


Returns latex representation.


Returns a tuple of just the names of models in self.lineage


Returns string without certain fields (such as ‘lineage’).

subscripts = ('lineage', 'idx')
classmethod unique_id()

Increment self.count and return it

Module contents

GP and SP modeling package