picos.modeling

Optimization problem modeling toolbox.

Outline

Classes

Footprint

Statistics on an optimization problem.

Objective

An optimization objective composed of search direction and function.

Options

Collection of optimization solver options.

Problem

PICOS’ representation of an optimization problem.

Solution

Assignment of primal and dual values to variables and constraints.

Specification

Representation of a mathematical class of optimization problems.

Strategy

Optimization problem solution strategy.

Functions

find_assignment

Find a feasible variable assignment.

maximize

Maximize a scalar expression subject to constraints.

minimize

Minimize a scalar expression subject to constraints.

Exceptions

NoStrategyFound

No solution strategy found.

SolutionFailure

Solving the problem failed.

Submodules

picos.modeling.file_in

Functions for reading optimization problems from a file.

picos.modeling.file_out

Functions for writing optimization problems to a file.

picos.modeling.footprint

Optimization problem description classes.

picos.modeling.options

Optimization solver parameter handling.

picos.modeling.problem

Implementation of Problem.

picos.modeling.quicksolve

Functions to quickly solve a problem.

picos.modeling.solution

Optimization problem solution representation.

picos.modeling.strategy

Optimization problem solution strategy search.

Classes

Footprint

class picos.modeling.Footprint(recordsOrDict)[source]

Bases: picos.containers.RecordTree

Statistics on an optimization problem.

Subtree comparison (<<) can be used to check if a specific problem represented by a Footprint instance is contained in a problem class represented by a Specification instance.

__init__(recordsOrDict)[source]

Construct a Footprint from raw data.

See picos.containers.RecordTree.__init__. The addValues argument is fixed; only variable and constraint paths are added.

classmethod from_problem(problem)[source]

Create a footprint from a problem instance.

classmethod from_types(obj_dir, obj_func, vars=[], cons=[], nd_opts={})[source]

Create a footprint from collections of detailed types.

Parameters
  • obj_dir (str) – Objective direction.

  • obj_func – Detailed objective function type.

  • nd_opts (list(str)) – A dictionary mapping option names to nondefault values.

Parm list(tuple) vars

A list of pairs of detailed variable type and occurence count.

Parm list(tuple) cons

A list of pairs of detailed constraint type and occurence count.

updated(recordsOrDict)[source]

Override updated.

This method, just like __init__, does not take the additional addValues argument.

with_extra_options(**extra_options)[source]

Return a copy with additional solution search options applied.

property constraints

A dictionary mapping detailed constraint types to their quantity.

property continuous

Whether no integral variable type is present.

property cost

A very rough measure on how expensive solving such a problem is.

This is logarithmic in the estimated size of the constraint matrix.

property direction

Objective function optimization direction.

property integer

Whether an integral variable type is present.

property nonconvex_quadratic_objective

Whether the problem has a nonconvex quadratic objective.

property nondefault_options

A dictionary mapping option names to their nondefault values.

Warning

This property is cached for performance reasons, do not modify any mutable option value (make a deep copy instead)!

property objective

Detailed type of the objective function.

property options

An Options object.

Warning

This property is cached for performance reasons, do not modify the returned object (make a copy instead)!

property size

Return the estimated size of the (dense) scalar constraint matrix.

property variables

A dictionary mapping detailed variable types to their quantity.

Objective

class picos.modeling.Objective(direction=None, function=None)[source]

Bases: object

An optimization objective composed of search direction and function.

__init__(direction=None, function=None)[source]

Construct an optimization objective.

Parameters
  • direction (str) –

    Case insensitive search direction string. One of

    • "min" or "minimize",

    • "max" or "maximize",

    • "find" or None (for a feasibility problem).

  • function (Expression) – The objective function. Must be None for a feasibility problem.

FIND = 'find'

Short string denoting a feasibility problem.

MAX = 'max'

Short string denoting a maximization problem.

MIN = 'min'

Short string denoting a minimization problem.

property direction

Search direction as a short string.

property feasibility

Whether the objective is “find an assignment”.

property function

Objective function.

property normalized

The objective but with feasiblity posed as “minimize 0”.

>>> from picos import Objective
>>> obj = Objective(); obj
<Objective: find a variable assignment>
>>> obj.normalized
<Objective: minimize 0>
property pair

Search direction and objective function as a pair.

property value

Value of the objective function.

Options

class picos.modeling.Options(*args, **kwargs)[source]

Bases: object

Collection of optimization solver options.

A collection of options that affect how a Problem is solved. Problem.options is an instance of this class.

The options can be accessed as an attribute or as an item. The latter approach supports Unix shell-style wildcard characters:

>>> import picos
>>> P = picos.Problem()
>>> P.options.verbosity = 2
>>> P.options["primals"] = False
>>> # Set all absolute tolerances at once.
>>> P.options["abs_*_tol"] = 1e-6

There are two corresponding ways to reset an option to its default value:

>>> del P.options.verbosity
>>> P.options.reset("primals", "*_tol")

Options can also be passed as a keyword argument sequence when the Problem is created and whenever a solution is searched:

>>> # Use default options except for verbosity.
>>> P = picos.Problem(verbosity = 1)
>>> x = P.add_variable("x", lower = 0); P.set_objective("min", x)
>>> # Only for the next search: Don't be verbose anyway.
>>> solution = P.solve(solver = "cvxopt", verbosity = 0)

Available Options

Jump to option: ➥ abs_bnb_opt_tol ➥ abs_dual_fsb_tol ➥ abs_ipm_opt_tol ➥ abs_prim_fsb_tol ➥ apply_solution ➥ assume_conic ➥ cplex_bnd_monitor ➥ cplex_lwr_bnd_limit ➥ cplex_params ➥ cplex_upr_bnd_limit ➥ dualize ➥ duals ➥ gurobi_params ➥ hotstart ➥ integrality_tol ➥ license_warnings ➥ lp_node_method ➥ lp_root_method ➥ markowitz_tol ➥ max_footprints ➥ max_fsb_nodes ➥ max_iterations ➥ mosek_params ➥ mskfsn_params ➥ penalty_cplex ➥ penalty_cvxopt ➥ penalty_ecos ➥ penalty_glpk ➥ penalty_gurobi ➥ penalty_mosek ➥ penalty_mskfsn ➥ penalty_scip ➥ penalty_smcp ➥ pool_abs_gap ➥ pool_rel_gap ➥ pool_size ➥ primals ➥ rel_bnb_opt_tol ➥ rel_dual_fsb_tol ➥ rel_ipm_opt_tol ➥ rel_prim_fsb_tol ➥ scip_params ➥ solver ➥ strict_options ➥ timelimit ➥ treememory ➥ verbosity ➥ verify_prediction

