cvxgrp / cvxpygen

Code generation with CVXPY
Apache License 2.0
127 stars 17 forks source link

generate code failed TypeError: 'NoneType' object is not subscriptable #20

Closed luong2710 closed 1 year ago

luong2710 commented 1 year ago

Hello everyone, this is my first time asking for help here. please kindly tell me if the problem is not clear enough. I am trying to test cvxpygen for simple Markowitz optimisation problem. Objective is to minimise portfolio variance with constraint on minimum return.

function to get portfolio return

ret = (np.array(expected_return) @ w )* annual # portfolio expected return as weighted sum of component expected return

function to get portfolio variance

port_var = cp.quad_form(w, cov) * annual #portfolio variance constraints = [cp.sum(w) == 1, # sum of weights = 1 w <= 1, # weights <= 1 ret >= ret_target_min # min return]

define problems

prob = cp.Problem(cp.Minimize(port_var), constraints)

Using CVXPY I was able to get result result_opt = prob.solve(verbose=False, eps_abs=1e-08)

trying with CVXPYGen

from cvxpygen import cpg cpg.generate_code(prob, "nonneg_LS") from nonneg_LS.cpg_solver import cpg_solve prob.register_solve("cpg",cpg_solve) val= prob.solve()

my code failed right at generating problem stage, with following error: ./lib/python3.11/site-packages/cvxpygen/cpg.py", line 252, in generate_code user_p_flat_usp = user_p_flat[user_p_sparsity_mask]


TypeError: 'NoneType' object is not subscriptable
apparently user_p_flat is None 

Any help is much appreciated. 
Many thanks,
maxschaller commented 1 year ago

Hi @luong2710! Thanks for reaching out. It looks like you have not defined your parameters as Parameter. Cvxpygen is built around the concept of Disciplined Parametrized Programming, or DPP. You might want to have a look. Also, cp.quad_form is not allowed with DPP. You might write sth like cp.sum_squares(R@w), where R is some root of cov, e.g., its Cholesky root (transposed). Please also have a look at this detailed portfolio optimization example with cvxpygen. You can simplify it to arrive at your problem.

Also, could you please provide a minimal example of your issue, i.e., one piece of code that one can run to reproduce the error? This is best practice.

maxschaller commented 1 year ago

Feel free to re-open in case the error persists.