This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

Export PETSc matrix and vector in file

+1 vote

Hello,

I am using FEniCS from a python interface, so I compute PETSc matrices and vectors that I need to export in external files. What is the correct syntax with petsc4py to get sparse matrices in ASCII format ?

I thought I cant use the option PETSC_VIEWER_ASCII_COMMON in PETSc's MatView, but I am missing the correct syntax in python.

thank you in advance for your help !

asked Aug 12, 2015 by Claire L FEniCS User (2,120 points)

1 Answer

+7 votes
 
Best answer

I found the answer to my own question ! I put this here, maybe it can help someone, if K is my matrix (<type 'petsc4py.PETSc.Mat'>):

myviewer = PETSc.Viewer().createASCII(
    "test.txt", format=PETSc.Viewer.Format.ASCII_COMMON,
    comm= PETSc.COMM_WORLD)
K.view(myviewer)

Claire

answered Aug 12, 2015 by Claire L FEniCS User (2,120 points)
selected Aug 13, 2015 by Claire L

Yes, your answer resolved my problem. You are so nice. Thanks a lot.

If you need arbitrary precision, you can export the matrix in binary :

from petsc4py import PETSc
viewer = PETSc.Viewer().createBinary('test.dat', 'w')
viewer(K)

and then read it back using : https://bitbucket.org/petsc/petsc4py/src/maint/demo/binary-io/matvecio.py

from scipy.io import mmwrite
import os
import PetscBinaryIO

io = PetscBinaryIO.PetscBinaryIO()
fh = open('test.dat')
objecttype = io.readObjectType(fh)
if objecttype == 'Mat':
    v = io.readMatSciPy(fh)
    mmwrite('test.mtx',v,precision=30)
    os.remove('test.dat')
    os.remove('test.dat.info')

Thank you for posting this. Very helpful.

One small comment. I tried the above and it didn't quite work for me. What did work was

viewer.view(K.mat())

instead of viewer(K). I just wanted to share this in case others might have a similar problem.

...