Giter VIP home page Giter VIP logo

cvxpy / cvxpy Goto Github PK

View Code? Open in Web Editor NEW
5.1K 123.0 1.0K 197.61 MB

A Python-embedded modeling language for convex optimization problems.

Home Page: https://www.cvxpy.org

License: Apache License 2.0

Shell 0.05% Python 25.39% Makefile 0.07% CMake 0.01% C++ 73.37% C 1.09% SWIG 0.02%
python cvxpy optimization modeling-language convex-optimization mathematical-optimization optimization-modeling numerical-optimization

cvxpy's Introduction

CVXPY

Build Status PyPI - downloads Conda - downloads Coverage Benchmarks OpenSSF Scorecard

The CVXPY documentation is at cvxpy.org.

We are building a CVXPY community on Discord. Join the conversation! For issues and long-form discussions, use Github Issues and Github Discussions.

Contents

CVXPY is a Python-embedded modeling language for convex optimization problems. It allows you to express your problem in a natural way that follows the math, rather than in the restrictive standard form required by solvers.

For example, the following code solves a least-squares problem where the variable is constrained by lower and upper bounds:

import cvxpy as cp
import numpy

# Problem data.
m = 30
n = 20
numpy.random.seed(1)
A = numpy.random.randn(m, n)
b = numpy.random.randn(m)

# Construct the problem.
x = cp.Variable(n)
objective = cp.Minimize(cp.sum_squares(A @ x - b))
constraints = [0 <= x, x <= 1]
prob = cp.Problem(objective, constraints)

# The optimal objective is returned by prob.solve().
result = prob.solve()
# The optimal value for x is stored in x.value.
print(x.value)
# The optimal Lagrange multiplier for a constraint
# is stored in constraint.dual_value.
print(constraints[0].dual_value)

With CVXPY, you can model

  • convex optimization problems,
  • mixed-integer convex optimization problems,
  • geometric programs, and
  • quasiconvex programs.

CVXPY is not a solver. It relies upon the open source solvers Clarabel, ECOS, SCS, and OSQP. Additional solvers are available, but must be installed separately.

CVXPY began as a Stanford University research project. It is now developed by many people, across many institutions and countries.

Installation

CVXPY is available on PyPI, and can be installed with

pip install cvxpy

CVXPY can also be installed with conda, using

conda install -c conda-forge cvxpy

CVXPY has the following dependencies:

  • Python >= 3.8
  • Clarabel >= 0.5.0
  • OSQP >= 0.6.2
  • ECOS >= 2
  • SCS >= 3.2.4.post1
  • NumPy >= 1.15
  • SciPy >= 1.1.0

For detailed instructions, see the installation guide.

Getting started

To get started with CVXPY, check out the following:

Issues

We encourage you to report issues using the Github tracker. We welcome all kinds of issues, especially those related to correctness, documentation, performance, and feature requests.

For basic usage questions (e.g., "Why isn't my problem DCP?"), please use StackOverflow instead.

Community

The CVXPY community consists of researchers, data scientists, software engineers, and students from all over the world. We welcome you to join us!

  • To chat with the CVXPY community in real-time, join us on Discord.
  • To have longer, in-depth discussions with the CVXPY community, use Github Discussions.
  • To share feature requests and bug reports, use Github Issues.

Please be respectful in your communications with the CVXPY community, and make sure to abide by our code of conduct.

Contributing

We appreciate all contributions. You don't need to be an expert in convex optimization to help out.

You should first install CVXPY from source. Here are some simple ways to start contributing immediately:

If you'd like to add a new example to our library, or implement a new feature, please get in touch with us first to make sure that your priorities align with ours.

Contributions should be submitted as pull requests. A member of the CVXPY development team will review the pull request and guide you through the contributing process.

Before starting work on your contribution, please read the contributing guide.

Team

CVXPY is a community project, built from the contributions of many researchers and engineers.