Option

Default

Description

abs_bnb_opt_tol

1e-06

Absolute optimality tolerance for branch-and-bound solution strategies to mixed integer problems.

A solution is optimal if the absolute difference between the objective function value of the current best integer solution and the current best bound obtained from a continuous relaxation is smaller than this value.

None lets the solver use its own default value.

abs_dual_fsb_tol

1e-08

Absolute dual problem feasibility tolerance.

A dual solution is feasible if some norm over the vector of dual constraint violations is smaller than this value.

Serves as an optimality criterion for the Simplex algorithm.

None lets the solver use its own default value.

abs_ipm_opt_tol

1e-08

Absolute optimality tolerance for interior point methods.

Depending on the solver, a fesible primal/dual solution pair is considered optimal if this value upper bounds either

  • the absolute difference between the primal and dual objective values, or

  • the violation of the complementary slackness condition.

The violation is computed as some norm over the vector that contains the products of each constraint’s slack with its corresponding dual value. If the norm is the 1-norm, then the two conditions are equal. Otherwise they can differ by a factor that depends on the number and type of constraints.

None lets the solver use its own default value.

abs_prim_fsb_tol

1e-08

Absolute primal problem feasibility tolerance.

A primal solution is feasible if some norm over the vector of primal constraint violations is smaller than this value.

None lets the solver use its own default value.

apply_solution

True

Whether to immediately apply the solution returned by a solver to the problem’s variables and constraints.

If multiple solutions are returned by the solver, then the first one will be applied. If this is False, then solutions can be applied manually via their apply method.

assume_conic

True

Determines how ConicQuadraticConstraint instances, which correspond to nonconvex constraints of the form x^TQx + p^Tx + q \leq (a^Tx + b)(c^Tx + d) with x^TQx + p^Tx + q representable as a squared norm, are processed:

  • True strengthens them into convex conic constraints by assuming the additional constraints a^Tx + b \geq 0 and c^Tx + d \geq 0.

  • False takes them verbatim and also considers solutions with (a^Tx + b) < 0 or (c^Tx + d) < 0. This requires a solver that accepts nonconvex quadratic constraints.

Warning

ConicQuadraticConstraint are also used in the case of Q = 0. For instance, x^2 \geq 1 is effectively ransformed to x \geq 1 if this is True.

cplex_bnd_monitor

False

Tells CPLEX to store information about the evolution of the bounds during the MIP solution search process. At the end of the computation, a list of triples (time, lowerbound, upperbound) will be provided in the field bounds_monitor of the dictionary returned by solve.

cplex_lwr_bnd_limit

None

Tells CPLEX to stop MIP optimization if a lower bound below this value is found.

cplex_params

{}

A dictionary of CPLEX parameters to be set after general options are passed and before the search is started.

For example, {"mip.limits.cutpasses": 5} limits the number of cutting plane passes when solving the root node to 5.

cplex_upr_bnd_limit

None

Tells CPLEX to stop MIP optimization if an upper bound above this value is found.

dualize

False

Whether to dualize the problem as part of the solution strategy.

This can sometimes lead to a significant solution search speedup.

duals

None

Whether to request a dual solution.

  • True will raise an exception if no optimal dual solution is found.

  • None will accept and apply also incomplete, infeasible or suboptimal dual solutions.

  • False will not ask for a dual solution and throw away any dual solution returned by the solver.

gurobi_params

{}

A dictionary of Gurobi parameters to be set after general options are passed and before the search is started.

For example, {"NodeLimit": 25} limits the number of nodes visited by the MIP optimizer to 25.

hotstart

False

Tells the solver to start from the (partial) solution that is stored in the variables assigned to the problem.

integrality_tol

1e-05

Integrality tolerance.

A number x \in \mathbb{R} is considered integral if \min_{z \in \mathbb{Z}}{|x - z|} is at most this value.

None lets the solver use its own default value.

license_warnings

True

Whether solvers are allowed to ignore the verbosity option to print licensing related warnings.

Warning

Using this option to suppress licensing related warnings is done at your own legal responsibility.

lp_node_method

None

Algorithm used to solve continuous linear problems at non-root nodes of the branching tree built when solving mixed integer programs.

  • None lets PICOS or the solver select it for you.

  • "psimplex" for Primal Simplex.

  • "dsimplex" for Dual Simplex.

  • "interior" for the interior point method.

lp_root_method

None

Algorithm used to solve continuous linear problems, including the root relaxation of mixed integer problems.

  • None lets PICOS or the solver select it for you.

  • "psimplex" for Primal Simplex.

  • "dsimplex" for Dual Simplex.

  • "interior" for the interior point method.

markowitz_tol

None

Markowitz threshold used in the Simplex algorithm.

None lets the solver use its own default value.

max_footprints

1024

Maximum number of different predicted problem formulations (footprints) to consider before deciding on a formulation and solver to use.

None lets PICOS exhaust all reachable problem formulations.

max_fsb_nodes

None

Maximum number of feasible solution nodes visited for branch-and-bound solution strategies.

None means no limit.

Note

If you want to obtain all feasible solutions that the solver encountered, use the pool_size option.

max_iterations

None

Maximum number of iterations allowed for iterative solution strategies.

None means no limit.

mosek_params

{}

A dictionary of MOSEK (Optimizer) parameters to be set after general options are passed and before the search is started.

See the list of MOSEK (Optimizer) 8.1 parameters.

mskfsn_params

{}

A dictionary of MOSEK (Fusion) parameters to be set after general options are passed and before the search is started.

See the list of MOSEK (Fusion) 8.1 parameters.

penalty_cplex

0.0

Penalty for using the CPLEX solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_cvxopt

1.0

Penalty for using the CVXOPT solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_ecos

1.0

Penalty for using the ECOS solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_glpk

1.0

Penalty for using the GLPK solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_gurobi

0.0

Penalty for using the GUROBI solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_mosek

0.0

Penalty for using the MOSEK solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_mskfsn

0.5

Penalty for using the MSKFSN solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_scip

1.0

Penalty for using the SCIP solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

penalty_smcp

2.0

Penalty for using the SMCP solver.

If solver A has a penalty of p and solver B has a larger penality of p + x, then B is be chosen over A only if the problem as passed to A would be 10^x times larger as when passed to B.

pool_abs_gap

None

Discards solutions from the solution pool as soon as a better solution is found that beats it by the given absolute objective function gap.

None is the solver’s choice, which may be never discard.

