Code Monkey home page Code Monkey logo

cvxpy's Introduction

CVXPY

Build Status Build status Downloads Join the chat at https://gitter.im/cvxgrp/cvxpy

Join the CVXPY mailing list and Gitter chat for the best CVXPY support!

The CVXPY documentation is at cvxpy.org.

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:

from cvxpy import *
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 = Variable(n)
objective = Minimize(sum_squares(A*x - b))
constraints = [0 <= x, x <= 1]
prob = 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)

CVXPY was designed and implemented by Steven Diamond, with input from Stephen Boyd and Eric Chu.

A tutorial and other documentation can be found at cvxpy.org.

This git repository holds the latest development version of CVXPY. For installation instructions, see the install guide at cvxpy.org.

cvxpy's People

Contributors

ajfriend avatar alexbrc avatar aorthey avatar bakhtiary avatar chrisdembia avatar cmale avatar dstonest avatar echu avatar enzbus avatar gbaier avatar gitter-badger avatar jaehyunp avatar judsonwilson avatar jwkvam avatar macklin avatar mirage007 avatar misrab avatar mseesquared avatar mwytock avatar pierre-haessig avatar rmcgibbo avatar sergiocallegari avatar stevediamond avatar tompx avatar tridao avatar

Watchers

 avatar  avatar

cvxpy's Issues

diff

Hey @SteveDiamond,

I'm trying to implement a simple diff expression in CVXPY: https://github.com/ajfriend/cvxpy/blob/master/cvxpy/atoms/affine/diff.py

I have two questions:

  1. My current tests are failing, and I'm not sure why. Any ideas?
    https://github.com/ajfriend/cvxpy/blob/master/cvxpy/tests/test_constant_atoms.py

  2. There's some gross type checking I'm doing to catch wether the input x is a numpy NDarray or a cvxpy Variable. Do you know a better way of doing that? Or a way of avoiding that check entirely?

error with power, p == 0

I'm starting to get the power atom added, but I get an error
when I run the test script mytest.py.

The point of the test was to try out the edge case of p=0, which should give an expression of all 1's.
But I get the following error. Any idea what I'm doing wrong, @SteveDiamond?

As a side note, when p=0, so power(x, 0) == 1, should the monotonicity of the atom be u.monotonicity.NONMONOTONIC?

$ ipython mytest.py
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/ajfriend/Dropbox/work/cvxpy/mytest.py in <module>()
      7
      8 prob = cvx.Problem(cvx.Maximize(cvx.sum_entries(g) + y), [0 <= x, x <= 1, y <= 2])
----> 9 prob.solve()

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/problems/problem.pyc in solve(self, *args, **kwargs)
    154             return func(self, *args, **kwargs)
    155         else:
--> 156             return self._solve(*args, **kwargs)
    157
    158     @classmethod

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/problems/problem.pyc in _solve(self, solver, ignore_dcp, warm_start, verbose, **kwargs)
    224                 raise Exception("Problem does not follow DCP rules.")
    225
--> 226         objective, constraints = self.canonicalize()
    227         # Choose a solver/check the chosen solver.
    228         if solver is None:

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/problems/problem.pyc in canonicalize(self)
    101         """
    102         canon_constr = []
--> 103         obj, constr = self.objective.canonical_form
    104         canon_constr += constr
    105

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/utilities/performance_utils.pyc in _lazyprop(self)
     36         """
     37         if not hasattr(self, attr_name):
---> 38             setattr(self, attr_name, func(self))
     39         return getattr(self, attr_name)
     40     return _lazyprop

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/utilities/canonical.pyc in canonical_form(self)
     44             A tuple of (affine expression, [constraints]).
     45         """
---> 46         return self.canonicalize()
     47
     48     @abc.abstractmethod

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/problems/objective.pyc in canonicalize(self)
     82         """Negates the target expression's objective.
     83         """
---> 84         obj, constraints = super(Maximize, self).canonicalize()
     85         return (lu.neg_expr(obj), constraints)
     86

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/problems/objective.pyc in canonicalize(self)
     44         """Pass on the target expression's objective and constraints.
     45         """
---> 46         return self._expr.canonical_form
     47
     48     def variables(self):

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/utilities/performance_utils.pyc in _lazyprop(self)
     36         """
     37         if not hasattr(self, attr_name):