CVXPY is developed and maintained by Steven Diamond, Akshay Agrawal, Riley Murray, Philipp Schiele, and Bartolomeo Stellato, with many others contributing significantly. A non-exhaustive list of people who have shaped CVXPY over the years includes Stephen Boyd, Eric Chu, Robin Verschueren, Michael Sommerauer, Jaehyun Park, Enzo Busseti, AJ Friend, Judson Wilson, and Chris Dembia.

For more information about the team and our processes, see our governance document.

Citing

If you use CVXPY for academic work, we encourage you to cite our papers. If you use CVXPY in industry, we'd love to hear from you as well, on Discord or over email.

cvxpy's People

Contributors

ajfriend avatar akshayka avatar alexbrc avatar aryamanjeendgar avatar aszekmosek avatar bstellato avatar chrisdembia avatar dependabot[bot] avatar echu avatar enzbus avatar jaehyunp avatar jiaxinwang-thu avatar judsonwilson avatar macklin avatar misrab avatar mkoeppe avatar mlubin avatar mwytock avatar parthb83 avatar paulnkk avatar phschiele avatar ptnobel avatar r-barnes avatar rileyjmurray avatar rkersh avatar rmcgibbo avatar roversch avatar stevediamond avatar transurgeon avatar tridao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cvxpy's Issues

Slowness/failure of entropy optimization compared to MATLAB cvx

Hi,

I'm trying to run a simple proof-of-concept entropy optimization in cvxpy:

import cvxpy as cp
import cvxopt
import numpy as np

N = 50
p = cp.Variable(N)
objective = cp.Maximize( sum(cp.entr(p)) )
cvx_constraints = [ np.ones( (1, N) ) * p == 1 ]
problem = cp.Problem(objective, cvx_constraints)
result = problem.solve()
print p.value

If N = 20, it finishes in < 1 second. If N = 30, it takes 23 seconds. If N = 50, it fails for some reason after 30 seconds (with no error) and prints None for p.value.

By contrast, I can run the identical MATLAB program with N = 1000 and it finishes successfully in < 2 minutes:

tic
N = 1000;
cvx_begin
    variable p(N)
    maximize(sum(entr(p)))
    subject to
        ones(1, N) * p == 1
cvx_end
toc

Is there anything to be done about this? Thanks!

is_dcp() doesn't work

The docs says "To check whether an Expression object follows the DCP rules, use the method expr.is_dcp(). Constraints, Objectives, and Problems also have an is_dcp method". However:

kbriggs:~/python> python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49) [GCC 4.8.1] on linux2

import cvxpy as cp
x = cp.Variable(5)
x.is_dcp()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Variable' object has no attribute 'is_dcp'
expr = 2*x # expr is an Expression object after each assignment.
expr.is_dcp()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'MulExpression' object has no attribute 'is_dcp'
type(expr)
<class 'cvxpy.atoms.affine.binary_operators.MulExpression'>

Bug in optimizer

Hi,
I was trying to solve a mean-variance optimization problem with constraints on the weights to in [0,1]. The solver returns negative values for some of the weights. Here is the code:

import cvxpy as cp
import numpy as np
import cvxopt

n=3
muVector=np.matrix([7.2,9.8,2.5])
sigma = np.diag([100,50,10])

x=cp.Variable(n)

expectedReturn = muVector_x
risk = cp.quad_form(x,sigma)
riskaversion=(.5)__-20
objective=cp.Maximize(expectedReturn - riskaversion_risk)
constraints = [0 <= x, x <= 1,sum(x)==1]

p=cp.Problem(objective,constraints)
p.solve()
for w in x.value:
print w

-0.196307484923
-0.257650575912
1.45395806083

Example problem using log atom does not converge within maxiter

The code below (feel free to use it as a test case or example problem) calculates the maximum expected log return for investment in 10 different assets with 10 different outcome scenarios. The objective is similar to that of acent.py, but it is a weighted sum of logs. The solvers do not converge to the solution within maxiter, though it is a rather straightforward problem. Any ideas?

import cvxpy as cvx
import cvxopt