pool_rel_gap

None

Discards solutions from the solution pool as soon as a better solution is found that beats it by the given relative objective function gap.

None is the solver’s choice, which may be never discard.

pool_size

None

Maximum number of mixed integer feasible solutions returned.

If this is not None, Problem.solve returns a list of solutions instead of just a single one.

None lets the solver return only the best solution.

primals

True

Whether to request a primal solution.

  • True will raise an exception if no optimal primal solution is found.

  • None will accept and apply also incomplete, infeasible or suboptimal primal solutions.

  • False will not ask for a primal solution and throw away any primal solution returned by the solver.

rel_bnb_opt_tol

0.0001

Relative optimality tolerance for branch-and-bound solution strategies to mixed integer problems.

Like abs_bnb_opt_tol, but the difference is divided by a convex combination of the absolute values of the two objective function values.

None lets the solver use its own default value.

rel_dual_fsb_tol

1e-08

Relative dual problem feasibility tolerance.

Like abs_dual_fsb_tol, but the norm is divided by the norm of the constraints’ right hand side vector. (See rel_prim_fsb_tol for exceptions.)

Serves as an optimality criterion for the Simplex algorithm.

None lets the solver use its own default value.

rel_ipm_opt_tol

1e-08

Relative optimality tolerance for interior point methods.

Like abs_ipm_opt_tol, but the suboptimality measure is divided by a convex combination of the absolute primal and dual objective function values.

None lets the solver use its own default value.

rel_prim_fsb_tol

1e-08

Relative primal problem feasibility tolerance.

Like abs_prim_fsb_tol, but the norm is divided by the norm of the constraints’ right hand side vector.

If the norm used is some nested norm (e.g. the maximum over the norms of the equality and inequality violations), then solvers might divide the inner violation norms by the respective right hand side inner norms (see e.g. CVXOPT).

To prevent that the right hand side vector norm is zero (or small), solvers would either add some small constant or use a fixed lower bound, which may be as large as 1.

None lets the solver use its own default value.

scip_params

{}

A dictionary of SCIP parameters to be set after general options are passed and before the search is started.

For example, {"lp/threads": 4} sets the number of threads to solve LPs with to 4.

solver

None

The solver to use.

Note

picos.available_solvers() returns a list of names of solvers that are available at runtime.

strict_options

False

Whether unsupported general options will raise an UnsupportedOptionError exception, instead of printing a warning.

timelimit

None

Maximum number of seconds spent searching for a solution.

None means no limit.

treememory

None

Bound on the memory used by the branch-and-bound tree, in Megabytes.

None means no limit.

verbosity

0

Verbosity level.

  • -1 attempts to suppress all output, even errros.

  • 0 only generates warnings and errors.

  • 1 generates standard informative output.

  • 2 or larger prints additional information for debugging purposes.

verify_prediction

True

Whether PICOS should validate that problem reformulations produce a problem that matches their predicted outcome.

If a mismatch is detected, a RuntimeError is thrown as there is a chance that it is caused by a bug in the reformulation, which could affect the correctness of the solution. By disabling this option you are able to retrieve a correct solution given that the error is only in the prediction, and given that the solution strategy remains valid for the actual outcome.

__init__(**options)[source]

Create a default option set and set the given options on top.

static __new__(cls, *args, **kwargs)[source]

Create an empty options set.

copy()[source]

Return an independent copy of the current options set.

help(*options)[source]

Print text describing selected options.

Parameters

options – The names of the options to describe, may contain wildcard characters.

reset(*options)[source]

Reset all or a selection of options to their default values.

Parameters

options – The names of the options to reset, may contain wildcard characters. If no name is given, all options are reset.

self_or_updated(**options)[source]

Return either a modified copy or self, depending on given options.

update(**options)[source]

Set multiple options at once.

This method is called with the keyword arguments supplied to the Options constructor, so the following two are the same:

>>> import picos
>>> a = picos.Options(verbosity = 1, primals = False)
>>> b = picos.Options()
>>> b.update(verbosity = 1, primals = False)
>>> a == b
True
Parameters

options – A parameter sequence of options to set.

updated(**options)[source]

Return a modified copy.

property nondefaults

A dictionary mapping option names to nondefault values.

Example

>>> from picos import Options
>>> o = Options()
>>> o.verbosity = 2
>>> o.nondefaults
{'verbosity': 2}
>>> Options(**o.nondefaults) == o
True

Problem

class picos.modeling.Problem(copyOptions=None, useOptions=None, **extra_options)[source]

Bases: object

PICOS’ representation of an optimization problem.

Example

>>> from picos import Problem, RealVariable
>>> X = RealVariable("X", (2,2), lower = 0)
>>> P = Problem()
>>> P.set_objective("max", X.tr)
>>> C1 = P.add_constraint(X.sum <= 10)
>>> C2 = P.add_constraint(X[0,0] == 1)
>>> print(P)
---------------------------------------
Linear Program
  maximize tr(X)
  over
    2×2 real variable X (bounded below)
  subject to
    ∑(X) ≤ 10
    X[0,0] = 1
---------------------------------------
>>> # PICOS will select a suitable solver if you don't specify one.
>>> solution = P.solve(solver = "cvxopt")
>>> solution.claimedStatus
'optimal'
>>> solution.searchTime 
0.002137422561645508
>>> round(P, 1)
10.0
>>> print(X) 
[ 1.00e+00  4.89e-10]
[ 4.89e-10  9.00e+00]
>>> round(C1.dual, 1)
1.0
__init__(copyOptions=None, useOptions=None, **extra_options)[source]

Create an empty problem and optionally set initial solver options.

Parameters
  • copyOptions – An Options object to copy instead of using the default options.

  • useOptions – An Options object to use (without making a copy) instead of using the default options.

  • extra_options – A sequence of additional solver options to apply on top of the default options or those given by copyOptions or useOptions.

add_constraint(constraint, key=None)[source]

Add a constraint to the problem.

Parameters
  • constraint (Constraint) – The constraint to be added.

  • key (str) – Optional name of the constraint.

Returns

The constraint that was added to the problem.

add_list_of_constraints(lst, it=None, indices=None, key=None)[source]

Add a list of constraints to the problem.

Adds a list of constraints to the problem, enabling the use of Python list comprehensions (see the example below).

Parameters
Returns

A list of all constraints that were added.

Example

