How to change the values of a cp.Parameter in the c code?
AlessandroZavoli opened this issue · comments
As the question title suggests, I would like to reuse the same code to solve a family of problems, changing only the values of a few parameters defined via cp.Parameter
. Do you think this could be possible?
I looked at the MPC example, where x0, A, B are parameters, but I don't know what to do to call the c code with updated values (e.g. updated initial conditions of the MPC)
@AlessandroZavoli that's totally possible. Let's have a look at the main c file generated for the default nonnegative least squares example, nonneg_LS/c/src/cpg_example.c
. It includes all necessary headers, updates parameter values, solves the problem instance, and prints the results.
/*
Auto-generated by CVXPYgen on April 02, 2024 at 15:24:11.
Content: Example program for updating parameters, solving, and inspecting the result.
*/
#include <stdio.h>
#include "cpg_workspace.h"
#include "cpg_solve.h"
static int i;
int main(int argc, char *argv[]){
// Update first entry of every user-defined parameter
cpg_update_A(0, 1.76405234596766402611);
cpg_update_b(0, 2.24089319920145779719);
// Solve the problem instance
cpg_solve();
// Print objective function value
printf("obj = %f\n", CPG_Result.info->obj_val);
// Print primal solution
for(i=0; i<2; i++) {
printf("x[%d] = %f\n", i, CPG_Result.prim->x[i]);
}
// Print dual solution
for(i=0; i<2; i++) {
printf("d0[%d] = %f\n", i, CPG_Result.dual->d0[i]);
}
return 0;
}
In general, you can update your parameter value, say the (i, j)
-th entry of matrix M
(dimension m
by n
) to value 3.0
, by calling
cpg_update_M(i + j * m, 3.0);
Note that matrices are stored in column-major format. If your parameter is a vector or scalar, the first argument to the update function is just the vector index or 0.
When you are using the Python interface and M
is a cp.Parameter((m, n))
, just write
M.value[i, j] = 3.0
Please let me know if you have any further questions.