scenario_probabilities = cvx.numpy.array((0.3,0.15,0.1,0.1,0.06,0.06,0.06,0.06,0.06,0.05)).reshape(1,-1)
joint_returns = cvx.numpy.array( \
    [[ 1.09,  0.96,  0.95,  1.06,  1.09,  1.54,  1.16,  1.01,  0.82,  1.04], \
    [ 1.14,  1.02,  1.04,  1.07,  1.02,  0.93,  1.09,  0.85,  1.47,  1.21], \
    [ 1.01,  1.35,  0.95,  0.81,  1.05,  0.85,  1.02,  0.88,  1.  ,  1.05], \
    [ 1.1 ,  0.96,  1.13,  1.95,  1.06,  0.81,  1.02,  1.12,  0.95,  0.97], \
    [ 1.12,  0.9 ,  1.  ,  1.08,  1.1 ,  1.07,  1.7 ,  0.94,  0.97,  0.93], \
    [ 1.64,  1.01,  1.25,  0.97,  0.93,  1.03,  0.81,  1.13,  1.02,  0.91], \
    [ 0.85,  0.95,  0.98,  0.99,  1.1 ,  1.02,  1.04,  1.67,  0.96,  0.96], \
    [ 1.15,  0.97,  1.54,  0.95,  1.09,  1.14,  1.08,  0.9 ,  0.91,  0.82], \
    [ 1.13,  0.95,  1.1 ,  1.03,  1.89,  1.2 ,  0.97,  1.04,  1.04,  1.  ], \
    [ 0.93,  1.08,  0.84,  0.97,  0.95,  0.8 ,  0.95,  0.98,  1.29,  1.46]])

portfolio = cvx.Variable(10)
riskfree = cvx.Variable()
scenario_returns = riskfree + joint_returns.T * portfolio
objective = scenario_probabilities * cvx.log(scenario_returns) 
p = cvx.Problem(cvx.Maximize(objective),[scenario_returns >= 1e-5, riskfree + sum(portfolio) <= 1])

p.solve()

Ecos needs to be installed explicitly.

Hey guys I don't know whether I did something wrong but when I installed cvxpy (already had cvxopt,numpy and scipy) it didn't let me run the first statement
"from cvxpy import * " because I didn't have the "ecos" module installed. So I would suggest that you either list that as one of the dependencies in the documentation or install it implicitly during cvxpy install. I see a .sh file that does install this but I don't think that is ever called, not a big deal just a suggestion. And it works fine after I installed "ecos" so thanks for your hard work!

Python 3 support?

How feasible would it be to add support for python 3? A lot of the solver interfaces and other packages these days are compatible, and quite a few people (including me) like to work in python 3 if possible.

Installation runs smoothly but there are some import issues when trying to load the cvxpy package. Seems to have something to do with namespaces?

Using numpy.random.randn(m,n) instead of cvxopt.normal(m,n) in objective

When using numpy instead of cvxopt for A,

objective1 = Minimize( norm(A*x1-b, 1) )
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxpy/atoms/norm.py", line 29, in norm
x = Expression.cast_to_const(x)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxpy/expressions/expression.py", line 114, in cast_to_const
return expr if isinstance(expr, Expression) else types.constant()(expr)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxpy/expressions/constants/constant.py", line 33, in init
self.set_context()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxpy/expressions/constants/constant.py", line 50, in set_context
sign = intf.sign(self.value)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxpy/interface/matrix_utilities.py", line 98, in sign
mat = INTERFACES[np.ndarray].const_to_matrix(constant)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxpy/interface/numpy_interface/ndarray_interface.py", line 32, in const_to_matrix
mat = numpy.array(value, dtype='float64')
ValueError: setting an array element with a sequence.

problem with qcqp.py

kbriggs:~/Downloads/cvxpy-master/examples> python qcqp.py
[ 4.69e+00 3.73e+00 3.66e+00 -4.17e+00 -3.56e+00 -2.45e-01]
[ 3.73e+00 8.01e+00 3.37e+00 -6.34e-01 -3.51e-01 -3.17e+00]
[ 3.66e+00 3.37e+00 6.14e+00 -5.39e+00 -4.22e+00 -7.17e-01]
[-4.17e+00 -6.34e-01 -5.39e+00 7.85e+00 5.11e+00 -6.85e-01]
[-3.56e+00 -3.51e-01 -4.22e+00 5.11e+00 7.31e+00 -1.02e+00]
[-2.45e-01 -3.17e+00 -7.17e-01 -6.85e-01 -1.02e+00 2.19e+00]

