Core Classes#
PEPBuilder#
- class pepflow.PEPBuilder(pep_context: PEPContext)#
The main class for Primal and Dual PEP formulation.
- Variables:
ctx (
PEPContext) – ThePEPContextassociated with thisPEPBuilderobject.init_conditions (list[
PSDConstraint|ScalarConstraint]) – A list of all the initial conditions associated with this PEP.performance_metric (
Scalar) – The performance metric for this PEP.relaxed_constraints (list[str]) – A list of names of the constraints that will be ignored when the Primal or Dual PEP is constructed.
dual_val_constraint (dict[str, list[tuple[str, float]]]) – A dictionary of the form {constraint_name: [(op, val)]}. The constraint_name is the name of the constraint the dual variable is associated with. The op is a string for the type of relation, i.e., le, ge, eq, <=, >=, or ==. The val is the value for the other side of the constraint. For example, consider {“f:x_1,x_0”, [(“eq”, 0)]}. Denote the associated dual variable as \(\lambda_{1,0}\). Then, this means to add a constraint of the form \(\lambda_{1,0} = 0\) to the Dual PEP. Because it is hard to judge if the constraint associated with constraint_name is active, we suggest to not add dual variable constraints manually but instead use the interactive dashboard.
Example
>>> pep_builder = pf.PEPBuilder(ctx)
- add_initial_constraint(constraint: PSDConstraint | ScalarConstraint)#
Add an initial condition.
- Parameters:
constraint (
PSDConstraint|ScalarConstraint) – APSDConstraintorScalarConstraintobject that represents the desired initial condition.
Example
>>> import pepflow as pf >>> f = pf.SmoothConvexFunction(is_basis=True, tags=["f"], L=1) >>> ctx = pf.PEPContext("ctx").set_as_current() >>> x = pf.Vector(is_basis=True, tags=["x_0"]) >>> x_star = f.set_stationary_point("x_star") >>> pb = pf.PEPBuilder(ctx) >>> pb.add_initial_constraint( ... ((x_0 - x_star) ** 2).le(R**2, name="initial_condition") ... )
- clear_setup()#
Resets the
PEPBuilderobject. Does not reset the ctx attribute.
- set_performance_metric(metric: Scalar)#
Set the performance metric.
Example
>>> pb.set_performance_metric(f(x_N) - f(x_star))
- set_relaxed_constraints(relaxed_constraints: list[str])#
Set the constraints that will be ignored.
- Parameters:
relaxed_constraints (list[str]) – A list of names of constraints that will be ignored.
- solve_dual(context: PEPContext | None = None, resolve_parameters: dict[str, NUMERICAL_TYPE] | None = None)#
Solve the Dual PEP associated with this
PEPBuilderobject using the givenPEPContextobject.- Parameters:
context (
PEPContext) – ThePEPContextobject used to solve the Dual PEP associated with thisPEPBuilderobject. None if we consider the current globalPEPContextobject.resolve_parameters (dict[str,
NUMERICAL_TYPE] | None) – A dictionary that maps the name of parameters to the numerical values.
- Returns:
PEPResult– APEPResultobject that contains the information obtained after solving the Dual PEP associated with thisPEPBuilderobject.
- solve_primal(context: PEPContext | None = None, resolve_parameters: dict[str, NUMERICAL_TYPE] | None = None)#
Solve the Primal PEP associated with this
PEPBuilderobject using the givenPEPContextobject.- Parameters:
context (
PEPContext) – ThePEPContextobject used to solve the Primal PEP associated with thisPEPBuilderobject. None if we consider the current globalPEPContextobject.resolve_parameters (dict[str,
NUMERICAL_TYPE] | None) – A dictionary that maps the name of parameters to the numerical values.
- Returns:
PEPResult– APEPResultobject that contains the information obtained after solving the Primal PEP associated with thisPEPBuilderobject.
PEPContext#
- class pepflow.PEPContext(name: str)#
A
PEPContextobject is a context manager which maintains the abstract mathematical objects of the Primal and Dual PEP.- Variables:
name (str) – The unique name of the
PEPContextobject.
Note
If the provided name matches the name of a previously created
PEPContextobject, the previously createdPEPContextwill be overwritten in the GLOBAL_CONTEXT_DICT.Example
>>> ctx = pf.PEPContext("ctx").set_as_current()
- basis_scalars() list[Scalar]#
Return a list of the basis
Scalarobjects managed by thisPEPContext.The order is of the list is in terms of when the basis
Scalarobjects are added.- Returns:
list[
Scalar] – A list of the basisScalarobjects managed by thisPEPContext.
Example
>>> import pepflow as pf >>> f = pf.SmoothConvexFunction(is_basis=True, tags=["f"], L=1) >>> ctx = pf.PEPContext("ctx").set_as_current() >>> f.set_stationary_point("x_star") >>> ctx.basis_scalars()
- basis_scalars_math_exprs() list[str]#
Return a list of the math expressions of the basis
Scalarobjects managed by thisPEPContext.The order is of the list is in terms of when the basis
Scalarobjects are added.- Returns:
list[str] – A list of the tags of the basis
Scalarobjects managed by thisPEPContext.
- basis_vectors() list[Vector]#
Return a list of the basis
Vectorobjects managed by thisPEPContext.The order is of the list is in terms of when the basis
Vectorobjects are added.- Returns:
list[
Vector] – A list of the basisVectorobjects managed by thisPEPContext.
- basis_vectors_math_exprs() list[str]#
Return a list of the math expressions of the basis
Vectorobjects managed by thisPEPContext.The order is of the list is in terms of when the basis
Vectorobjects are added.- Returns:
list[str] – A list of the tags of the basis
Vectorobjects managed by thisPEPContext.
- clear() None#
Reset this
PEPContextobject.
- get_by_tag(tag: str)#
Under this
PEPContext, get theVectororScalarobject associated with the provided tag.
- get_duplet_by_point_tag(point_or_tag: Vector | str, op: Operator) Duplet#
Returns a duplet of the given point or its tag in the operator.
- get_triplet_by_point_tag(point_or_tag: Vector | str, func: Function) Triplet#
Returns a triplet of the given point or its tag in the function.
- set_as_current() PEPContext#
Set this
PEPContextobject as the global context.- Returns:
PEPContext– ThisPEPContextobject.
Example
>>> ctx = pf.PEPContext("ctx").set_as_current()
- tracked_func_val(func: Function) list[Scalar]#
This function returns a list of the visited function values \(\{f(x_i)\}\) under this
PEPContext.Each function \(f\) used in Primal and Dual PEP is associated with a set of triplets \(\{x_i, f(x_i), \nabla f(x_i)\}\) visited by the considered algorithm. We can also consider a subgradient \(\widetilde{\nabla} f(x)\) instead of the gradient \(\nabla f(x_i)\).
- tracked_grad(func: Function) list[Vector]#
This function returns a list of the visited gradients \(\{\nabla f(x_i)\}\) under this
PEPContext.Each function \(f\) used in Primal and Dual PEP is associated with a set of triplets \(\{x_i, f(x_i), \nabla f(x_i)\}\) visited by the considered algorithm. We can also consider a subgradient \(\widetilde{\nabla} f(x)\) instead of the gradient \(\nabla f(x_i)\).
- tracked_output(oper: Operator) list[Vector]#
This function returns a list of the visited outputs \(\{A(x_i)\}\) under this
PEPContext.Each operator \(A\) used in Primal and Dual PEP is associated with a set of duplets \(\{x_i, A(x_i)\}\) visited by the considered algorithm.
- tracked_point(func_or_oper: Function | Operator) list[Vector]#
Returns a list of the visited vectors \(\{x_i\}\) associated with func_or_oper under this
PEPContext.Each function \(f\) used in Primal and Dual PEP is associated with a set of triplets \(\{x_i, f(x_i), \nabla f(x_i)\}\) visited by the considered algorithm. We can also consider a subgradient \(\widetilde{\nabla} f(x)\) instead of the gradient.
- pepflow.get_current_context() PEPContext | None#
Return the current global
PEPContext.- Returns:
PEPContext– The current globalPEPContext.
- pepflow.set_current_context(ctx: PEPContext | None)#
Change the current global
PEPContext.- Parameters:
ctx (
PEPContext) – ThePEPContextto set as the new globalPEPContext.
Example
>>> ctx = pf.PEPContext(ctx).set_as_current()
Registry Functions#
PEPResult#
- class pepflow.PEPResult(opt_value: float, dual_var_manager: PrimalPEPDualVarManager | DualPEPDualVarManager, pep_type: PEPType, solver_status: Any, context: PEPContext)#
A data class object that contains the results of solving the PEP.
- Variables:
opt_value (float) – The objective value of the solved Primal or Dual PEP.
dual_var_manager (
PrimalPEPDualVarManagerorDualPEPDualVarManager) – A manager object which provides access to the dual variables associated with the constraints of the Primal PEP or the dual variables that correspond to the constraints of the Dual PEP.pep_type (
PEPType) – The type of the solved PEP, either “primal” or “dual”.solver_status (Any) – States whether the solver managed to solve the Primal/Dual PEP successfully.
context (
PEPContext) – ThePEPContextobject used to solve the PEP.
Example
>>> result = ctx.solve(resolve_parameters={"L": 1}) >>> opt_value = result.opt_value
- get_gram_dual_matrix() MatrixWithNames#
Return the Gram dual variable matrix associated with the constraint that the Primal PEP decision variable \(G\) is PSD.
- Returns:
MatrixWithNames– The PSD dual variable matrix associated with the constraint that the Primal PEP decision variable \(G\) is PSD.
- get_matrix_constraint_dual_values(func_or_oper: Function | Operator) dict[str, np.ndarray]#
Return a dictionary that maps the names of the PSD constraints to their corresponding dual variable matrices.
- get_scalar_constraint_dual_value_in_numpy(func_or_oper: Function | Operator) dict[str, MatrixWithNames] | MatrixWithNames#
Return a dictionary that maps the names of the scalar constraints to their corresponding dual variables.
- Parameters:
func_or_oper (
Function|Operator) – TheFunctionorOperatorobject whose scalar constraints’ dual variables we want to retrieve.- Returns:
dict[str,
MatrixWithNames] – A dictionary that maps the names of the scalar constraints to their corresponding dual variable matrices stored in aMatrixWithNames.
- get_scalar_constraint_dual_value_in_pandas(func_or_oper: Function | Operator) dict[str, pd.DataFrame] | pd.DataFrame#
Return a dictionary that maps the names of the scalar constraints to their corresponding dual variables.
- Parameters:
func_or_oper (
Function|Operator) – TheFunctionorOperatorobject whose scalar constraints’ dual variables we want to retrieve.- Returns:
dict[str, pd.dataframe] – A dictionary that maps the names of the scalar constraints to their corresponding dual variable matrices stored in a DataFrame.
- class pepflow.MatrixWithNames(matrix: ndarray, row_names: list[str], col_names: list[str])#
A data class that stores a matrix along with the names of its rows and columns.
You can access a specific element by providing its row and column labels.
- Variables:
matrix (np.ndarray) – A matrix.
row_names (list[str]) – A list of the names of the rows of the matrix.
col_names (list[str]) – A list of the names of the columns of the matrix.
- pprint() None#
Prints a matrix with corresponding row and column labels.
- to_dataframe() DataFrame#
Convert the matrix to a pandas DataFrame with row and column names.
ExpressionManager#
- class pepflow.ExpressionManager(pep_context: pc.PEPContext, resolve_parameters: dict[str, NUMERICAL_TYPE] | None = None)#
A class handling concrete representations of abstract
VectorandScalarobjects managed by a particularPEPContextobject.- Variables:
context (
PEPContext) – ThePEPContextobject which manages the abstractVectorandScalarobjects of interest.resolve_parameters (dict[str,
NUMERICAL_TYPE] | None) – A dictionary that maps the name of parameters to the numerical values.
- eval_scalar(scalar: Scalar | Parameter | float | int, sympy_mode: bool = False)#
Return the concrete representation of the
Scalar,Parameter, float, or int.Concrete representations of
Scalarobjects areEvaluatedScalarobjects. Concrete representations of float or int arguments are themselves. If aParameterobject is passed in, the function will return the corresponding value stored in resolve_parameters.- Parameters:
scalar (
Scalar,Parameter, float, int) – The abstractScalar,Parameter, float, or int object whose concrete representation we want to find.sympy_mode (bool) – If true, then the input should be defined completely in terms of SymPy objects and should not mix Python numeric objects. Will raise an error if sympy_mode is True and the input contains a Python numeric object. By default False.
- Returns:
EvaluatedScalar| float | int – The concrete representation of the scalar argument.
Example
>>> import pepflow as pf >>> import numpy as np >>> ctx = pf.PEPContext("ctx").set_as_current() >>> f = pf.SmoothConvexFunction(is_basis=True, tags=["f"], L=1) >>> x_0 = pf.Vector(is_basis=True, tags=["x_0"]) >>> f_0 = f(x_0) >>> pm = pf.ExpressionManager(ctx) >>> pm.eval_scalar(f_0).func_coords == np.array([1, 0]) >>> pm.eval_scalar(x_0**2).inner_prod_coords == np.array([[1, 0], [0, 0]])
- eval_vector(vector: Vector | Parameter | float | int, sympy_mode: bool = False)#
Return the concrete representation of the
Vector,Parameter, float, or int.Concrete representations of
Vectorobjects areEvaluatedVectorobjects. Concrete representations of float or int arguments are themselves. If aParameterobject is passed in, the function will return the corresponding value stored in resolve_parameters.- Parameters:
vector (
Vector,Parameter, float, int) – The abstractVector,Parameter, float, or int object whose concrete representation we want to find.sympy_mode (bool) – If true, then the input should be defined completely in terms of SymPy objects and should not mix Python numeric objects. Will raise an error if sympy_mode is True and the input contains a Python numeric object. By default False.
- Returns:
EvaluatedVector| float | int – The concrete representation of the vector argument.
Example
>>> import pepflow as pf >>> import numpy as np >>> ctx = pf.PEPContext("ctx").set_as_current() >>> f = pf.SmoothConvexFunction(is_basis=True, tags=["f"], L=1) >>> x_0 = pf.Vector(is_basis=True, tags=["x_0"]) >>> pm.eval_vector(x_0).coords == np.array([1])
- repr_evaluated_scalar_by_basis(evaluated_scalar: EvaluatedScalar, greedy_square: bool = False) str#
Express the
EvaluatedScalarobject using the basisVectorandScalarobjects of the associatedPEPContext.A
Scalarcan be formed by linear combinations of basisScalarobjects. AScalarcan also be formed through the inner product of two basisVectorobjects. This function returns the representation of thisScalarobject in terms of the basisVectorandScalarobjects as a str.- Parameters:
evaluated_scalar (
EvaluatedScalar) – TheEvaluatedScalarobject which we want to express in terms of the basisVectorandScalarobjects.greedy_square (bool) – If greedy_square is true, the function will try to return \(\|a-b\|^2\) whenever possible. If not, the function will return \(\|a\|^2 - 2 * \langle a, b \rangle + \|b\|^2\) instead. True by default.
- Returns:
str – The representation of evaluated_scalar in terms of the basis
VectorandScalarobjects of thePEPContextassociated with thisExpressionManager.
- repr_evaluated_vector_by_basis(evaluated_vector: EvaluatedVector) str#
Express the
EvaluatedVectorobject as the linear combination of the basisVectorobjects of the associatedPEPContext.This linear combination is expressed as a str.
- Parameters:
evaluated_vector (
EvaluatedVector) – TheEvaluatedVectorobject which we want to express in terms of the basisVectorobjects.- Returns:
str – The representation of evaluated_vector in terms of the basis
Vectorobjects of thePEPContextassociated with thisExpressionManager.
- repr_scalar_by_basis(scalar: Scalar, *, greedy_square: bool = False, sympy_mode: bool = False) str#
Express the
Scalarobject using the basisVectorandScalarobjects of the associatedPEPContext.A
Scalarcan be formed by linear combinations of basisScalarobjects. AScalarcan also be formed through the inner product of two basisVectorobjects. This function returns the representation of thisScalarobject in terms of the basisVectorandScalarobjects as a str.- Parameters:
scalar (
Scalar) – TheScalarobject which we want to express in terms of the basisVectorandScalarobjects.greedy_square (bool) – If greedy_square is true, the function will try to return \(\|a-b\|^2\) whenever possible. If not, the function will return \(\|a\|^2 - 2 * \langle a, b \rangle + \|b\|^2\) instead. True by default.
sympy_mode (bool) – If true, then the input should be defined completely in terms of SymPy objects and should not mix Python numeric objects. Will raise an error if sympy_mode is True and the input contains a Python numeric object. By default False.
- Returns:
str – The representation of scalar in terms of the basis
VectorandScalarobjects of thePEPContextassociated with thisExpressionManager.
- repr_vector_by_basis(vector: Vector, *, sympy_mode: bool = False) str#
Express the
Vectorobject as the linear combination of the basisVectorobjects of the associatedPEPContext.This linear combination is expressed as a str.
- Parameters:
vector (
Vector) – TheVectorobject which we want to express in terms of the basisVectorobjects.sympy_mode (bool) – If true, then the input should be defined completely in terms of SymPy objects and should not mix Python numeric objects. Will raise an error if sympy_mode is True and the input contains a Python numeric object. By default False.
- Returns:
str – The representation of vector in terms of the basis
Vectorobjects of thePEPContextassociated with thisExpressionManager.
- pepflow.represent_matrix_by_basis(matrix: ndarray, ctx: PEPContext, greedy_square: bool = False) str#
Express the matrix in terms of the basis
Vectorobjects of thePEPContext.The concrete representation of the inner product of two abstract basis
Vectorobjects is a matrix (the outer product of the basis vectors corresponding to the concrete representations of the abstract basisVectorobjects). The matrix can then be expressed as a linear combination of the inner products of abstract basisVectorobjects. This is provided as a str.- Parameters:
matrix (np.ndarray) – The matrix which we want to express in terms of the basis
Vectorobjects of thePEPContext.ctx (
PEPContext) – ThePEPContextwhose basisVectorobjects we consider.greedy_square (bool) – If greedy_square is true, the function will try to return \(\|a-b\|^2\) whenever possible. If not, the function will return \(\|a\|^2 - 2 * \langle a, b \rangle + \|b\|^2\) instead. True by default.
- Returns:
str – The representation of matrix in terms of the basis
Vectorobjects of ctx.
Example
>>> x_1 = vt.Vector(is_basis=True, tags=["x_1"]) >>> x_2 = vt.Vector(is_basis=True, tags=["x_2"]) >>> x_3 = vt.Vector(is_basis=True, tags=["x_3"]) >>> matrix = np.array([[0.5, 0.5, 0], [0.5, 2, 0], [0, 0, 3]]) >>> exm.represent_matrix_by_basis(matrix, pep_context, greedy_square=True)
PrimalPEPDualVarManager#
- class pepflow.PrimalPEPDualVarManager(named_constraints: list[tuple[str, Constraint]])#
A class to access the dual variables associated with the constraints of the Primal PEP.
Note
Should not be instantiated directly. Automatically generated as a member variable of the
PEPResultobject returned when callingpepflow.PEPBuilder.solve_primal().- dual_value(name: str) float | None#
Given the name of a
PSDConstraintorScalarConstraintobject, return the value of its corresponding dual variable.- Parameters:
name (str) – The name of the
PSDConstraintorScalarConstraintobject whose associated dual variable we want to retrieve.- Returns:
float – The value of the dual variable corresponding to the
PSDConstraintorScalarConstraintobject associated with the name argument.
DualPEPDualVarManager#
- class pepflow.DualPEPDualVarManager(named_variables: list[tuple[str, Variable]])#
A class to access the dual variables associated with the constraints of Primal PEP after solving Dual PEP.
Note
Should not be instantiated directly. Automatically generated as a member variable of the
PEPResultobject returned when callingpepflow.PEPBuilder.solve_dual().- dual_value(name: str) float | None#
Given the name of a
PSDConstraintorScalarConstraintobject, return the value of its corresponding dual variable.- Parameters:
name (str) – The name of the
PSDConstraintorScalarConstraintobject whose corresponding dual variable we want to retrieve.- Returns:
float – The value of the dual variable corresponding to the
PSDConstraintorScalarConstraintobject associated with the name argument.