[petsc-users] Understanding the structure of SNES matrix-free jacobian

Daniel PINO MUNOZ daniel.pino_munoz at minesparis.psl.eu
Sat Apr 25 13:05:31 CDT 2026


Dear all,

I am struggling to understand how I should set up a SNES solver where the Newton Raphson iterations can be computed using a matrix-free method.

This is what I would like to do :


  *
I want to solve F(x) = 0
  *
The Newton Raphson iteration J(x) dx = -F(x) should be computed using a matrix-free method
  *
Then classic Newton Raphson update x = x + dx

The first question I would have is whether this can be done using SNES ?
If not, I can always this done using a classic matrix-free product and implementing the Newton Raphson iterations myself.

What I have tried, without success is the following :

 SNESCreate(PETSC_COMM_WORLD, &snes);
  SNESSetApplicationContext(snes, (void *)(&userCtx));
  SNESSetFunction(snes, r, FormFunction1, (void *)&userCtx);
  MatCreateSNESMF(snes, &J);

  MatShellSetOperation(J, MATOP_MULT, (void(*)(void))mult);
  MatSetFromOptions(J);
  MatSetUp(J);
  SNESSetJacobian(snes, J, J, MFJacobianVectorProduct, (void *)&userCtx);
 SNESSetFromOptions(snes);
  SNESSetUseMatrixFree(snes, PETSC_FALSE, PETSC_TRUE);
...


  *
The function 'mult' implements the matrix-free multiplication, say A y = b
     *
But how do I get the point at which A is computed ? Since A is supposed to be the Jacobian it is something like A(x)
     *
To try to do that, I added a method 'MFJacobianVectorProduct' where I store in the SNES Application Context the point 'x' at which the jacobian should be computed, then in the 'mult' function I try to get the context of 'J' and use it to compute the matrix-free product

I am probably misunderstanding something since the code runs, but the Jacobian is simply computed using finite differences and my "matrix-free" Jacobian product implementation is not called.

If you have an example, I would be happy to look into it.

Thank you in advance,

  Daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/petsc-users/attachments/20260425/f1019df9/attachment.html>


More information about the petsc-users mailing list