Traceback (most recent call last):
File "qcqp.py", line 65, in
if get_status(primal_result) is SOLVED:
NameError: name 'get_status' is not defined

handle complex variable

Hi, I was wondering if cvxpy can handle problem with complex numbers.
I want to solve a optimazation problem like
minimize norm2(x)
subject to: Ax = b

in which A, b contains complex elements.
How should I program by CVXPY/
Thank you for helps.

Vstack import

I'm 90% sure the error is happening because I forgot to commit a file in my patch yesterday. I'll fix it as soon as I have computer access today.

Different dual variable results from Matlab obtained for A4.1

This issue relates to question 4.1 of the EE364A additional exercises.

I tried this both on Matlab and Python and obtained different results for the dual variable, for the same problem and data. The primal optimal variable value is the same. The difference in dual variables between CVX for Matlab and CVXPY is on the order of 1e-1.

The following code snippets are the minimum necessary to see the differing dual variable values (lambda). I can provide the full scripts if that would be helpful.

A = [1 -0.5; -0.5 2];
C = [1 2; 1 -4];
E = [5 76];
d = [-2; -3];
f = 1;

cvx_begin quiet
    variable x(2)
    dual variable lambda1
    dual variable lambda2
    minimize quad_form(x, A) - x(1)
    subject to
        lambda1 : C*x <= d
        lambda2 : E*x <= f
cvx_end

optimal = cvx_optval
x
lambda = [lambda1; lambda2]

Matlab output:

>> add4q1_test
optimal =
    8.2222
x =
   -2.3333
    0.1667
lambda =
    1.8994
    3.4684
    0.0931

Python:

import cvxpy as cp
import numpy.matlib as ml
import itertools
mat = ml.asmatrix
concat = ml.concatenate

x = cp.Variable(2)
u = cp.Parameter(2)

A = mat('1 -0.5; -0.5 2')
C = mat('1 2; 1 -4')
E = mat('5 76')
f = 1
objective = cp.Minimize(cp.quad_form(x, A) - x[0])
constraints = [
    C*x <= u,
    E*x <= f
]
problem = cp.Problem(objective, constraints)

u_original = mat('-2; -3')
u.value = u_original

result = problem.solve()
status = cp.get_status(result)

x_val = mat(x.value)
lambda_val = concat((mat(constraints[0].dual_value), mat(constraints[1].dual_value)))

print "Status:", status
print "Optimal value p*:", result
print "Optimal primal value x*:", x_val.T
print "Optimal dual value lambda*:", lambda_val.T

Python output:

$ python add4q1_test.py
Status: solved
Optimal value p*: 8.2222216673
Optimal primal value x*: [[-2.33333352  0.16666658]]
Optimal dual value lambda*: [[ 1.18646785  3.95896591  0.13766984]]

Minimum Volume Ellipsoid

Hey,

I'm just starting to work with this library, and I've gotten a few problems working, which is great. However, I'm currently trying to find the minimum volume ellipsoid containing a finite set of points, and I'm having a hard time understanding how to express that objective using this library. I haven't found either the logdet(A) or the det(A)^(1/n) functions available as concave objectives for A = Variable(n,n). Is this available and I have just missed it, or is this objective planned to be implemented?

Silence Output

Is there a way to silence the output to the console? The old syntax from 0.0.1 is not working any more. Thanks!

MemoryError on Win7 (PythonXY 2.7.3.1)

When creating a semidefinite cone, a MemoryError exception is thrown. It appears to be caused by using line 55 in semidefinite_cone.py. When m is assigned el.shape[0] this has a type of numpy.int32. Using this type to index G in line 65 causes the memory error. Changing line 55 to:

m = int(el.shape[0])

eliminated the exception.