>>> import picos as pic
>>> import cvxopt as cvx
>>> from pprint import pprint
>>> prob=pic.Problem()
>>> x=[prob.add_variable('x[{0}]'.format(i),2) for i in range(5)]
>>> pprint(x)
[<2×1 Real Variable: x[0]>,
 <2×1 Real Variable: x[1]>,
 <2×1 Real Variable: x[2]>,
 <2×1 Real Variable: x[3]>,
 <2×1 Real Variable: x[4]>]
>>> y=prob.add_variable('y',5)
>>> IJ=[(1,2),(2,0),(4,2)]
>>> w={}
>>> for ij in IJ:
...         w[ij]=prob.add_variable('w[{},{}]'.format(*ij),3)
...
>>> u=pic.new_param('u',cvx.matrix([2,5]))
>>> C1=prob.add_list_of_constraints([u.T*x[i] < y[i] for i in range(5)])
>>> C2=prob.add_list_of_constraints([abs(w[i,j])<y[j] for (i,j) in IJ])
>>> C3=prob.add_list_of_constraints([y[t] > y[t+1] for t in range(4)])
>>> print(prob)
-----------------------------------------------------------
Feasibility Problem
  find an assignment
  for
    2×1 real variable x[i] ∀ i ∈ [0…4]
    3×1 real variable w[i,j] ∀ (i,j) ∈ zip([1,2,4],[2,0,2])
    5×1 real variable y
  subject to
    uᵀ·x[i] ≤ y[i] ∀ i ∈ [0…4]
    ‖w[i,j]‖ ≤ y[j] ∀ (i,j) ∈ zip([1,2,4],[2,0,2])
    y[i] ≥ y[i+1] ∀ i ∈ [0…3]
-----------------------------------------------------------
add_variable(name, size=1, vtype='continuous', lower=None, upper=None)[source]

Legacy method to create a PICOS variable.

Parameters
  • name (str) – The name of the variable.

  • size (anything recognized by load_shape) – The shape of the variable.

  • vtype (str) –

    Domain of the variable. Can be any of

    • 'continuous' – real valued,

    • 'binary' – either zero or one,

    • 'integer' – integer valued,

    • 'symmetric' – symmetric matrix,

    • 'antisym' or 'skewsym' – skew-symmetric matrix,

    • 'complex' – complex matrix,

    • 'hermitian' – complex hermitian matrix.

  • lower (anything recognized by load_data) – A lower bound on the variable.

  • upper (anything recognized by load_data) – An upper bound on the variable.

Returns

A BaseVariable instance.

Example

>>> from picos import Problem
>>> P = Problem()
>>> x = P.add_variable("x", 3)
>>> x
<3×1 Real Variable: x>
>>> # Variable are not stored inside the problem any more:
>>> P.variables
mappingproxy(OrderedDict())
>>> # They are only part of the problem if they actually appear:
>>> P.set_objective("min", abs(x)**2)
>>> P.variables
mappingproxy(OrderedDict([('x', <3×1 Real Variable: x>)]))

Deprecated since version 2.0: Variables can now be created independent of problems, and do not need to be added to any problem explicitly.

as_dual()[source]

Return the Lagrangian dual problem of the standardized problem.

Deprecated since version 2.0: Use dual instead.

check_current_value_feasibility(tol=1e-05, inttol=None)[source]

Check if the problem is feasibly valued.

Checks whether all variables that appear in constraints are valued and satisfy both their bounds and the constraints up to the given tolerance.

Parameters
  • tol (float) – Largest tolerated absolute violation of a constraint or variable bound. If None, then the abs_prim_fsb_tol solver option is used.

  • inttol – DEPRECATED

Returns

A tuple (feasible, violation) where feasible is a bool stating whether the solution is feasible and violation is either None, if feasible == True, or the amount of violation, otherwise.

clone(copyOptions=True)[source]

Create a semi-deep copy of the problem.

The copy is constrained by the same constraint objects and thereby references the existing variables that appear in these constraints.

The clone can be modified to describe a new problem, but whenever a solution is applied to its variables, some of these variables can be the same that still appear in the original problem. If this is not a problem to you, then cloning can be much faster than copying.

Parameters

copyOptions (bool) – Whether to make an independent copy of the problem’s options. Disabling this will apply any option changes to the original problem as well but yields a (very small) reduction in cloning time.

continuous_relaxation(copy_continuous_variables=True)[source]

Return a continuous relaxation of the problem.

This is done by replacing integer variables with continuous ones.

Parameters

copy_continuous_variables (bool) – Whether variables that are already continuous should still be copied. If this is False, then the relxation shares these variables with the original problem.

copy()[source]

Create a deep copy of the problem, using new variables.

get_constraint(idOrIndOrCon)[source]

Return a (list of) constraint(s) of the problem.

Parameters

idOrIndOrCon (picos.constraints.Constraint or int or tuple or list) –

One of the following:

  • A constraint object. It will be returned when the constraint is part of the problem, otherwise a KeyError is raised.

  • The integer ID of the constraint.

  • The integer offset of the constraint in the list of all constraints that are part of the problem, in the order that they were added.

  • A list or tuple of length 1. Its only element is the index of a constraint group (of constraints that were added together), where groups are indexed in the order that they were added to the problem. The whole group is returned as a list of constraints. That list has the constraints in the order that they were added.

  • A list or tuple of length 2. The first element is a constraint group offset as above, the second an offset within that list.

Returns

A constraint or a list thereof.

Example

>>> import picos as pic
>>> import cvxopt as cvx
>>> from pprint import pprint
>>> prob=pic.Problem()
>>> x=[prob.add_variable('x[{0}]'.format(i),2) for i in range(5)]
>>> y=prob.add_variable('y',5)
>>> Cx=prob.add_list_of_constraints([(1|x[i]) < y[i] for i in range(5)])
>>> Cy=prob.add_constraint(y>0)
>>> print(prob)
--------------------------------------
Linear Feasibility Problem
  find an assignment
  for
    2×1 real variable x[i] ∀ i ∈ [0…4]
    5×1 real variable y
  subject to
    ∑(x[i]) ≤ y[i] ∀ i ∈ [0…4]
    y ≥ 0
--------------------------------------
>>> # Retrieve the second constraint, indexed from zero:
>>> prob.get_constraint(1)
<1×1 Affine Constraint: ∑(x[1]) ≤ y[1]>
>>> # Retrieve the fourth consraint from the first group:
>>> prob.get_constraint((0,3))
<1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>
>>> # Retrieve the whole first group of constraints:
>>> pprint(prob.get_constraint((0,)))
[<1×1 Affine Constraint: ∑(x[0]) ≤ y[0]>,
 <1×1 Affine Constraint: ∑(x[1]) ≤ y[1]>,
 <1×1 Affine Constraint: ∑(x[2]) ≤ y[2]>,
 <1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>,
 <1×1 Affine Constraint: ∑(x[4]) ≤ y[4]>]
