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
You must be logged in to post a comment.