Glossary¶
For an alphabetical listing of all commands, check out the Index
Subpackages¶
- gpkit.constraints package
- Submodules
- gpkit.constraints.array module
- gpkit.constraints.bounded module
- gpkit.constraints.costed module
- gpkit.constraints.linked module
- gpkit.constraints.model module
- gpkit.constraints.prog_factories module
- gpkit.constraints.set module
- gpkit.constraints.signomial_program module
- gpkit.constraints.single_equation module
- gpkit.constraints.tight module
- Module contents
- gpkit.interactive package
- gpkit.nomials package
- gpkit.tests package
- Submodules
- gpkit.tests.helpers module
- gpkit.tests.run_tests module
- gpkit.tests.t_constraints module
- gpkit.tests.t_examples module
- gpkit.tests.t_keydict module
- gpkit.tests.t_model module
- gpkit.tests.t_nomial_array module
- gpkit.tests.t_nomials module
- gpkit.tests.t_small module
- gpkit.tests.t_solution_array module
- gpkit.tests.t_sub module
- gpkit.tests.t_tools module
- gpkit.tests.t_vars module
- Module contents
- 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 mskexpopt.
-
name
= 'cvxopt'¶
-
-
class
gpkit.build.
Mosek
¶ Bases:
gpkit.build.SolverBackend
MOSEK finder and builder.
-
build
()¶ Builds a dynamic library to GPKITBUILD or $HOME/.gpkit
-
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 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);', ' 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);'}}¶
-
-
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.
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.feasibility module¶
Module for assessing feasibility of GPs and SPs
-
gpkit.feasibility.
feasibility_model
(program, flavour='max', varname=None, constants=None, signomials=None, programType=None)¶ 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 slack variables.. Useful for identifying the most problematic constraints. Described in Eqn. 11 of [Boyd2007]
- “constants” : Slack the constants of a problem and minimize the product
- of those slack variables.
- varname : str
- LaTeX name of slack variables.
- program : Program of the same type as the input
- (Model, GeometricProgram, or SignomialProgram)
[Boyd2007] : “A tutorial on geometric programming”, Optim Eng 8:67-122
gpkit.geometric_program module¶
Implement the GeometricProgram class
-
class
gpkit.geometric_program.
GeometricProgram
(cost, constraints, substitutions=None, verbosity=1)¶ Bases:
gpkit.nomials.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 if solution status is optimal
>>> gp = gpkit.geometric_program.GeometricProgram( # minimize x, [ # subject to 1/x # <= 1, implicitly ]) >>> gp.solve()
-
check_solution
(cost, primal, nu, la, tol=1e-05)¶ Run a series of checks to mathematically confirm sol 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
RuntimeWarning, if any problems are found
-
latex
()¶ LaTeX representation of a GeometricProgram.
-
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.keydict module¶
Implements KeyDict and KeySet classes
-
class
gpkit.keydict.
KeyDict
(*args, **kwargs)¶ Bases:
dict
KeyDicts allow storing and accessing the same value with multiple keys
A KeyDict keeps an internal list of VarKeys as canonical keys, but allows accessing their values with any object whose key attribute matches one of those VarKeys, or with strings who match any of the multiple possible string interpretations of each key.
Creating a KeyDict: >>>> kd = gpkit.keydict.KeyDict()
Now kd[x] can be set, where x is any gpkit Variable or VarKey. __getitem__ is such that kd[x] can be accessed using:
- x
- x.key
- x.name (a string)
- “x_modelname” (x’s name including modelname)
In addition, 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.
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.
See also: gpkit/tests/t_keydict.py.
-
collapse_arrays
= 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
-
class
gpkit.keydict.
KeySet
(*args, **kwargs)¶ Bases:
gpkit.keydict.KeyDict
KeySets are KeyDicts without values, serving only to filter and map keys
-
add
(item)¶ Adds an item to the keyset
-
collapse_arrays
= False¶
-
update
(*args, **kwargs)¶ Iterates through the dictionary created by args and kwargs
-
gpkit.modified_ctypesgen module¶
gpkit.repr_conventions module¶
Repository for representation standards
gpkit.small_classes module¶
Miscellaneous small classes
-
class
gpkit.small_classes.
CootMatrix
¶ Bases:
gpkit.small_classes.CootMatrix
A very simple sparse matrix representation.
-
append
(row, col, data)¶ Appends entry to matrix.
-
dot
(arg)¶ Returns dot product with arg.
-
shape
= None¶
-
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.
-
-
gpkit.small_classes.
CootMatrixTuple
¶ alias of
CootMatrix
-
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_united_array
(unitless_keys=(), united=False)¶ Converts all lists into array, potentially grabbing units from keys.
-
-
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.
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.
unitstr
(units, into='%s', options='~', dimless='-')¶ Returns the unitstr of a given object.
-
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)
-
program
= None¶
-
subinto
(posy)¶ Returns NomialArray of each solution substituted into posy.
-
table
(tables=('cost', 'sweepvariables', 'freevariables', 'constants', 'sensitivities'), latex=False, **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
= {'freevariables': 'Free Variables', 'variables': 'Variables', 'cost': 'Cost', 'sweepvariables': 'Sweep Variables', 'sensitivities': 'Sensitivities', 'constants': 'Constants'}¶
-
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)) < minvalprintunits: 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.varkey module¶
Defines the VarKey class
-
class
gpkit.varkey.
Count
¶ Bases:
object
Like python 2’s itertools.count, for Python 3 compatibility.
-
next
()¶ Increment self.count and return it
-
-
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.
-
eq_ignores
= frozenset(['units', 'value'])¶
-
latex
(excluded=None)¶ Returns latex representation.
-
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
()¶ Returns latex unitstr
Module contents¶
GP and SP 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.
GPkitUnits
¶ Bases:
object
Return monomials instead of Quantitites
-
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_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_units
(path=None)¶ 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.
-
gpkit.
load_settings
(path='/home/docs/checkouts/readthedocs.org/user_builds/gpkit/envs/v0.4.2/local/lib/python2.7/site-packages/gpkit/env/settings')¶ Load the settings file at SETTINGS_PATH; return settings dict