Markus.london Markus.london - 3 months ago 44
Python Question

Dynamically generate constraints list in CVXPY

I am working on a minimum variance optimisation in python using CVXPY that takes in constraints in the form of

constraints = [
sum_entries(w) == 1,
w[0:5] >0.05,
w[1] > 0.05,
w[6] == 0,
sum_entries(w[country_mappings['France']]) == 0.39,
w >= 0,positive
w[country_mappings['France']] > 0.12
]


With w being in the form of

w = Variable(n)


To run this more efficiently I want to create my list of constraints dynamically based on a file where I will store my settings.

Reading in and creating a constraints list works fine, and by using

type(constraints)


it shows

<type 'list'>


But looking at the actual entries it contains

[EqConstraint(Expression(AFFINE, UNKNOWN, (1, 1)), Constant(CONSTANT,
POSITIVE, (1, 1))), LeqConstraint(Constant(CONSTANT, POSITIVE, (1,
1)), Expression(AFFINE, UNKNOWN, (5, 1))),
LeqConstraint(Constant(CONSTANT, POSITIVE, (1, 1)),
Expression(AFFINE, UNKNOWN, (1, 1))), EqConstraint(Expression(AFFINE,
UNKNOWN, (1, 1)), Constant(CONSTANT, ZERO, (1, 1))),
EqConstraint(Expression(AFFINE, UNKNOWN, (1, 1)), Constant(CONSTANT,
POSITIVE, (1, 1))), LeqConstraint(Constant(CONSTANT, ZERO, (1, 1)),
Variable(10, 1)), LeqConstraint(Constant(CONSTANT, POSITIVE, (1, 1)),
Expression(AFFINE, UNKNOWN, (3L, 1L)))]


whereas mine are in this format

['sum_entries(w) == 1',
'w[0:5] > 0.05',
'w[1] > 0.05',
'w[6] == 0',
'sum_entries(w[country_mappings['France']]) == 0.39',
'w >= 0',
'w[country_mappings['France']] > 0.12'
]


The code used to read in the data is

def read_in_config(filename):
with open(filename) as f:
content = f.read().splitlines()
return content


Does anyone know how this can be done ? The problem is getting w in the variable format of CVXPY before it can be used.

Answer

Ok so i have found a solution that works.

One can read in the constraints and concatenate a string to get s.th like

'constraints = [sum_entries(w) == 1,w[0:5] > 0.05,w[1] > 0.05,           
w[6] == 0, sum_entries(w[country_mappings['France']]) == 0.39, 
w >= 0, w[country_mappings['France']] > 0.12 ]'

Then just use

exec 'string from above'

I know exec is not the safest option to use but it works. W has to be defined in the code

w = Variable(n)
Comments