osqp-eigen icon indicating copy to clipboard operation
osqp-eigen copied to clipboard

Ownership of bounds, gradient, Hessian, and constraint matrix

Open joaospinto opened this issue 6 years ago • 3 comments
trafficstars

When writing a class that encapsulates the use of this library in my codebase, I noticed that I had to store all matrices/vectors as private variables, otherwise some of the pointers would become stale (your library does not seem to be taking ownership of those matrices/vectors). Is this intended? Took me a while to figure this out.

Also, the way you pass Eigen objects around seems a bit unorthodox. You may want to read this.

joaospinto avatar Jan 18 '19 18:01 joaospinto

Hi @joaospinto thanks for using osqp-eigen

When writing a class that encapsulates the use of this library in my codebase, I noticed that I had to store all matrices/vectors as private variables, otherwise some of the pointers would become stale (your library does not seem to be taking ownership of those matrices/vectors). Is this intended?

The library wants to be a simple wrapper to osqp and so we try to reduce the memory allocation (matrices and vectors). However in the initialization phase (e.g. here) the Hessian matrix is saved inside the data structure of osqp.

https://github.com/robotology/osqp-eigen/blob/7109a226f0cc6dd7d01eb912561e9a0e9eb1d57a/include/OsqpEigen/Data.tpp#L35

and here the memory is allocated and the Hessian matrix is copied https://github.com/robotology/osqp-eigen/blob/7109a226f0cc6dd7d01eb912561e9a0e9eb1d57a/include/OsqpEigen/SparseMatrixHelper.tpp#L34-L53 This is required by osqp itself. Indeed osqp wants a pointer to a csc struct when the first optimization problem is created.

On the other hand, when you set the gradient no memory allocation is performed and a pointer to the vector is passed to the osqp library https://github.com/robotology/osqp-eigen/blob/7109a226f0cc6dd7d01eb912561e9a0e9eb1d57a/include/OsqpEigen/Data.tpp#L44-L55

So in simple terms:

  • you do not need to save the matrices as private variables (dynamic memory allocation is performed by the csc_spalloc function)
  • you need to save the vectors as private variables because no memory allocation is performed.

On the light of this, it would be nice to have a simple example where I can try to replicate your problem.

GiulioRomualdi avatar Jan 19 '19 00:01 GiulioRomualdi

@GiulioRomualdi That makes sense. I actually only had issues with the bound vectors; I somehow assumed that the same issue would exist with the matrices, so I made sure they would not go out of scope as well, but had not double checked. Thanks for clarifying! Also, thanks for writing this library, you probably saved me a couple of days of work.

joaospinto avatar Jan 21 '19 23:01 joaospinto

cc @miladShafiee

GiulioRomualdi avatar Apr 16 '19 16:04 GiulioRomualdi