How to serialize BaseMatrix?

Hi all,
NGSolve is a great tool, but I’m having trouble with some details.
I have set up a solver for my PDE, and calculated inverse of system matrix since I’m solving for many different “right-hand sides”. Now, for bigger meshes, the calculation of the inverse takes some time and I wanted to store the calculated inverse. However, it seems it’s not working like other ngs objects.

Here is the code:

ainv_filename = f'{self.results_dir}/A_inv.npz'
if os.path.exists(ainv_filename)
    self.log(f'Loading inverse of stiffness matrix...')
    # Load A_inv
    self.a_inv.mat = np.load(ainv_filename) # First self.a_inv should be initialized?
    
else:
    self.log(f'Calculating inverse of stiffness matrix...')
    self.a_inv = self.a.mat.Inverse(self.fes.FreeDofs())
    np.savez_compressed(ainv_filename, self.a_inv.mat)

The calculation is working without issues:

# Compute the solution (using precalculated inverse of stifness matrix A)
self.gfu.vec.data = self.a_inv * self.f.vec

To sum it up, how can I save BaseMatrix values to a file (NumPy or any other format)?

Thanks and I whish all of you a happy 2022!

Hi Stefan,

if you can use the in-house SparseCholesky (for symmetric positive definite matrices)

inv = mat.Inverse (inverse="sparsecholesky")

you have pickling support for it.

All the best for 2022 !

Joachim

Hi Joachim,
Thank you for replying so promptly!

I’ve tried this:

self.a_inv = self.a.mat.Inverse(self.fes.FreeDofs(), inverse="sparsecholesky")
pickle.dump(self.a_inv, open("a_inv.p", "wb"))

but it seems pickling is not supported in my version of NGSolve:

TypeError: cannot pickle 'ngsolve.la.SparseCholesky_d' object

Is this a recently added feature? I’ve installed NGSolve via Anaconda:

>>> import ngsolve as ngs
>>> ngs.__version__
'6.2.2008'

Hi,

Yes, this feature was added with the latest release (6.2.2105). It is available on anaconda:
https://anaconda.org/NGSolve/ngsolve

Best,
Matthias

Hi Matthiash,
I’ve updated ngsolve to the latest and now I can pickle SparseCholesky objects.
However, this comes with an excessive memory consumption and script/program crashes (Calculating inverse is already at about 27 GB, and pickling consumes the remaining 5GB on this machine).

Is there a way or advice on how to do it “manually”?