Elementwise entropy function?

Any chance there will be an elementwise entropy function coming to cvxpy? The MATLAB version of cvx has a function called entr, where entr(x) = x .* log(x). See http://cvxr.com/cvx/doc/funcref.html#built-in-functions.

I know I can construct this using the kl_div atom, but that takes scalar arguments so I have to add all the scalars in my (long) vector variable, which seems like it might be inefficient (?)

How to turn off the printing to the console

Hi,
This happened after the very last update. Now when I call prob.solve(), it prints a lot of stuff to the console. I am guessing it is due to something that was turned on for debugging. Anyway, just wanted to give you a quick feedback on that.

atoms with generators

The code:

square(xi - yi for xi, yi in zip(expression_list, constant_list))

yields the error

Exception: <type 'generator'> is not a valid type for a Constant value.

log atom?

Is there a way to model the log function? I believe it exists in CVXOPT, but I couldn't find it in CVXPY.

constant sparse matrices are no longer supported

working with sparse matrices results in an error, as evidenced in the 'stock_tradeoff.py' example script:

python examples/stock_tradeoff.py
Traceback (most recent call last):
File "stock_tradeoff.py", line 19, in
variance = square(norm2(F.T_x)) + square(norm2(D_x))
File "/python2.7/site-packages/cvxpy/expressions/expression.py", line 144, in rmul
return Expression.cast_to_const(other) * self
File "/python2.7/site-packages/cvxpy/expressions/expression.py", line 75, in cast_to_const
return expr if isinstance(expr, Expression) else types.constant()(expr)
File "/python2.7/site-packages/cvxpy/expressions/constant.py", line 34, in init
self.set_sign_curv()
File "/python2.7/site-packages/cvxpy/expressions/constant.py", line 54, in set_sign_curv
sign = intf.sign(self.value)
File "/python2.7/site-packages/cvxpy/interface/matrix_utilities.py", line 90, in sign
mat = NDARRAY_INTERFACE.const_to_matrix(constant)
File "/python2.7/site-packages/cvxpy/interface/numpy_interface/ndarray_interface.py", line 34, in const_to_matrix
return numpy.array(value, dtype='float64')
TypeError: float() argument must be a string or a number

Update PyPi release of cvxpy to include the setup.py changes

If the PyPi release is updated, then people should be able to simply easy_install cvxpy or pip install cvxpy and get the dependencies automatically.

But apparently, easy_install cvxopt doesn't successfully install cvxopt on Windows, so I suppose automatic installation of dependencies for cvxpy isn't quite as useful.

solver_error (scalibility?)

Hi, I am writng a code for example 1 in
http://see.stanford.edu/materials/lsocoee364a/hw6sol.pdf
The probelm require k = 201, and I encountered solver_error during optimzation.
I tried k =40, then the result is perfected fitted. Is this probelm related to the scalibility of cvxpy? (The code is pasted here)

import numpy as np
import cvxpy as cp
k = 80
t = [-3.0+6.0*(i)/(k-1) for i in range(k) ]
y = np.exp(t)
T_powers = np.matrix(np.hstack((np.ones((k,1)),np.matrix(t).T,np.power(np.matrix(t).T,2))))
u = np.exp(3)
l = 0
bisection_tol = 1e-3
gamma1 = cp.Parameter(sign='positive')
a = cp.Variable(3)
b = cp.Variable(2)
objective = 0

constraints = [cp.abs(T_powers[i]a-y[i](T_powers[i]cp.vstack(1,b)))<=gamma1(T_powers[i]*cp.vstack(1,b)) for i in range(100)]

constraints = [T_powers_a-np.diag(y)(T_powers_cp.vstack(1,b))<=gamma1(T_powers*cp.vstack(1,b)),

T_powers_a-np.diag(y)(T_powers_cp.vstack(1,b))>=-gamma1(T_powers_cp.vstack(1,b))]

