Commit d3760750 authored by bzfsagno's avatar bzfsagno

picos 100

parent aadc85d1
......@@ -30,4 +30,29 @@ v0.1.3, 17.04.13
* The weak inequalities operator can now be used.
* Minor bugs corrected (access to the duals of fixed variables with CPLEX,
evaluation of constant affine expressions with a zero coefficient appearing
in the dict of linear terms, number of constraints is now updated in remove_constraint() )
\ No newline at end of file
in the dict of linear terms, number of constraints is now updated in remove_constraint() )
v1.0.0, 19.07.13
* Semidefinite Programming Interface for MOSEK 7.0 !!!
* New options ``handleBarVars`` and ``handleConeVars`` to customize how SOCP and SDPs are passed to MOSEK
(When these options are set to ``True`` , PICOS tries to minimize the number of variables of the
MOSEK instance).
* The function dualize() returns the Lagrangian dual of a Problem.
* The option ``solve_via_dual`` allows the user to pass the dual
of a problem to a solver, instead of the primal problem itself. This can yield important speed-up for
certain problems.
* In addition to the geometric mean function picos.geomean(), it is now possible
to pass rational powers of affine expressions (through an overload of the ``**`` operator), trace of
matrix powers with picos.tracepow(), (generalized) p-norms
with picos.norm(), and nth root of a determinant with
picos.detrootn(). These functions automatically reformulate the entered inequalities
as a set of equivalent SOCP or SDP constraints.
* It is now possible to specify variable bounds directly (rather than adding constraints of the type ``x >= 0`` ).
This can be done with the Keywords ``lower`` and ``upper`` of the function add_variable() ,
or by the methods set_lower(), set_upper(), set_sparse_lower(), and set_sparse_upper() of the class Variable.
* It is now more efficient to update a Problem and resolve it. This is done thanks to the attribute ``passed``
of the classes Constraint and Variable ,
that stores which solvers are already aware of a constraint / variable. There is also an
attribute ``obj_passed`` of the class Problem that lists the solver instances
where the objective function has already been passed. The option ``onlyChangeObjective`` has been
deprecated.
\ No newline at end of file
# file GENERATED by distutils, do NOT edit
CHANGES.txt
LICENSE.txt
README.txt
setup.py
doc/api.rst
doc/constraint.rst
doc/download.rst
doc/examples.rst
doc/expression.rst
doc/graphs.rst
doc/index.rst
doc/intro.rst
doc/optdes.rst
doc/problem.rst
doc/tools.rst
doc/tuto.rst
doc/_templates/download.html
doc/_templates/localtoc2.html
picos/__init__.py
picos/constraint.py
picos/cplex_callbacks.py
......
Mention in the doc that socp - write_to_file --> scaled vars [mettre ds nom variable ?]
documenter solve_via_dual, bounds et passed
automatic selection of solve_via_dual for sdp problems.
detrootn for sdp matrices.
tracepow
solve_via_dual avec cvxopt -- something special to do (finir primalize())
probleme qd solve problems 2 times in a row (test_cutting_plane.py avec mosek6)
probleme qd solve problems 2 times in a row (test_cutting_plane.py avec mosek6, but only at zib (?))
problem avec duals de gurobi pour probleme dsocp de test_picos.py (faire testSOCP5 ?). Bug gurobi -> min example ?
write_to_file --> scaled vars [mettre ds nom variable ?]
file reader
mps writer
dat-s writer with option to desymmetrize the matrices
......
This diff is collapsed.
files = ['index.html','api.html','variable.html',
files = ['index.html','api.html',
'examples.html','constraint.html','expression.html',
'intro.html','tools.html','problem.html',
'download.html','graphs.html','tuto.html','optdes.html']
......
......@@ -69,9 +69,9 @@ copyright = u'2012, Guillaume Sagnol'
# built documents.
#
# The short X.Y version.
version = '0.1'
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '0.1.4'
release = '1.0.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
......
......@@ -12,5 +12,13 @@ Constraint
:inherited-members: slack
.. autoclass:: picos.NormP_Constraint
:members:
:inherited-members: slack
.. autoclass:: picos.TracePow_Constraint
:members:
:inherited-members: slack
.. autoclass:: picos.DetRootN_Constraint
:members:
:inherited-members: slack
\ No newline at end of file
......@@ -6,7 +6,7 @@ Download
The latest version of PICOS can be downloaded here:
`picos-0.1.3 <dist/PICOS-0.1.3.tar.gz>`_
`picos-1.0.0 <dist/PICOS-1.0.0.tar.gz>`_
Installation instructions are explained
:ref:`here <requirements>`.
......@@ -14,6 +14,8 @@ Installation instructions are explained
**Older versions**
`picos-0.1.3 <dist/PICOS-0.1.3.tar.gz>`_
`picos-0.1.2 <dist/PICOS-0.1.2.tar.gz>`_
`picos-0.1.1 <dist/PICOS-0.1.1.tar.gz>`_
......
......@@ -50,4 +50,16 @@ NormP_Exp
=========
.. autoclass:: picos.NormP_Exp
:members:
TracePow_Exp
============
.. autoclass:: picos.TracePow_Exp
:members:
DetRootN_Exp
============
.. autoclass:: picos.DetRootN_Exp
:members:
\ No newline at end of file
......@@ -14,46 +14,39 @@ PICOS: A Python Interface for Conic Optimization Solvers
**News**
* 17 Apr. 13: **Picos** :ref:`0.1.3 <download>` **Released** |br|
Major changes:
* Function :func:`picos.geomean() <picos.tools.geomean>` implemented, to handle inequalities involving
a geometric mean and reformulate them automatically as a set of SOCP constraints.
* Some options were added for the function :func:`solve() <picos.Problem.solve>` ,
to tell CPLEX to stop the computation as soon as a given value for the
upper bound (or lower bound) is reached (see the options ``uboundlimit`` and ``lboundlimit``
documented in :func:`set_all_options_to_default() <picos.Problem.set_all_options_to_default>`).
* The time used by the solver is now stored in the dictionary
returned by :func:`solve() <picos.Problem.solve>`.
* The option ``boundMonitor`` of the function :func:`solve() <picos.Problem.solve>`
gives access to the values of the lower and upper bounds over time with cplex.
(this option is documented in :func:`set_all_options_to_default() <picos.Problem.set_all_options_to_default>`).
* The weak inequalities operators ``<=`` and ``>=`` can now be used (but strict inequalities are
still interpreted as weak inequalities !).
* Minor bugs corrected (access to the duals of fixed variables with CPLEX,
evaluation of constant affine expressions with a zero coefficient appearing
in the dict of linear terms, number of constraints is now updated in
:func:`remove_constraint() <picos.Problem.remove_constraint>`).
* 19 Jul. 13: **Picos** :ref:`1.0.0 <download>` **Released** |br|
Major Release with following changes:
* Semidefinite Programming Interface for MOSEK 7.0 !!!
* New options ``handleBarVars`` and ``handleConeVars`` to customize how SOCP and SDPs are passed to MOSEK
(When these options are set to ``True`` , PICOS tries to minimize the number of variables of the
MOSEK instance, see the doc in :func:`set_all_options_to_default() <picos.Problem.set_all_options_to_default>`).
* The function :func:`dualize() <picos.Problem.dualize>` returns the Lagrangian dual of a Problem.
* The option ``solve_via_dual`` (documented in
:func:`set_all_options_to_default() <picos.Problem.set_all_options_to_default>` ) allows the user to
pass the dual of a problem to a solver, instead of the primal problem itself.
This can yield important speed-up for certain problems.
* In addition to the geometric mean function :func:`picos.geomean() <picos.tools.geomean>` , it is now possible
to pass rational powers of affine expressions (through an overload of the ``**`` operator), trace of
matrix powers with :func:`picos.tracepow() <picos.tools.tracepow>` , (generalized) p-norms
with :func:`picos.norm() <picos.tools.norm>`, and nth root of a determinant with
:func:`picos.detrootn() <picos.tools.detrootn>`. These functions automatically reformulate the entered inequalities as a set of equivalent SOCP or SDP constraints.
* It is now possible to specify variable bounds directly (rather than adding constraints of the type ``x >= 0`` ).
This can be done with the Keywords ``lower`` and ``upper`` of the function
:func:`add_variable() <picos.Problem.add_variable>` ,
or by the methods :func:`set_lower() <picos.Variable.set_lower>` ,
:func:`set_upper() <picos.Variable.set_upper>` ,
:func:`set_sparse_lower() <picos.Variable.set_sparse_lower>` , and
:func:`set_sparse_upper() <picos.Variable.set_sparse_upper>` of the class :class:`Variable <picos.Variable>`.
* It is now more efficient to update a Problem and resolve it. This is done thanks to the attribute ``passed``
of the classes :class:`Constraint <picos.Constraint>` and :class:`Variable <picos.Variable>` ,
that stores which solvers are already aware of a constraint / variable. There is also an
attribute ``obj_passed`` of the class :class:`Problem <picos.Problem>` , that lists the solver instances
where the objective function has already been passed. The option ``onlyChangeObjective`` has been
deprecated.
* 10 Jan. 13: **Picos** :ref:`0.1.2 <download>` **Released** |br|
bug-fix release, correcting:
* The :func:`write_to_file() <picos.Problem.write_to_file>`
function for sparse SDPA files. The function was writing the
coefficients of the lower triangular part of the constraint matrices
instead of the upper triangle.
* An ``IndexError`` occuring with the function
:func:`remove_constraint() <picos.Problem.remove_constraint>`.
Thanks to Warren Schudy for pointing out these bugs of the previous release !
* 08 Dec. 12: **Picos** :ref:`0.1.1 <download>` **Released** |br|
Major changes:
* Picos now interfaces GUROBI !
* You can specify an initial solution to *warm-start* mixed integer optimizers.
(see the option ``hotstart`` documented in
:func:`set_all_options_to_default() <picos.Problem.set_all_options_to_default>`)
* Minor bugs with quadratic expressions corrected
* It's possible to return a reference to a constraint added
with add_constraint()
* Former changes are listed :ref:`here <changes>`.
**PICOS Documentation contents**
......@@ -74,6 +67,7 @@ on every function of PICOS.
examples
api
download
changes
Indices and tables
==================
......
This diff is collapsed.
......@@ -5,4 +5,4 @@ picos.tools
===========
.. automodule:: picos.tools
:members: available_solvers, diag, diag_vect, lowtri, eval_dict, lse, new_param, sum, norm, geomean, _retrieve_matrix
\ No newline at end of file
:members: available_solvers, diag, diag_vect, lowtri, eval_dict, lse, new_param, sum, norm, geomean, tracepow, detrootn, _retrieve_matrix
\ No newline at end of file
......@@ -11,7 +11,7 @@ First of all, let us import the PICOS module and cvxopt
We now generate some arbitrary data, that we will use in this tutorial.
>>> pairs = [(0,2), (1,4), (1,3), (3,2), (0,4),(2,4)] #a list of pairs
>>> pairs = [(0,2), (1,4), (1,3), (3,2), (0,4),(2,4)] #a list of pairs
>>> A = []
>>> b = ( [0 ,2 ,0 ,3 ], #a tuple of 5 lists, each of length 4
... [1 ,1 ,0 ,5 ],
......@@ -513,6 +513,63 @@ A few examples:
>>> 1 < (t-1)*(x[2]+x[3]) #1 is understood as the squared norm of [1]
# (1x1)-Rotated SOC constraint: 1.0 < ( t -1.0)( x[2] + x[3]) #
Semidefinite Constraints
-------------------------
Linear matrix inequalities (LMI) can be entered thanks to an overload of the operators
``<<`` and ``>>``. For example, the LMI
.. math::
:nowrap:
\begin{equation*}
\sum_{i=0}^3 x_i b_i b_i^T \succeq b_4 b_4^T,
\end{equation*}
where :math:`\succeq` is used to denote the Löwner ordering,
is passed to PICOS by writing:
>>> pic.sum([x[i]*b[i]*b[i].T for i in range(4)],'i','0...3') >> b[4]*b[4].T
# (4x4)-LMI constraint Σ_{i in 0...3} x[i]*b[i]*b[i].T ≽ b[4]*b[4].T #
Note the difference with
>>> pic.sum([x[i]*b[i]*b[i].T for i in range(4)],'i','0...3') > b[4]*b[4].T
# (4x4)-affine constraint: Σ_{i in 0...3} x[i]*b[i]*b[i].T > b[4]*b[4].T #
which yields an elementwise inequality.
For convenience, it is possible to add a symmetric matrix variable ``X``,
by specifying the option ``vtype=symmetric``. This has the effect to
store all the affine expressions which depend on ``X`` as a function
of its lower triangular elements only.
>>> sdp = pic.Problem()
>>> X = sdp.add_variable('X',(4,4),vtype='symmetric')
>>> sdp.add_constraint(X >> 0)
>>> print sdp #doctest: +NORMALIZE_WHITESPACE
---------------------
optimization problem (SDP):
10 variables, 0 affine constraints, 10 vars in 1 SD cones
<BLANKLINE>
X : (4, 4), symmetric
<BLANKLINE>
find vars
such that
X ≽ |0|
---------------------
In this example, you see indeed that the problem has 10=(4*5)/2 variables,
which correspond to the lower triangular elements of ``X``.
.. Warning::
When a constraint of the form ``A >> B`` is passed to PICOS, it is not
assumed that A-B is symmetric. Instead, the symmetric matrix whose lower
triangular elements are those of A-B is forced to be positive semidefnite.
So, in the cases where A-B is not implicitely forced to be symmetric, you
should add a constraint of the form ``A-B==(A-B).T`` in the problem.
Inequalities involving geometric means
--------------------------------------
......@@ -537,6 +594,12 @@ thanks to the function :func:`picos.geomean() <picos.tools.geomean>` :
>>> t < pic.geomean(t //x[1] //x[1] //1)
# geometric mean ineq : t<geomean( [t;x[1];x[1];1.0])#
Note that the latter example can also be passed to picos in a more simple way,
thanks to an overloading of the ``**`` exponentiation operator:
>>> t < x[1]**(2./3)
# pth power ineq : ( x[1])**2/3>t#
Inequalities involving geometric means are stored in a temporary object
of the class :class:`GeoMeanConstraint <picos.GeoMeanConstraint>`,
which can be passed to a problem with :func:`add_constraint() <picos.Problem.add_constraint>`:
......@@ -556,63 +619,94 @@ are used internally to represent the geometric mean:
# (1x1)-Rotated SOC constraint: ||u[2:4-x]||^2 < ( u[1:4-5])( t) #,
# (1x1)-Rotated SOC constraint: ||t||^2 < ( u[2:0-3])( u[2:4-x]) #]
Semidefinite Constraints
-------------------------
Linear matrix inequalities (LMI) can be entered thanks to an overload of the operators
``<<`` and ``>>``. For example, the LMI
Inequalities involving real powers or trace of matrix powers
------------------------------------------------------------
.. math::
:nowrap:
As mentionned above, the ``**`` exponentiation operator has been overloaded
to support real exponents. A rational approximation of the exponent is used,
and the inequality are internally reformulated as a set of equivalent SOC inequalities.
Note that only inequalities defining a convex regions can be passed:
\begin{equation*}
\sum_{i=0}^3 x_i b_i b_i^T \succeq b_4 b_4^T,
\end{equation*}
>>> t**0.6666 > x[0]
# pth power ineq : ( t)**2/3>x[0]#
>>> t**-0.5 < x[0]
# pth power ineq : ( t)**-1/2<x[0]#
>>> t**-0.5 > x[0] #doctest: +NORMALIZE_WHITESPACE, ELLIPSIS
...
Exception: >= operator can be used only when the function is concave (0<p<=1)
>>> t**2 < x[1]+x[2]
# (1x1)-Rotated SOC constraint: ||t||^2 < x[1] + x[2] #
More generally, inequalities involving trace of matrix powers can be passed to PICOS,
by using the :func:`picos.tracepow() <picos.tools.tracepow>` function. The following example
creates the constraint
.. math::
\operatorname{trace}\ \big(x_0 A_0 A_0^T + x_2 A_2 A_2^T\big)^{2.5} \leq 3.
where :math:`\succeq` is used to denote the Löwner ordering,
is passed to PICOS by writing:
>>> pic.sum([x[i]*b[i]*b[i].T for i in range(4)],'i','0...3') >> b[4]*b[4].T
# (4x4)-LMI constraint Σ_{i in 0...3} x[i]*b[i]*b[i].T ≽ b[4]*b[4].T #
>>> pic.tracepow(x[0] * A[0]*A[0].T + x[2] * A[2]*A[2].T, 2.5) <= 3
# trace of pth power ineq : trace( x[0]*A[0]*A[0].T + x[2]*A[2]*A[2].T)**5/2<3.0#
.. Warning::
when a power expression :math:`x^p` (resp. the trace of matrix power :math:`\operatorname{trace}\ X^p` )
is used, the base :math:`x` is forced to be nonnegative (resp. the base :math:`X` is
forced to be positive semidefinite) by picos.
As for geometric means, inequalities involving real powers are
stored in a temporary object of the class :class:`TracePow_Constraint <picos.TracePow_Constraint>`,
which contains a field ``Ptmp`` , a Problem instance with all the SOC or SDP constraints
used to represent the original inequality.
Note the difference with
Inequalities involving generalized p-norm
-----------------------------------------
>>> pic.sum([x[i]*b[i]*b[i].T for i in range(4)],'i','0...3') > b[4]*b[4].T
# (4x4)-affine constraint: Σ_{i in 0...3} x[i]*b[i]*b[i].T > b[4]*b[4].T #
Inequalities of the form :math:`\Vert x \Vert_p \leq t` can be entered by using the
function :func:`picos.norm() <picos.tools.norm>`. This function is also defined for :math:`p < 1`
by the usual formula :math:`\Vert x \Vert_p := \Big(\sum_i |x_i|^p \Big)^{1/p}`.
The norm function is convex over :math:`\mathbb{R}^n` for all :math:`p\geq 1`, and
concave over the set of vectors with nonnegative coordinates for :math:`p \leq 1`.
which yields an elementwise inequality.
>>> pic.norm(x,3) < t
# p-norm ineq : norm_3( x)<t#
>>> pic.norm(x,0.5) > x[0]-x[1]
# generalized p-norm ineq : norm_1/2( x)>x[0] -x[1]#
.. Warning::
For convenience, it is possible to add a symmetric matrix variable ``X``,
by specifying the option ``vtype=symmetric``. This has the effect to
store all the affine expressions which depend on ``X`` as a function
of its lower triangular elements only.
Note that when a constraint of the form ``norm(x,p) >= t`` is entered (with :math:`p \leq 1` ),
PICOS forces the vector ``x`` to be nonnegative (componentwise).
>>> sdp = pic.Problem()
>>> X = sdp.add_variable('X',(4,4),vtype='symmetric')
>>> sdp.add_constraint(X >> 0)
>>> print sdp #doctest: +NORMALIZE_WHITESPACE
---------------------
optimization problem (SDP):
10 variables, 0 affine constraints, 10 vars in 1 SD cones
<BLANKLINE>
X : (4, 4), symmetric
<BLANKLINE>
find vars
such that
X ≽ |0|
---------------------
As for geometric means, inequalities involving p-norms are
stored in a temporary object of the class :class:`NormP_Constraint <picos.NormP_Constraint>`,
which contains a field ``Ptmp`` , a Problem instance with all the SOC constraints
used to represent the original inequality.
Inequalities involving the nth root of a determinant
----------------------------------------------------
In this example, you see indeed that the problem has 10=(4*5)/2 variables,
which correspond to the lower triangular elements of ``X``.
The function :func:`picos.detrootn() <picos.tools.detrootn>`
can be used to enter the :math:`n` th root of the determinant of a
:math:`(n \times n)-`symmetric positive semidefinite matrix:
>>> M = sdp.add_variable('M',(5,5),'symmetric')
>>> t < pic.detrootn(M)
# nth root of det ineq : det( M)**1/5>t#
.. Warning::
When a constraint of the form ``A >> B`` is passed to PICOS, it is not
assumed that A-B is symmetric. Instead, the symmetric matrix whose lower
triangular elements are those of A-B is forced to be positive semidefnite.
So, in the cases where A-B is not implicitely forced to be symmetric, you
should add a constraint of the form ``A-B==(A-B).T`` in the problem.
Note that when a constraint of the form ``t < pic.detrootn(M)`` is entered (with :math:`p \leq 1` ),
PICOS forces the matrix ``M`` to be positive semidefinite.
As for geometric means, inequalities involving the nth root of a determinant are
stored in a temporary object of the class :class:`DetRootN_Constraint <picos.DetRootN_Constraint>`,
which contains a field ``Ptmp`` , a Problem instance with all the SOC and SDP constraints
used to represent the original inequality.
=========================
Write a Problem to a file
=========================
......
......@@ -15,4 +15,39 @@ P.solve()
#P.solve()
print x
p=-1.33333;[1./(2**(p/(p-1))+1)**(1./p),1./(0.5**(p/(p-1))+1)**(1./p)]
\ No newline at end of file
p=-1.33333;[1./(2**(p/(p-1))+1)**(1./p),1./(0.5**(p/(p-1))+1)**(1./p)]
import picos as pic
p=1.7
P=pic.Problem()
x=P.add_variable('x',1)
t=P.add_variable('t',1)
P.set_objective('max',x-t)
cs = P.add_constraint(x**p<t,ret=True)
print P
P.solve()
print t
print p**(p/(1-p))
p=5./7.
P=pic.Problem()
x=P.add_variable('x',1)
t=P.add_variable('t',1)
P.set_objective('max',t-x)
cs = P.add_constraint(t<x**p,ret=True)
print P
P.solve()
print x
print (1/p)**(1/(p-1))
p = -6/5.
P=pic.Problem()
x=P.add_variable('x',1)
t=P.add_variable('t',1)
P.set_objective('min',t+x)
cs = P.add_constraint(t>x**p,ret=True)
print P
P.solve()
print x
print (-1/p)**(-1/(1-p))
# coding: utf-8
#-------------------------------------------------------------------
#Picos 0.1.4 : A pyton Interface To Conic Optimization Solvers
#Picos 1.0.0 : A pyton Interface To Conic Optimization Solvers
#Copyright (C) 2012 Guillaume Sagnol
#
#This program is free software: you can redistribute it and/or modify
......@@ -28,6 +28,6 @@
from problem import *
from expression import *
from constraint import *
from tools import sum,lse,new_param,diag,diag_vect,geomean,norm,QuadAsSocpError,NotAppropriateSolverError,NonConvexError
from tools import sum,lse,new_param,diag,diag_vect,geomean,norm,tracepow,detrootn,QuadAsSocpError,NotAppropriateSolverError,NonConvexError
__all__=['tools','constraint','expression','problem']
# coding: utf-8
#-------------------------------------------------------------------
#Picos 0.1.4 : A pyton Interface To Conic Optimization Solvers
#Picos 1.0.0 : A pyton Interface To Conic Optimization Solvers
#Copyright (C) 2012 Guillaume Sagnol
#
#This program is free software: you can redistribute it and/or modify
......@@ -32,7 +32,7 @@ import sys
from .tools import *
__all__=['Constraint','_Convex_Constraint','GeoMeanConstraint','NormP_Constraint']
__all__=['Constraint','_Convex_Constraint','GeoMeanConstraint','NormP_Constraint','TracePow_Constraint','DetRootN_Constraint']
class Constraint(object):
"""A class for describing a constraint.
......@@ -317,6 +317,9 @@ class _Convex_Constraint(Constraint):
self.Ptmp = Ptmp
self.myconstring=constring
self.constypestr=constypestr
def __str__(self):
return '# '+self.constypestr+' : ' + self.constring() + '#'
def __repr__(self):
return '# '+self.constypestr+' : ' + self.constring() + '#'
......@@ -339,7 +342,7 @@ class GeoMeanConstraint(_Convex_Constraint):
slack = property(slack_var,Constraint.set_slack,Constraint.del_slack)
class NormP_Constraint(_Convex_Constraint):
""" A temporary object used to pass p-norm inequalities
""" A temporary object used to pass p-norm inequalities.
This class derives from :class:`Constraint <picos.Constraint>`
"""
def __init__(self,expaff,expnorm,alpha,beta,Ptmp,constring):
......@@ -363,3 +366,46 @@ class NormP_Constraint(_Convex_Constraint):
return -(self.expaff.value-norm(self.expnorm,self.numerator,self.denominator).value)
slack = property(slack_var,Constraint.set_slack,Constraint.del_slack)
class TracePow_Constraint(_Convex_Constraint):
""" A temporary object used to pass (trace of) pth power inequalities
This class derives from :class:`Constraint <picos.Constraint>`
"""
def __init__(self,exprhs,explhs,alpha,beta,Ptmp,constring):
self.explhs = explhs
self.exprhs = exprhs
self.numerator=alpha
self.denominator=beta
p = float(alpha)/float(beta)
if explhs.size[0]>1:
_Convex_Constraint.__init__(self,Ptmp,constring,'trace of pth power ineq')
else:
_Convex_Constraint.__init__(self,Ptmp,constring,'pth power ineq')
self.prefix='_ntp'
"""prefix to be added to the names of the temporary variables when add_constraint() is called"""
def slack_var(self):
p = float(self.numerator) / self.denominator
slk = self.exprhs.value-tracepow(self.explhs,self.numerator,self.denominator).value
if p>0 and p<1:
return -slk
else:
return slk
slack = property(slack_var,Constraint.set_slack,Constraint.del_slack)
class DetRootN_Constraint(_Convex_Constraint):
""" A temporary object used to pass nth root of determinant inequalities.
This class derives from :class:`Constraint <picos.Constraint>`
"""
def __init__(self,expdet,exprhs,Ptmp,constring):
self.expdet = expdet
self.exprhs = exprhs
_Convex_Constraint.__init__(self,Ptmp,constring,'nth root of det ineq')
self.prefix='_ndt'
"""prefix to be added to the names of the temporary variables when add_constraint() is called"""
def slack_var(self):
return self.exprhs.value - detrootn(self.expdet).value
slack = property(slack_var,Constraint.set_slack,Constraint.del_slack)
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
# coding: utf-8
#-------------------------------------------------------------------
#Picos 0.1.4 : A pyton Interface To Conic Optimization Solvers
#Picos 1.0.0 : A pyton Interface To Conic Optimization Solvers
#Copyright (C) 2012 Guillaume Sagnol
#
#This program is free software: you can redistribute it and/or modify
......@@ -58,7 +58,8 @@ __all__=['_retrieve_matrix',
'_flatten',
'_remove_in_lil',
'norm',
'_read_sdpa'
'_read_sdpa',
'tracepow',
]
......@@ -167,7 +168,7 @@ def geomean(exp):
Note that geometric mean inequalities are internally reformulated as a
set of SOC inequalities.
** Example: **
** Example:**
>>> import picos as pic
>>> prob = pic.Problem()
......@@ -199,7 +200,7 @@ def norm(exp,num=2,denom=1):
or directly by a float ``p`` given as second argument. In the latter case a rational
approximation of ``p`` will be used.
**Examples: **
**Example:**
>>> import picos as pic
>>> prob = pic.Problem()
......@@ -225,8 +226,67 @@ def norm(exp,num=2,denom=1):
frac = Fraction(p).limit_denominator(1000)
return NormP_Exp(exp,frac.numerator,frac.denominator)
def tracepow(exp,num=1,denom=1):
"""returns a :class:`TracePow_Exp <picos.TracePow_Exp>` object representing the trace of the pth-power of the symmetric matrix ``exp``.
This can be used to enter constraints of the form :math:`\operatorname{trace} X^p \leq t` with :math:`p\geq1` or :math:`p < 0`, or :math:`\operatorname{trace} X^p \geq t` with :math:`0 \leq p \leq 1`.
Note that :math:`X` is forced to be positive semidefinite when a constraint of this form is entered in PICOS.
Trace of power inequalities are internally reformulated as a set of Linear Matrix Inequalities (SDP),
or second order cone inequalities if ``exp`` is a scalar.
The exponent :math:`p` of the norm must be specified either by
a couple numerator (2d argument) / denominator (3d arguments),
or directly by a float ``p`` given as second argument. In the latter case a rational
approximation of ``p`` will be used.
**Example:**
>>> import picos as pic
>>> prob = pic.Problem()
>>> X = prob.add_variable('X',(3,3),'symmetric')
>>> t = prob.add_variable('t',1)
>>> pic.tracepow(X,7,3) < t
# trace of pth power ineq : trace( X)**7/3<t#
>>> pic.tracepow(X,0.6) > t
# trace of pth power ineq : trace( X)**3/5>t#
"""
from .expression import AffinExp
from .expression import TracePow_Exp
if not isinstance(exp,AffinExp):
mat,name=_retrieve_matrix(exp)
exp = AffinExp({},constant=mat[:],size=mat.size,string=name)
if num == denom:
return exp
p = float(num)/float(denom)
if p==0:
raise Exception('undefined for p=0')
from fractions import Fraction
frac = Fraction(p).limit_denominator(1000)
return TracePow_Exp(exp,frac.numerator,frac.denominator)
def detrootn(exp):
"""returns a :class:`DetRootN_Exp <picos.DetRootN_Exp>` object representing the determinant of the
:math:`n` th-root of the symmetric matrix ``exp``, where :math:`n` is the dimension of the matrix.
This can be used to enter constraints of the form :math:`(\operatorname{det} X)^{1/n} \geq t`.
Note that :math:`X` is forced to be positive semidefinite when a constraint of this form is entered in PICOS.
Determinant inequalities are internally reformulated as a set of Linear Matrix Inequalities (SDP).
**Example:**
>>> import picos as pic
>>> prob = pic.Problem()
>>> X = prob.add_variable('X',(3,3),'symmetric')
>>> t = prob.add_variable('t',1)
>>> t < pic.detrootn(X)
# nth root of det ineq : det( X)**1/3>t#
"""
from .expression import AffinExp
from .expression import DetRootN_Exp
if not isinstance(exp,AffinExp):
mat,name=_retrieve_matrix(exp)
exp = AffinExp({},constant=mat[:],size=mat.size,string=name)
return DetRootN_Exp(exp)
def allIdent(lst):
......@@ -873,28 +933,62 @@ def svecm1(vec,triu=False):
return cvx.spmatrix(V,I,J,(n,n))
def ltrim1(vec):
def ltrim1(vec,uptri = True):
"""
If ``vec`` is a vector or an affine expression of size n(n+1)/2, ltrim1(vec) returns a (n,n) matrix with
the elements of vec in the lower triangle.
If ``uptri == False``, the upper triangle is 0, otherwise the upper triangle is the symmetric of the lower one.
"""
if vec.size[1]>1:
raise ValueError('should be a column vector')
from .expression import AffinExp
v=vec.size[0]
n=int(np.sqrt(1+8*v)-1)/2
if n*(n+1)/2 != v:
raise ValueError('vec should be of dimension n(n+1)/2')
if not isinstance(vec,cvx.matrix):
vec=cvx.matrix(vec)
M = cvx.matrix(0.,(n,n))
r = 0
c = 0
for v in vec:
if r==n:
c+=1
r=c
M[r,c]=v
if r>c:
M[c,r]=v
r+=1
if isinstance(vec,cvx.matrix) or isinstance(vec,cvx.spmatrix):
if not isinstance(vec,cvx.matrix):
vec=cvx.matrix(vec)
M = cvx.matrix(0.,(n,n))
r = 0
c = 0
for v in vec:
if r==n:
c+=1
r=c
M[r,c]=v
if r>c and uptri:
M[c,r]=v
r+=1
return M
return M
elif isinstance(vec,AffinExp):
I,J,V=[],[],[]
r = 0
c = 0
for i in range(v):