>>> # Retrieve the second "group", containing just one constraint:
>>> prob.get_constraint((1,))
[<5×1 Affine Constraint: y ≥ 0>]
get_valued_variable(name)[source]

Retrieve values of variables referenced by the problem.

This method works the same get_variable but it returns the variable’s values instead of the variable objects.

Raises

NotValued – If any of the selected variables is not valued.

get_variable(name)[source]

Retrieve variables referenced by the problem.

Retrieves either a single variable with the given name or a group of variables all named name[param] with different values for param. If the values for param are the integers from zero to the size of the group minus one, then the group is returned as a list ordered by param, otherwise it is returned as a dict with the values of param as keys.

Note

Since PICOS 2.0, variables are independent of problems and only appear in a problem for as long as they are referenced by the problem’s objective function or constraints.

Parameters

name (str) – The name of a variable, or the base name of a group of variables.

Returns

A variable or a list or dict thereof.

Example

>>> from picos import Problem, RealVariable
>>> from pprint import pprint
>>> # Create a number of variables with structured names.
>>> vars = [RealVariable("x")]
>>> for i in range(4):
...     vars.append(RealVariable("y[{}]".format(i)))
>>> for key in ["alice", "bob", "carol"]:
...     vars.append(RealVariable("z[{}]".format(key)))
>>> # Make the variables appear in a problem.
>>> P = Problem()
>>> P.set_objective("min", sum([var for var in vars]))
>>> print(P)
-----------------------------------------------------------------------
Linear Program
  minimize x + y[0] + y[1] + y[2] + y[3] + z[alice] + z[bob] + z[carol]
  over
    1×1 real variable x, y[0], y[1], y[2], y[3], z[alice], z[bob],
      z[carol]
-----------------------------------------------------------------------
>>> # Retrieve the variables from the problem.
>>> P.get_variable("x")
<1×1 Real Variable: x>
>>> pprint(P.get_variable("y"))
[<1×1 Real Variable: y[0]>,
 <1×1 Real Variable: y[1]>,
 <1×1 Real Variable: y[2]>,
 <1×1 Real Variable: y[3]>]
>>> pprint(P.get_variable("z"))
{'alice': <1×1 Real Variable: z[alice]>,
 'bob': <1×1 Real Variable: z[bob]>,
 'carol': <1×1 Real Variable: z[carol]>}
>>> P.get_variable("z")["alice"] is P.get_variable("z[alice]")
True
is_continuous()[source]

Whether all variables are of continuous types.

Deprecated since version 2.0: Use continuous instead.

is_pure_integer()[source]

Whether all variables are of integral types.

Deprecated since version 2.0: Use pure_integer instead.

maximize(obj, **extra_options)[source]

Look for a maximization solution.

Sets the objective to maximize the given objective function and calls the solver with the given additional options.

Parameters
  • obj (Expression) – The objective function to maximize.

  • extra_options – A sequence of additional solver options.

Returns

A dictionary, see solve.

Warning

This is equivalent to set_objective followed by solve and will thus override any existing objective function and direction.

Deprecated since version 2.0: Misleading semantics. Maybe picos.maximize is what you want.

minimize(obj, **extra_options)[source]

Look for a minimizing solution.

Sets the objective to minimize the given objective function and calls the solver with the given additional options.

Parameters
  • obj (Expression) – The objective function to minimize.

  • extra_options – A sequence of additional solver options.

Returns

A dictionary, see solve.

Warning

This is equivalent to set_objective followed by solve and will thus override any existing objective function and direction.

Deprecated since version 2.0: Misleading semantics. Maybe picos.minimize is what you want.

obj_value()[source]

Objective function value.

Raises

AttributeError – If the problem is a feasibility problem or if the objective function is not valued. This is legacy behavior. Note that value just returns None while functions that do raise an exception to denote an unvalued expression would raise NotValued instead.

Deprecated since version 2.0: Use value instead.

prepared(steps=None, **extra_options)[source]

Perform a dry-run returning the reformulated (prepared) problem.

This behaves like solve in that it takes a number of additional temporary options, finds a solution strategy matching the problem and options, and performs the strategy’s reformulations in turn to obtain modified problems. However, it stops after the given number of steps and never hands the reformulated problem to a solver. Instead of a solution, prepared then returns the last reformulated problem.

Unless this method returns the problem itself, the special attributes prepared_strategy and prepared_steps are added to the returned problem. They then contain the (partially) executed solution strategy and the number of performed reformulations, respectively.

Parameters
  • steps (int) – Number of reformulations to perform. None means as many as there are. If this parameter is 0, then the problem itself is returned. If it is 1, then only the implicit first reformulation ExtraOptions is executed, which may also output the problem itself, depending on extra_options.

  • extra_options – Additional solver options to use with this dry-run only.

Returns

The reformulated problem.

Raises
  • NoStrategyFound – If no solution strategy was found.

  • ValueError – If there are not as many reformulation steps as requested.

Example

>>> from picos import Problem, RealVariable
>>> x = RealVariable("x")
>>> P = Problem()
>>> P.set_objective("min", x**2)
>>> Q = P.prepared(solver = "cvxopt")
>>> print(Q.prepared_strategy)  # Show prepared reformulation steps.
1. ExtraOptions
2. EpigraphReformulation
3. ConvexQuadraticToConicReformulation
4. CVXOPTSolver
>>> Q.prepared_steps  # Check how many steps have been performed.
3
>>> print(P)
-----------------------
Quadratic Program
  minimize x²
  over
    1×1 real variable x
-----------------------
>>> print(Q)
-------------------------------------------------------------
Second Order Cone Program
  minimize __..._t
  over
    1×1 real variable __..._t, x
  subject to
    ‖quadroot(x²)‖² ≤ -(aff(x²) - __..._t) ∧ -(aff(x²) -
      __..._t) ≥ 0
-------------------------------------------------------------
remove_all_constraints()[source]

Remove all constraints from the problem.

Note

This method does not remove bounds set directly on variables.

remove_constraint(idOrIndOrCon)[source]

Delete a constraint from the problem.

Parameters

idOrIndOrCon – See get_constraint.

Example