constraints = [cp.abs(T_powers_a-np.diag(y)(T_powers_cp.vstack(1,b)))<=gamma1(T_powers_cp.vstack(1,b))]
objective = cp.Minimize(0)
p = cp.Problem(objective,constraints)
gamma1.value = (l+u)/2.0
a_opt = 0
b_opt = 0
gamma1.value = (u+l)/2
while (u-l)>=bisection_tol:
print p.is_dcp()
p.solve()
if p.status is 'optimal':
u = gamma1.value
a_opt = a.value
b_opt = b.value
#print a_opt
#print b_opt
objval_opt = gamma1.value
#print 'here'

else:
    l = gamma1.value
gamma1.value = (l+u)/2
#print gamma1.value
print p.status

y_fit = T_powers*a_opt

print a_opt
print b_opt
print gamma1.value
plot(t,y,'b')
f_fit = np.divide(T_powers_a_opt,T_powers_np.vstack((1,b_opt)))
plot(t,f_fit,'r+')

Test case fails

running "nosetests" in the base directory yields an error:

ERROR: Failure: ImportError (No module named containers)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/nose-1.2.1-py2.7.egg/nose/loader.py", line 390, in loadTestsFromName
addr.filename, addr.module)
File "/Library/Python/2.7/site-packages/nose-1.2.1-py2.7.egg/nose/importer.py", line 39, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/Library/Python/2.7/site-packages/nose-1.2.1-py2.7.egg/nose/importer.py", line 86, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/Users/echu/src/cvxpy/tests/test_expressions.py", line 5, in
from cvxpy.expressions.containers import Variables
ImportError: No module named containers

shadowing builtins

as much as "from cvxpy import *" is convenient, i think we should either

(a) discourage this or
(b) ensure that our atoms escape to builtins when appropriate

i was using some code that involved "min" somewhere and it just did not work as expected; the error messages are very cryptic and the result is actually quite surprising.

error with vstack

changing import to 'cvxpy.atoms.vstack' is most obvious fix, but that creates a circular dependency in the Atom class.

Traceback (most recent call last):
File "app.py", line 4, in
from cvxpy import *
File "/python2.7/site-packages/cvxpy/init.py", line 20, in
from atoms import *
File "/python2.7/site-packages/cvxpy/atoms/init.py", line 20, in
from abs import abs
File "/python2.7/site-packages/cvxpy/atoms/abs.py", line 20, in
from atom import Atom
File "/python2.7/site-packages/cvxpy/atoms/atom.py", line 21, in
from cvxpy.expressions.variable import Variable
File "/python2.7/site-packages/cvxpy/expressions/variable.py", line 21, in
import cvxpy.interface.matrix_utilities as intf
File "/python2.7/site-packages/cvxpy/interface/matrix_utilities.py", line 23, in
import cvxpy.utilities as u
File "/python2.7/site-packages/cvxpy/utilities/init.py", line 22, in
from curvature import Curvature
File "/python2.7/site-packages/cvxpy/utilities/curvature.py", line 21, in
from vstack import vstack
ImportError: No module named vstack

dims[] errors

After installing cvxpy and running tests I got about 60 errors like
dims['l'] ought to be a nonnegative integer

For example this code works fine
import cvxopt
import cvxpy as cp
c = cvxopt.matrix([1, 1])
x = cp.Variable(2)
objective = cp.Minimize(c.T_x)
a1 = cvxopt.matrix([2, 1], (1, 2))
a2 = cvxopt.matrix([1, 3], (1, 2))
b1 = 1
b2 = 1
constraints = [0 <= x, a1_x >= b1, a2*x >= b2]
p = cp.Problem(objective, constraints)
result = p.solve()

This code:
import cvxopt
import cvxpy as cp
c = cvxopt.matrix([1, 1])
x = cp.Variable(2)
objective = cp.Minimize(c.T_x)
A = cvxopt.matrix([2, 1, 1, 3], (2, 2))
b = cvxopt.matrix([1, 1])
constraints = [0 <= x, A_x >= b]
p = cp.Problem(objective, constraints)
result = p.solve()
raise error
dims['l'] ought to be a nonnegative integer

