pythoncvxoptcvxpy

How to Access CVXPY Variables/Parameters After Declaration


I'd like to standardize a few cvxpy problems and use them in many places in my codebase. Here is a cleaned example:

from cvxpy import Variable, Parameter, Problem, Minimize

def problem_builder(n, ...)
    var = Variable(n)
    param = Parameter(n)

    costs = #Some complex convex function of var and param
    return Problem(Minimize(costs), constraints)

prob = problem_builder(4)
prob.var.value = [1,2,3,4]  #???
prob.parameters()[0] = [1,2,3,4]  #Ugly ???

I could create var and param outside the function and then pass them around with the problem but that seems awkward.

Can I access var and param somehow from prob? What are the best practices around using the same cvxpy Problem across multiple modules?


Solution

  • You can now access the parameters and variables as a dictionary using:

    param = cp.Parameter(name='paramname')
    problem.param_dict
    

    and

    var = cp.Variable(name='varname')
    problem.var_dict
    

    where the parameter/variable names are the keys of the dictionary