>>> import picos
>>> from pprint import pprint
>>> P = picos.Problem()
>>> x = [P.add_variable('x[{0}]'.format(i), 2) for i in range(4)]
>>> y = P.add_variable('y', 4)
>>> Cxy = P.add_list_of_constraints(
...     [(1 | x[i]) <= y[i] for i in range(4)])
>>> Cy = P.add_constraint(y >= 0)
>>> Cx0to2 = P.add_list_of_constraints([x[i] <= 2 for i in range(3)])
>>> Cx3 = P.add_constraint(x[3] <= 1)
>>> pprint(list(P.constraints.values()))
[<1×1 Affine Constraint: ∑(x[0]) ≤ y[0]>,
 <1×1 Affine Constraint: ∑(x[1]) ≤ y[1]>,
 <1×1 Affine Constraint: ∑(x[2]) ≤ y[2]>,
 <1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>,
 <4×1 Affine Constraint: y ≥ 0>,
 <2×1 Affine Constraint: x[0] ≤ [2]>,
 <2×1 Affine Constraint: x[1] ≤ [2]>,
 <2×1 Affine Constraint: x[2] ≤ [2]>,
 <2×1 Affine Constraint: x[3] ≤ [1]>]
>>> # Delete the 2nd constraint (counted from 0):
>>> P.remove_constraint(1)
>>> pprint(list(P.constraints.values()))
[<1×1 Affine Constraint: ∑(x[0]) ≤ y[0]>,
 <1×1 Affine Constraint: ∑(x[2]) ≤ y[2]>,
 <1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>,
 <4×1 Affine Constraint: y ≥ 0>,
 <2×1 Affine Constraint: x[0] ≤ [2]>,
 <2×1 Affine Constraint: x[1] ≤ [2]>,
 <2×1 Affine Constraint: x[2] ≤ [2]>,
 <2×1 Affine Constraint: x[3] ≤ [1]>]
>>> # Delete the 2nd group of constraints, i.e. the constraint y > 0:
>>> P.remove_constraint((1,))
>>> pprint(list(P.constraints.values()))
[<1×1 Affine Constraint: ∑(x[0]) ≤ y[0]>,
 <1×1 Affine Constraint: ∑(x[2]) ≤ y[2]>,
 <1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>,
 <2×1 Affine Constraint: x[0] ≤ [2]>,
 <2×1 Affine Constraint: x[1] ≤ [2]>,
 <2×1 Affine Constraint: x[2] ≤ [2]>,
 <2×1 Affine Constraint: x[3] ≤ [1]>]
>>> # Delete the 3rd remaining group of constraints, i.e. x[3] < [1]:
>>> P.remove_constraint((2,))
>>> pprint(list(P.constraints.values()))
[<1×1 Affine Constraint: ∑(x[0]) ≤ y[0]>,
 <1×1 Affine Constraint: ∑(x[2]) ≤ y[2]>,
 <1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>,
 <2×1 Affine Constraint: x[0] ≤ [2]>,
 <2×1 Affine Constraint: x[1] ≤ [2]>,
 <2×1 Affine Constraint: x[2] ≤ [2]>]
>>> # Delete 2nd constraint of the 2nd remaining group, i.e. x[1] < |2|:
>>> P.remove_constraint((1,1))
>>> pprint(list(P.constraints.values()))
[<1×1 Affine Constraint: ∑(x[0]) ≤ y[0]>,
 <1×1 Affine Constraint: ∑(x[2]) ≤ y[2]>,
 <1×1 Affine Constraint: ∑(x[3]) ≤ y[3]>,
 <2×1 Affine Constraint: x[0] ≤ [2]>,
 <2×1 Affine Constraint: x[2] ≤ [2]>]
remove_variable(name)[source]

Does nothing.

Deprecated since version 2.0: Whether a problem references a variable is now determined dynamically, so this method has no effect.

reset(resetOptions=False)[source]

Reset the problem instance to its initial empty state.

Parameters

resetOptions (bool) – Whether also solver options should be reset to their default values.

set_all_options_to_default()[source]

Set all solver options to their default value.

Deprecated since version 2.0: Use Problem.options instead.

set_objective(direction=None, expression=None)[source]

Set the optimization direction and objective function of the problem.

Parameters
  • direction (str) –

    Case insensitive search direction string. One of

    • "min" or "minimize",

    • "max" or "maximize",

    • "find" or None (for a feasibility problem).

  • expression (Expression) – The objective function. Must be None for a feasibility problem.

set_option(key, val)[source]

Set a single solver option to the given value.

Parameters
  • key (str) – String name of the option, see below for a list.

  • val – New value for the option.

Deprecated since version 2.0: Use Problem.options instead.

set_var_value(name, value)[source]

Set the value of a variable.

For a Problem P, this is the same as P.variables[name] = value.

Parameters
  • name (str) – Name of the variable to be valued.

  • value (anything recognized by load_data) – The value to be set.

Deprecated since version 2.0: Use variables instead.

solve(**extra_options)[source]

Hand the problem to a solver.

You can select the solver manually with the solver option. Otherwise a suitable solver will be selected among those that are available on the platform.

The default behavior (options primals=True, duals=None) is to raise a SolutionFailure when the primal solution is not found optimal by the solver, while the dual solution is allowed to be missing or incomplete.

When this method succeeds and unless apply_solution=False, you can access the solution as follows:

  • The problem’s value denotes the objective function value.

  • The variables’ value is set according to the primal solution. You can in fact query the value of any expression involving valued variables like this.

  • The constraints’ dual is set according to the dual solution.

Parameters

extra_options

A sequence of additional solver options to use with this solution search only. In particular, this lets you

  • select a solver via the solver option,

  • obtain non-optimal primal solutions by setting primals=None,

  • require a complete and optimal dual solution with duals=True, and

  • skip valuing variables or constraints with apply_solution=False.

Returns ~picos.Solution or list(~picos.Solution)

A solution object or list thereof.

Raises

SolutionFailure

In the following cases:

  1. No solution strategy was found.

  2. Multiple solutions were requested but none were returned.

  3. A primal solution was explicitly requested (primals=True) but the primal solution is missing/incomplete or not claimed optimal.

  4. A dual solution was explicitly requested (duals=True) but the dual solution is missing/incomplete or not claimed optimal.

The case number is stored in the code attribute of the exception.

update_options(**options)[source]

Set multiple solver options at once.

Parameters

options – A parameter sequence of options to set.

Deprecated since version 2.0: Use Problem.options instead.

verbosity()[source]

Return the problem’s current verbosity level.

Deprecated since version 2.0: Use Problem.options instead.

write_to_file(filename, writer='picos')[source]

See picos.modeling.file_out.write.

property constraints

Maps constraint IDs to constraints that are part of the problem.