QP problem from examples like this
n = 3
P = cvxopt.matrix([13, 12, -2, 12, 17, 6, -2, 6, 12], (n,n))
q = cvxopt.matrix([-22, -14.5, 13], (n,1))
r = 1
x = Variable(n)
objective = Minimize( 0.5 * quad_form(x, P) + q.T * x + r )
constraints = [ x >= -1, x <= 1]
p = Problem(objective, constraints)
result = p.solve()
raise error
dims['q'] ought to be a list of positive integers

Slice Variable

Hi,

Can you tell me if Variable can be sliced and how. I try the following code
x= Variable(3,30)
x[:,1]
it gave Exception: Invalid indices 1,slice(2, 2, None) for 'var30194'.

Thank you for any help!

SDP problem

Solving the following SDP problem, gives me a matrix that is not positive semi-definite. I was wondering what the problem is.

import numpy as np
from pylab import *
import cvxopt as co
import cvxpy as cp

x1 = cp.Variable()
x2 = cp.Variable()
x3 = cp.Variable()
t = cp.Variable()

A0 = co.matrix([[0,0,0,-2],[0,0,0,-3],[0,0,0,-4],[-2,-3,-4,0]])
A1 = co.matrix([[0,0,0,1],[0,0,0,2],[0,0,0,3],[1,2,3,0]])
A2 = co.matrix([[0,0,0,1],[0,0,0,1],[0,0,0,2],[1,1,2,0]])
A3 = co.matrix([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])
I = np.identity(4)

objective = cp.Minimize(x3)

constraints = [ A0+A1_x1+A2_x2+A3*x3 >= 0 ]

p = cp.Problem(objective, constraints)

result=p.solve()
print(result)

print(x1.value)

print(x2.value)

print(x3.value)

print(np.linalg.eig(A0+A1_x1.value+A2_x2.value+A3*x3.value)[0])

CVXOPT exception is not very descriptive to user

I tried to use CVXPY with the CVXOPT solver, and ended up with the following exception:

ValueError: Rank(A) < p or Rank([G; A]) < n

It'd be nice if CVXPY could catch this exception and emit a more information error message about my constraints. I think a user shouldn't need to know what CVXOPT calls G.

Vector variables and matrices

When I run the following code in Sage, the problem is unbounded. I was wondering what the problem is.

from future import division
RealNumber=float
Integer=int
from cvxopt.base import matrix as m
import cvxopt
import numpy
from pylab import *
import math
from cvxpy import *

x = Variable(2)

constraints

a1 = m([1,1])
a2 = m([2,1])
constraints = [ a1.T_x >= -1, a2.T_x <= 10]

objective

objective = Maximize(sum(x))

p = Problem(objective, constraints)
result = p.solve()
print result

The optimal value

print x.value

Examples do not run (ValueError: invalid shape)

The example at the head of README.md and the examples in the examples directory do not run. Inside Problem.solve(), SciPy throws a "ValueError: invalid shape" exception. The example notebook pa3p8 has the same problem, but pa13p3 runs correctly.

I am running Ubuntu Saucy (13.10), Python 2.7.5, IPython 1.2.0, CVXOPT 1.1.6, and the latest cvxpy from git.

kl_div with non-constant arguments

I can't get figure out how to use this. Maybe a test or example could be included for the KL divergence of a variable distribution from a constant distribution (or constant from variable, or variable from variable)?

Comparisons with ndarrays of Variable do not work as intended

First of all, thanks for cvxpy. It seems to me like a promising and already quite useful piece of software.

I have noted that comparisons with numpy arrays of cvxpy Variable objects do not function. Minimal illustration follows (Python 2.7):

import numpy as np
import cvxpy as cp

a = np.array([cp.Variable(), cp.Variable()], dtype=object)
b = np.array([cp.Variable(), cp.Variable()], dtype=object)
c = 3

print a <= c
print a == c
print a > c
print a == b
print a >= b

The result of each comparison is [True, True], but I had hoped it would produce an object array with comparisons like array([var1 <= 3, var2 <=3]) etc.

Conflict with pylab --inline

I experience conflicts with pylab --inline in Ipython notebooks. In a nutshell:

