Glossary

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

gpkit package

Submodules

gpkit.build module

Finds solvers, sets gpkit settings, and builds gpkit

class gpkit.build.CVXopt

Bases: gpkit.build.SolverBackend

CVXopt finder.

look()

Attempts to import cvxopt.

name = 'cvxopt'
class gpkit.build.Mosek

Bases: gpkit.build.SolverBackend

MOSEK finder and builder.

bin_dir = None
build()

Builds a dynamic library to GPKITBUILD or $HOME/.gpkit

expopt_files = None
flags = None
lib_name = None
lib_path = None
look()

Looks in default install locations for latest mosek version.

name = 'mosek'
patches = {'dgopt.c': {'printf("Number of Hessian non-zeros: %d\\n",nlh[0]->numhesnz);': 'MSK_echotask(task,MSK_STREAM_MSG,"Number of Hessian non-zeros: %d\\n",nlh[0]->numhesnz);'}, 'expopt.c': {'printf("Warning: The variable with index \'%d\' has only positive coefficients akj.\\n The problem is possibly ill-posed.\\n.\\n",i);': 'MSK_echotask(expopttask,MSK_STREAM_MSG, "Warning: The variable with index \'%d\' has only positive coefficients akj.\\n The problem is possibly ill-posed.\\n.\\n",i);', 'printf("Warning: The variable with index \'%d\' has only negative coefficients akj.\\n The problem is possibly ill-posed.\\n",i);': 'MSK_echotask(expopttask,MSK_STREAM_MSG, "Warning: The variable with index \'%d\' has only negative coefficients akj.\\n The problem is possibly ill-posed.\\n",i);', 'printf ("solsta = %d, prosta = %d\\n", (int)*solsta,(int)*prosta);': 'MSK_echotask(expopttask,MSK_STREAM_MSG, "solsta = %d, prosta = %d\\n", (int)*solsta,(int)*prosta);'}}
version = None
class gpkit.build.MosekCLI

Bases: gpkit.build.SolverBackend

MOSEK command line interface finder.

look()

Attempts to run mskexpopt.

name = 'mosek_cli'
class gpkit.build.SolverBackend

Bases: object

Inheritable class for finding solvers. Logs.

build = None
installed = False
look = None
name = None
gpkit.build.build_gpkit()

Builds GPkit

gpkit.build.call(cmd)

Calls subprocess. Logs.

gpkit.build.diff(filename, diff_dict)

Applies a simple diff to a file. Logs.

gpkit.build.isfile(path)

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

gpkit.build.log(*args)

Print a line and append it to the log string.

gpkit.build.pathjoin(*args)

Join paths, collating multiple arguments.

gpkit.build.rebuild()

Changes to the installed gpkit directory and runs build_gpkit()

gpkit.build.replacedir(path)

Replaces directory at $path. Logs.

gpkit.exceptions module

GPkit-specific Exception classes

exception gpkit.exceptions.InvalidGPConstraint

Bases: exceptions.Exception

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

gpkit.globals module

global mutable variables

class gpkit.globals.NamedVariables(model)

Bases: object

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

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.Vectorize(dimension_length)

Bases: object

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

gpkit.globals.begin_variable_naming(model)

Appends a model name and num to the environment.

gpkit.globals.end_variable_naming()

Pops a model name and num from the environment.

gpkit.globals.load_settings(path=None)

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

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

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

If .keymapping is True, a KeyDict 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
  • x.name (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.

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/t_keydict.py.

collapse_arrays = True
get(key, alternative=<type 'exceptions.KeyError'>)
keymapping = True
parse_and_index(key)

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

update(*args, **kwargs)

Iterates through the dictionary created by args and kwargs

update_keymap()

Updates the keymap with the keys in _unmapped_keys

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

Bases: gpkit.keydict.KeyDict

KeyDicts that don’t collapse arrays or store values.

add(item)

Adds an item to the keyset

collapse_arrays = False
update(*args, **kwargs)

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

gpkit.repr_conventions.unitstr(units, into='%s', options='~', 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.

append(row, col, data)

Appends entry to matrix.

dot(arg)

Returns dot product with arg.

tocoo()

Converts to another type of matrix.

tocsc()

Converts to another type of matrix.

tocsr()

Converts to a Scipy sparse csr_matrix

todense()

Converts to another type of matrix.

todia()

Converts to another type of matrix.

todok()

Converts to another type of matrix.

class gpkit.small_classes.Count

Bases: object

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

next()

Increment self.count and return it

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.

classify(cls)

Converts dictionaries whose first key isn’t a string to given class.

to_united_array(unitless_keys=(), united=False)

Converts all lists into array, potentially grabbing units from keys.

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

Return a copy of this

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)

Append and potentially write the new line.

gpkit.small_classes.matrix_converter(name)

Generates conversion function.

gpkit.small_scripts module

Assorted helper methods

gpkit.small_scripts.is_sweepvar(sub)

Determines if a given substitution indicates a sweep.

gpkit.small_scripts.latex_num(c)

Returns latex string of numbers, potentially using exponential notation.

gpkit.small_scripts.mag(c)

Return magnitude of a Number or Quantity

gpkit.small_scripts.nomial_latex_helper(c, pos_vars, neg_vars)

Combines (varlatex, exponent) tuples, separated by positive vs negative exponent, into a single latex string

gpkit.small_scripts.try_str_without(item, excluded)

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

gpkit.small_scripts.veckeyed(key)

Return a veckey version of a VarKey

gpkit.solution_array module

Defines SolutionArray class

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)
>>>
>>> # SENSITIVITIES
>>> senss = [sol.sens(x_min), sol.sens(x_min)]
>>> senss.append(sol["sensitivities"]["variables"]["x_{min}"])
>>> assert all(np.array(senss) == 1)
plot(posys=None, axes=None)

Plots a sweep for each posy

program = None
subinto(posy)

Returns NomialArray of each solution substituted into posy.

summary(showvars=(), ntopsenss=5)

Print summary table, showing top sensitivities and no constants

table(showvars=(), tables=('cost', 'sweepvariables', 'freevariables', 'constants', 'sensitivities'), **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

str

table_titles = {'variables': 'Variables', 'freevariables': 'Free Variables', 'sweepvariables': 'Sweep Variables', 'constants': 'Constants'}
gpkit.solution_array.insenss_table(data, _, maxval=0.1, **kwargs)

Returns insensitivity table lines

gpkit.solution_array.results_table(data, title, minval=0, printunits=True, fixedcols=True, varfmt='%s : ', valfmt='%-.4g ', vecfmt='%-8.3g', included_models=None, excluded_models=None, latex=False, sortbyvals=False, **_)

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
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
sortbyvals : boolean
If true, rows are sorted by their average value instead of by name.
gpkit.solution_array.senss_table(data, showvars=(), title='Sensitivities', **kwargs)

Returns sensitivity table 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

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.

latex(excluded=None)

Returns latex representation.

latex_unitstr()

Returns latex unitstr

naming

Returns this varkey’s naming tuple

new_unnamed_id()

Increment self.count and return it

str_without(excluded=None)

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

subscripts = ('models', 'idx')
unitstr(units, into='%s', options='~', dimless='')

Returns the string corresponding to an object’s units.

Module contents

GP and SP modeling package