Running LP-solver in Postgres

Having reinstalled PostgreSQL with support for Python and pointing at my non-system python, it is time to test whether I can use the convex optimizer library I’ve installed in my Python 2.7 (pip install cvxopt).

Install PL/Python if not already installed

-- if not already installed. Doesn't hurt.
CREATE extension plpythonu;

Create a function that imports cvxopt:

CREATE OR REPLACE FUNCTION hello_cvxopt()
  RETURNS text
AS $$
  import cvxopt
  RETURN cvxopt.__doc__
$$ LANGUAGE plpythonu IMMUTABLE;

See if it works:

SELECT hello_cvxopt();
-- should return a documentation string

Try the linear programming example:

CREATE OR REPLACE FUNCTION cvxopt_lp_example()
  RETURNS FLOAT[]
AS $$
  FROM cvxopt import matrix, solvers
  A = matrix([ [-1.0, -1.0, 0.0, 1.0], [1.0, -1.0, -1.0, -2.0] ])
  b = matrix([ 1.0, -2.0, 0.0, 4.0 ])
  c = matrix([ 2.0, 1.0 ])
  solvers.options['show_progress'] = FALSE
  sol=solvers.lp(c,A,b)
  RETURN list(sol['x'])
$$ LANGUAGE plpythonu IMMUTABLE;
 
SELECT cvxopt_lp_example();
-- should return something like "{0.499999995215,1.49999999912}"

Try

Leave a Reply