%pylab inline
import cvxpy as cp

x = cp.Variable(5)
objective = cp.Minimize(sum(cp.square(x)))

throws the exception "type 'str' is not a valid type for a Constant value.". No problem without pylab inline. My installation is latest cvxpy from github repo, Python 2.7.3, Matplotlib 1.3.1, Ipython 1.0.0. and Windows 8 64bit. Thanks!

import convex_sets as cs

In examples/geometry/separating_hyperplanes.py, there is:

import convex_sets as cs

but it generates:
File "/../cvxpy-master/examples/geometry/convex_sets.py", line 4, in
from cvxpy.expressions.affine import AffObjective
ImportError: No module named affine

I was wondering what the problem is.

log_normcdf equivalent

Hi,
I would like to know if there is any way to create objective function with log_normcdf like cvx?

Issue with min

Hi, Thank you for your excellent project. I am new to python and now trying to run an example from the text book of convex optimazation 4.17 (addition excercise from online course).
I would like to find minimum values for each row in a matrix containing expressions and then sum those min values (this will be served as objective). However, I recieved a buffer format not supported error. I guess min cannot take matrix containing expressions as arguments, then what should I do? Any helps is highly appreciated.

schur complement

I wanted to make the schur complement of a positive semidefinite matrix in a way that cvxpy understands the schur complement properties.

Use cvxpy for quadratic programing?

Hi, I wonder if cvxpy can be used for modeling quadratic programing and how to fomulate it . For instance, is there something like quad_form in cvx? or Can I express qp into a equavelent form? (in matrix form)

Thank you very much

quad_form breaks for matrices with 0 eigenvalues

I generated a random 10 x 20 matrix Q and took P = Q.T * Q, so this is a positive semidefinite matrix. I then defined a variable x. Calling cvxpy.quad_form(x, P) fails with the exception "P has both positive and negative eigenvalues". Indeed, some of the zero eigenvalues are stored as -1e-14 due to numerical precision. However, for some reason, quad_form in the Matlab version of CVX handles such a P with no problem (even though it has the same numerical issues with negative eigenvalues).

separating_polyhedra.py doesn't work

kbriggs:~/Downloads/cvxpy-master/examples/geometry> python separating_polyhedra.py
Traceback (most recent call last):
File "separating_polyhedra.py", line 4, in
import convex_sets as cs
File "/home/kbriggs/Downloads/cvxpy-master/examples/geometry/convex_sets.py", line 4, in
from cvxpy.expressions.affine import AffObjective
ImportError: No module named affine

CVXPY is unbounded with constraints but bounded without constraints.

I am solving a linear program where objective is minimization is norm1. Clearly the objective is bounded. After adding a few constraints and solving it with cvxpy.ECOS, I get status as "unbounded". If I solve the same problem, without the constraints I get an answer. The data and math program are documented here:
http://nbviewer.ipython.org/gist/vijayvd/8319396

The latexed version of the math program can be seen if you download the ipython notebook. For some reason it is not rendering on the nbviewer site.

How can we change solver options ?

I have a log det sdp problem with linear inequality constraints in matrix variables. I tried to solve it using new cvxpy but it couldn't solve it. I got 'solver_error' in prog.status.

I tried to solve it using old cvxpy and at first, I got "Terminated (singular KKT matrix)" error message. Then I decreased the precision using
prog.options['abstol']=1e-02
prog.options['feastol']=1e-04
prog.options['reltol']=1e-04
and it worked fine.

How can we modify solver options using new cvxpy ? (I am using cvxopt's solver)

Missing Package

Hi all,
I tried installing cvxpy but when running setup.py I ran in the following error:

error: package directory 'cvxpy/atoms/nonlinear' does not exist

Indeed there is no nonlinear folder in the atoms directory, my solution was to comment out line 12 in setup.py in order to skip the package.

IndexVariable value property

Currently, the "value" property of an IndexVariable accesses its parent's value.

It ought to check if the parent.value is None before attempting to index into it with self.key.

# The value at the index.
@property
def value(self):
    return self.parent.value[self.key]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.