---> 38             setattr(self, attr_name, func(self))
     39         return getattr(self, attr_name)
     40     return _lazyprop

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/utilities/canonical.pyc in canonical_form(self)
     44             A tuple of (affine expression, [constraints]).
     45         """
---> 46         return self.canonicalize()
     47
     48     @abc.abstractmethod

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/atoms/atom.pyc in canonicalize(self)
    114             constraints = []
    115             for arg in self.args:
--> 116                 obj, constr = arg.canonical_form
    117                 arg_objs.append(obj)
    118                 constraints += constr

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/utilities/performance_utils.pyc in _lazyprop(self)
     36         """
     37         if not hasattr(self, attr_name):
---> 38             setattr(self, attr_name, func(self))
     39         return getattr(self, attr_name)
     40     return _lazyprop

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/utilities/canonical.pyc in canonical_form(self)
     44             A tuple of (affine expression, [constraints]).
     45         """
---> 46         return self.canonicalize()
     47
     48     @abc.abstractmethod

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/atoms/atom.pyc in canonicalize(self)
    109             # Non-parameterized expressions are evaluated immediately.
    110             else:
--> 111                 return Constant(self.value).canonical_form
    112         else:
    113             arg_objs = []

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/expressions/constants/constant.pyc in __init__(self, value)
     34             self._sparse = True
     35         else:
---> 36             self._value = intf.DEFAULT_INTERFACE.const_to_matrix(value)
     37             self._sparse = False
     38         # Set DCP attributes.

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/interface/base_matrix_interface.pyc in new_converter(self, value, convert_scalars)
     47     def scalar_const(converter):
     48         def new_converter(self, value, convert_scalars=False):
---> 49             if not convert_scalars and cvxpy.interface.matrix_utilities.is_scalar(value):
     50                 return cvxpy.interface.matrix_utilities.scalar_value(value)
     51             else:

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/interface/matrix_utilities.pyc in is_scalar(constant)
     76 # Is the constant a scalar?
     77 def is_scalar(constant):
---> 78     return size(constant) == (1, 1)
     79
     80 def from_2D_to_1D(constant):

/Users/ajfriend/Dropbox/work/cvxpy/cvxpy/interface/matrix_utilities.pyc in size(constant)
     68         return INTERFACES[sp.csc_matrix].size(constant)
     69     else:
---> 70         raise TypeError("%s is not a valid type for a Constant value." % type(constant))
     71
     72 # Is the constant a column vector?

TypeError: <type 'NoneType'> is not a valid type for a Constant value.

power implementation details

I think I've got the power atom completely working, but I've got a few questions for ya, @SteveDiamond.

Since all the functions involving powers need to use something like the geometric mean for their representation, I moved that functionality out to a helper module power_tools. The main helper function there is gm_constrs, which forms the internal CVXPY constraints to represent the weighted geometric mean
t <= x_list[1]^p[1] * x_list[1]^p[1] * ... * x_list[n]^p[n],

where x_list is a list of cxvpy.Variable objects.

Both geo_mean.py and power.py use this helper function to form their graph implementation.

  1. I'm passing in a python list of cvxpy.Variables to gm_constrs. For geo_mean, I form
    x_list = [index.get_index(arg_objs[0], [], i, 0) for i in range(len(w))] before calling gm_constrs(t, x_list, w), since I'm expecting x to be a vector. For power.py I do something a little different, as I'm expecting only a 'single' (but elemwise) x. Is forming a list as I currently do it the best approach? Or should I be using some CVXPY construct?
  2. geo_mean and power each use the same helper function. But one is elemwise and the other isn't. Since geo_mean isn't elemwise, my original code used SOC to form the constraints. Since the helper function now supports both, I use SOC_Elemwise. Does that cost us anything in the geo_mean case? If it doesn't cost much, would it make sense to consolidate SOC and SOC_Elemwise into a single, general function? Put another way, is it always OK to just use SOC_Elemwise?

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.