Returns

A read-only view to an OrderedDict. The order is that in which constraints were added.

property continuous

Whether all variables are of continuous types.

property countCons

The same as len applied to constraints.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property countVar

The same as len applied to variables.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property dual

The Lagrangian dual problem of the standardized problem.

More precisely, this property invokes the following:

  1. The primal problem is posed as an equivalent conic standard form minimization problem, with variable bounds expressed as additional constraints.

  2. The Lagrangian dual problem of the reposed primal is computed.

  3. The optimization direction and objective function sign of the dual are adjusted such that, given strong duality and primal feasibility, the optimal values of both problems are equal. In particular, if the primal problem is a minimization or a maximization problem, the dual problem returned will be the respective other.

This property is intended for educational purposes. If you want to solve the primal problem via its dual, use the dualize option instead.

property footprint

Problem footprint as a Footprint object.

property last_solution

The last Solution applied to the problem.

property no

Normalized objective as an Objective instance.

Either a minimization or a maximization objective, with feasibility posed as “minimize 0”.

The same as the normalized attribute of the objective.

property numberConeConstraints

Number of quadratic conic constraints stored.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property numberLSEConstraints

Number of LogSumExpConstraint stored.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property numberOfVars

The sum of the dimensions of all referenced variables.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property numberQuadConstraints

Number of quadratic constraints stored.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property numberSDPConstraints

Number of LMIConstraint stored.

Deprecated since version 2.0: Still used internally by legacy code; will be removed together with that code.

property objective

Optimization objective as an Objective instance.

property options

Solution search parameters as an Options object.

property pure_integer

Whether all variables are of integral types.

property status

The solution status string as claimed by last_solution.

property strategy

Solution strategy as a Strategy object.

A strategy is available once you order the problem to be solved and it will be reused for successive solution attempts (of a modified problem) while it remains valid with respect to the problem’s footprint.

When a strategy is reused, modifications to the variables, constraints, and objective of a problem are passed step by step through the strategy’s reformulation pipeline while existing reformulation work is not repeated. If the solver also supports these kinds of updates, then modifying and re-solving a problem can be much faster than solving the problem from scratch.

Example

>>> from picos import Problem, RealVariable
>>> x = RealVariable("x")
>>> P = Problem()
>>> P.set_objective("min", x**2)
>>> print(P.strategy)
None
>>> sol = P.solve(solver = "cvxopt")  # Creates a solution strategy.
>>> print(P.strategy)
1. ExtraOptions
2. EpigraphReformulation
3. ConvexQuadraticToConicReformulation
4. CVXOPTSolver
>>> P.add_constraint((x-2)**2 <= 1)  # Also convex quadratic.
<Convex Quadratic Constraint: (x - 2)² ≤ 1>
>>> P.strategy.valid(solver = "cvxopt")
True
>>> P.strategy.valid(solver = "glpk")
False
>>> sol = P.solve(solver = "cvxopt")  # Reuses the strategy.

It’s also possible to create a startegy from scratch:

>>> from picos.modeling import Strategy
>>> from picos.reforms import (EpigraphReformulation,
...     ConvexQuadraticToConicReformulation)
>>> from picos.solvers import CVXOPTSolver
>>> # Mimic what solve() does when no strategy exists:
>>> P.strategy = Strategy(P, CVXOPTSolver, EpigraphReformulation,
...     ConvexQuadraticToConicReformulation)
property type

The problem type as a string, such as “Linear Program”.

property value

Objective function value.

If all variables that appear in the objective function are valued, in particular after a successful solution search, this is the numeric value of the objective function. If the objective function is not fully valued or if the problem is a feasiblity problem without an objective function, this is None.

Note

The Python special functions int, float, complex and round as well as the special method __index__ make use of this value when applied to a Problem.

property variables

Maps names to variables in use by the problem.

Returns

A read-only view to an OrderedDict. The order is deterministic and depends on the order of operations performed on the Problem instance as well as on the variables’ names.

Solution

class picos.modeling.Solution(primals, duals=None, problem=None, solver='user', primalStatus='unknown', dualStatus='unknown', problemStatus='unknown', searchTime=0.0, info=None, vectorizedPrimals=False)[source]

Bases: object

Assignment of primal and dual values to variables and constraints.

Instances are usually returned by a solver (and thus bound to a problem instance), but may be manually created by the user:

>>> import picos
>>> P = picos.Problem()
>>> x = P.add_variable("x")
>>> s = picos.Solution({x: 1}); s
<detached primal solution from user>
>>> s.apply()
>>> x.value
1.0

If the solution was created by a solver (or attached to a problem via attach_to), more information is available:

>>> C1 = P.add_constraint(x >= 2)
>>> s = P.minimize(x, solver = "cvxopt", duals = False); s
<feasible primal solution (claimed optimal) from cvxopt>
>>> "{:.2f} ms".format(1000.0 * s.searchTime) 
'0.83 ms'
>>> C2 = P.add_constraint(x >= 3); s
<infeasible primal solution (was feasible and claimed optimal) from cvxopt>
__init__(primals, duals=None, problem=None, solver='user', primalStatus='unknown', dualStatus='unknown', problemStatus='unknown', searchTime=0.0, info=None, vectorizedPrimals=False)[source]

Create a solution to an optimization problem.

