Glossary¶
For an alphabetical listing of all commands, check out the Index
gpkit package¶
Subpackages¶
- gpkit.constraints package
- Submodules
- gpkit.constraints.array module
- gpkit.constraints.bounded module
- gpkit.constraints.costed module
- gpkit.constraints.gp module
- gpkit.constraints.model module
- gpkit.constraints.prog_factories module
- gpkit.constraints.relax module
- gpkit.constraints.set module
- gpkit.constraints.sgp module
- gpkit.constraints.sigeq module
- gpkit.constraints.single_equation module
- gpkit.constraints.tight module
- Module contents
- gpkit.interactive package
- gpkit.nomials package
- gpkit.tools 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
= u'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
= u'mosek'¶
-
patches
= {u'dgopt.c': {u'printf("Number of Hessian non-zeros: %d\\n",nlh[0]->numhesnz);': u'MSK_echotask(task,MSK_STREAM_MSG,"Number of Hessian non-zeros: %d\\n",nlh[0]->numhesnz);'}, u'expopt.c': {u'printf ("solsta = %d, prosta = %d\\n", (int)*solsta,(int)*prosta);': u'MSK_echotask(expopttask,MSK_STREAM_MSG, "solsta = %d, prosta = %d\\n", (int)*solsta,(int)*prosta);', u'printf("Warning: The variable with index \'%d\' has only negative coefficients akj.\\n The problem is possibly ill-posed.\\n",i);': u'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);', u'printf("Warning: The variable with index \'%d\' has only positive coefficients akj.\\n The problem is possibly ill-posed.\\n.\\n",i);': u'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);'}}¶
-
version
= None¶
-
-
class
gpkit.build.
MosekCLI
¶ Bases:
gpkit.build.SolverBackend
MOSEK command line interface finder.
-
look
()¶ Attempts to run mskexpopt.
-
name
= u'mosek_cli'¶
-
-
class
gpkit.build.
MosekConif
¶ Bases:
gpkit.build.SolverBackend
MOSEK exponential cone solver finder.
-
look
()¶ Attempts to import mosek, version >= 9.
-
name
= u'mosek_conif'¶
-
-
class
gpkit.build.
SolverBackend
¶ Bases:
object
Inheritable class for finding solvers. Logs.
-
build
= None¶
-
installed
= False¶
-
look
= None¶
-
name
= None¶
-
-
gpkit.build.
build
()¶ 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.
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
-
exception
gpkit.exceptions.
InvalidPosynomial
¶ Bases:
exceptions.Exception
Raised when a Posynomial would be created with a negative coefficient
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
= {}¶
-
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, firstattempt=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:
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
(k[, d]) → D[k] if k in D, else d. d defaults to None.¶
-
keymap
= []¶
-
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
-
class
gpkit.repr_conventions.
GPkitObject
¶ Bases:
object
This class combines various printing methods for easier adoption.
-
ast
= None¶
-
cached_strs
= None¶
-
latex_unitstr
()¶ Returns latex unitstr
-
lineagestr
(modelnums=True)¶ Returns properly formatted lineage string
-
parse_ast
(excluded=u'units')¶ Turns the AST of this object’s construction into a faithful string
-
unitstr
(into=u'%s', options=u':~', dimless=u'')¶ Returns the string corresponding to an object’s units.
-
-
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=u'%s', options=u':~', dimless=u'')¶ 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.
-
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.
-
to_arrays
()¶ 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})
-
copy
()¶ Return a copy of this
-
hashvalue
= None¶
-
-
class
gpkit.small_classes.
SolverLog
(verbosity=0, output=None, **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
-
class
gpkit.small_scripts.
SweepValue
(value)¶ Bases:
object
Object to represent a swept substitution.
-
gpkit.small_scripts.
appendsolwarning
(msg, data, result, category='uncategorized')¶ Append a particular category of warnings to a solution.
-
gpkit.small_scripts.
get_sweepval
(sub)¶ Returns a given substitution’s indicated sweep, or None.
-
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.
maybe_flatten
(value)¶ Extract values from 0-d numpy arrays, if necessary
-
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.
splitsweep
(sub)¶ 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.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)
-
almost_equal
(sol, reltol=0.001, sens_abstol=0.01)¶ Checks for almost-equality between two solutions
-
diff
(sol, showvars=None, min_percent=1.0, show_sensitivities=True, min_senss_delta=0.1, sortbymodel=True)¶ Outputs differences between this solution and another
- sol : solution or string
- Strings are treated as paths to valid pickled solutions
- min_percent : float
- The smallest percentage difference in the result to consider
- show_sensitivities : boolean
- if True, also computer sensitivity deltas
- min_senss_delta : float
- The smallest absolute difference in sensitivities to consider
str
-
model
= None¶
-
name_collision_varkeys
()¶ Returns the set of contained varkeys whose names are not unique
-
pickle_prep
()¶ After calling this, the SolutionArray is ready to pickle
-
plot
(posys=None, axes=None)¶ Plots a sweep for each posy
-
program
= None¶
-
save
(filename=u'solution.pkl')¶ Pickles the solution and saves it to a file.
- The saved solution is identical except for two things:
- the cost is made unitless
- the solution’s ‘program’ attribute is removed
- the solution’s ‘model’ attribute is removed
- the data field is removed from the solution’s warnings
- (the “message” field is preserved)
Solution can then be loaded with e.g.: >>> import pickle >>> pickle.load(open(“solution.pkl”))
-
savecsv
(showvars=None, filename=u'solution.csv', valcols=5, **kwargs)¶ Saves primal solution as a CSV sorted by modelname, like the tables.
-
savemat
(filename=u'solution.mat', showvars=None, excluded=(u'unnecessary lineage', u'vec'))¶ Saves primal solution as matlab file
-
savetxt
(filename=u'solution.txt', printmodel=True, **kwargs)¶ Saves solution table as a text file
-
subinto
(posy)¶ 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=(u'cost', u'warnings', u'sweepvariables', u'freevariables', u'constants', u'sensitivities', u'tightest constraints'), **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
= {u'constants': u'Constants', u'freevariables': u'Free Variables', u'sweepvariables': u'Sweep Variables', u'variables': u'Variables'}¶
-
todataframe
(showvars=None, excluded=(u'unnecessary lineage', u'vec'))¶ Returns primal solution as pandas dataframe
-
varnames
(showvars, exclude)¶ Returns list of variables, optionally with minimal unique names
-
gpkit.solution_array.
constraint_table
(data, 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.
reldiff
(val1, val2)¶ Relative difference between val1 and val2 (positive if val2 is larger)
-
gpkit.solution_array.
senss_table
(data, showvars=(), title=u'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
-
gpkit.solution_array.
var_table
(data, title, printunits=True, latex=False, rawlines=False, varfmt=u'%s : ', valfmt=u'%-.4g ', vecfmt=u'%-8.3g', minval=0, sortbyvals=False, hidebelowminval=False, included_models=None, excluded_models=None, sortbymodel=True, maxcolumns=5, **_)¶ 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.varkey module¶
Defines the VarKey class
-
class
gpkit.varkey.
VarKey
(name=None, **kwargs)¶ Bases:
gpkit.repr_conventions.GPkitObject
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=())¶ Returns latex representation.
-
models
¶ Returns a tuple of just the names of models in self.lineage
-
str_without
(excluded=())¶ Returns string without certain fields (such as ‘lineage’).
-
subscripts
= (u'lineage', u'idx')¶
-
classmethod
unique_id
()¶ Increment self.count and return it
-
vars_of_a_name
= {}¶
Module contents¶
GP and SP modeling package