Parameters
  • object) primals (dict(picos.expressions.BaseVariable,) – A mapping of variables to their primal solution value.

  • object) duals (dict(picos.constraints.Constraint,) – A mapping of constraints to their dual solution value.

  • problem (picos.Problem) – The problem that was solved to create the solution. If None, then the solution is “detached”.

  • solver (str) – The name of the solver that was used to create the solution.

  • primalStatus (str) – The primal solution status as reported by the solver.

  • dualStatus (str) – The dual solution status as reported by the solver.

  • problemStatus (str) – The state of the problem as reported by the solver.

  • searchTime (float) – Seconds that the solution process took.

  • info (dict) – Additional solution (meta)data.

  • vectorizedPrimals (bool) – Whether primal solution values are given with respect to the variable’s special vectorization format as used by PICOS internally.

apply(primals=True, duals=True, clearOnNone=True, toProblem=None, snapshotStatus=False)[source]

Apply the solution to the involved variables and constraints.

Parameters
  • primals (bool) – Whether to apply the primal solution.

  • duals (bool) – Whether to apply the dual solution.

  • clearOnNone (bool) – Whether to clear the value of a variable or constraint if the solution has it set to None. This could happen in case of an error or shortcoming of the solver or PICOS.

  • toProblem (picos.Problem) – If set to a copy of the problem that was used to produce the solution, will apply the solution to that copy’s variables and constraints instead.

  • snapshotStatus (bool) – Whether to update the lastStatus attribute with the new (verified) solution status. PICOS enables this whenever it applies a solution returned by a solver.

attach_to(problem, snapshotStatus=False)[source]

Attach (or move) the solution to a problem.

Only variables and constraints that exist on the problem (same name or ID, respectively) are kept.

Parameters

snapshotStatus (bool) – Whether to set the lastStatus attribute of the copy to match the new problem.

claimedStatus

The primal and dual solution status as claimed by the solver.

dualStatus

The dual solution status as claimed by the solver.

duals

The dual solution values returned by the solver.

info

Additional information provided by the solver.

lastStatus

The solution status as verified by PICOS when the solution was applied to the problem.

primalStatus

The primal solution status as claimed by the solver.

primals

The primal solution values returned by the solver.

problem

The problem that was solved to produce the solution.

problemStatus

The problem status as claimed by the solver.

searchTime

Time in seconds that the solution search took.

solver

The solver that produced the solution.

property status

The current solution status as verified by PICOS.

Warning

Accessing this attribute is expensive for large problems as a copy of the problem needs to be created and valued. If you have just applied the solution to a problem, query the solution’s lastStatus attribute instead.

property value

The objective value of the solution.

Warning

Accessing this attribute is expensive for large problems as a copy of the problem needs to be created and valued. If you have just applied the solution to a problem, query that problem instead.

vectorizedPrimals

Whether primal values refer to variables’ special vectorizations.

Specification

class picos.modeling.Specification(recordsOrDict)[source]

Bases: picos.containers.RecordTree

Representation of a mathematical class of optimization problems.

Subtree comparison (<<) can be used to check if a specific problem represented by a Footprint instance is contained in a problem class represented by a Specification instance.

__init__(recordsOrDict)[source]

Construct a Specification from raw data.

See picos.containers.RecordTree.__init__.

classmethod compile(directions=(), objectives=(), variables=(), constraints=(), nondefault_options=<class 'picos.containers.RecordTree.ALL'>)[source]

Create a specification from the given features.

Strategy

class picos.modeling.Strategy(problem, solver, *reforms)[source]

Bases: object

Optimization problem solution strategy.

__init__(problem, solver, *reforms)[source]

Construct a Strategy.

Parameters
  • problem (Problem) – The first step in the solution pipeline; the problem to be solved.

  • solver (type) – The last step in the solution pipeline; the solver class to be used.

  • reforms (list(Reformulation)) – Intermediate steps in the pipeline; reformulations to be applied. May not include ExtraOptions which is automatically made the first reformulation.

execute(**extra_options)[source]

Execute the solution strategy.

Parameters

extra_options – A keyword parameter sequence of additional options (in addition to those of the problem) to use for this search.

Returns

Solution to the problem.

classmethod from_problem(problem, **extra_options)[source]

Create a solution strategy for the given problem.

Parameters
  • problem (Problem) – The optimization problem to search a strategy for.

  • extra_options – A keyword parameter sequence of additional options (in addition to those of the problem) to assume used.

valid(**extra_options)[source]

Whether the solution strategy can be executed.

Parameters

extra_options – A keyword parameter sequence of additional options (in addition to those of the problem) to assume used.

property problem

The problem to be solved.

property reforms

All reformulations in use.

This includes the implicit ExtraOptions.

property solver

The solver instance in use.

Functions

find_assignment

picos.modeling.find_assignment(subject_to=[], **options)[source]

Find a feasible variable assignment.

Internally, this creates a Problem, adds constraints and performs a solution search.

Parameters
  • subject_to (list(Constraint)) – A collection of constraints to obey.

  • options – A keyword argument sequence of solver options to use. See Options.

Returns

Nothing. Check the concerned variables’ values.

Raises

SolutionFailure – See solve.

Example

>>> from picos import find_assignment, RealVariable
>>> x = RealVariable("x")
>>> values = find_assignment([x**2 + 1 <= x], solver="cvxopt")
... 
Traceback (most recent call last):
    ...
picos.modeling.problem.SolutionFailure: Code 3: ...
>>> x.value
>>> find_assignment([x**2 + 0.25 <= x], solver="cvxopt")
>>> round(x.value, 5)
0.5

maximize

picos.modeling.maximize(function, subject_to=[], **options)[source]

Maximize a scalar expression subject to constraints.

Internally, this creates a Problem, sets an objective, adds constraints, performs a solution search and returns an optimum value found.

Parameters
  • function (Expression) – The objective function to maximize.

  • subject_to (list(Constraint)) – A collection of constraints to obey.

  • options – A keyword argument sequence of solver options to use. See Options.

Returns

The optimum value, as computed from an applied solution.

Raises

SolutionFailure – See solve.

Example

>>> from picos import maximize, RealVariable
>>> x = RealVariable("x")
>>> p = maximize(-x**2, [(x - 2)**2 <= x - 2], solver="cvxopt")
>>> round(p, 5)
-4.0
>>> round(x, 5)
2.0

minimize

picos.modeling.minimize(function, subject_to=[], **options)[source]

Minimize a scalar expression subject to constraints.

Internally, this creates a Problem, sets an objective, adds constraints, performs a solution search and returns an optimum value found.

Parameters
  • function (Expression) – The objective function to minimize.

  • subject_to (list(Constraint)) – A collection of constraints to obey.

  • options – A keyword argument sequence of solver options to use. See Options.

Returns

The optimum value, as computed from an applied solution.

Raises

SolutionFailure – See solve.

Example

>>> from picos import minimize, RealVariable
>>> x = RealVariable("x")
>>> p = minimize(x**2, [(x - 2)**2 <= x - 2], solver="cvxopt")
>>> round(p, 5)
4.0
>>> round(x, 5)
2.0

Exceptions

NoStrategyFound

exception picos.modeling.NoStrategyFound[source]

Bases: RuntimeError

No solution strategy found.

Raised when no viable combination of reformulations and solver to tackle the problem could be found.

__init__(*args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

__new__(**kwargs)

Create and return a new object. See help(type) for accurate signature.

SolutionFailure

exception picos.modeling.SolutionFailure(code, message)[source]

Bases: RuntimeError

Solving the problem failed.

__init__(code, message)[source]

Construct a SolutionFailure.

Parameters
  • code (int) – Status code, as defined in Problem.solve.

  • message (str) – Text description of the failure.

__new__(**kwargs)

Create and return a new object. See help(type) for accurate signature.