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

How to dump a FEniCS matrix to an text file (Matrix Market format) ?

+2 votes

How to dump a FEniCS matrix to an text file (Matrix Market format) ?

For example, I would like to get the bilinear form a (as a matrix) from this https://github.com/hplgit/fenics-tutorial/blob/master/pub/python/vol1/ft01_poisson.py to be dumped to a text file (i-j-aij format: list all i,j indices and the associated value - Matrix Market format).

Tried this:
afile = File('a.raw')
afile << a
And this:
numpy.savetxt("a.txt", a)
... But does not work.

Franck

asked Jul 3, 2017 by fhoussen FEniCS Novice (140 points)
edited Jul 3, 2017 by fhoussen

2 Answers

+1 vote

You could try this instead:

numpy.savetxt("a.txt", assemble(a).array())

answered Jul 3, 2017 by meron FEniCS User (2,340 points)

@meron: thanks, this works ! Seems I can get values (aij) of the matrix a this way. For each value of the matrix a, I need the 3-uplet {i, j, aij}: how to get corresponding indices (i, j) for each aij ?

+3 votes

Hi, for large matrices you should have a look at the functionality of PETScViewer (via petsc4py). For smaller ones the following should do

from dolfin import *
from petsc4py import PETSc
from scipy.sparse import csr_matrix, coo_matrix
import numpy as np

mesh = UnitSquareMesh(10, 10)
V = FunctionSpace(mesh, 'CG', 1)
u, v = TrialFunction(V), TestFunction(V)
M = assemble(inner(u, v)*dx)

Mmat = as_backend_type(M).mat()
mat = coo_matrix(csr_matrix(Mmat.getValuesCSR()[::-1]))

np.savetxt('foo.mtx',
           np.c_[mat.row, mat.col, mat.data],
           fmt=['%d', '%d', '%.16f']) 
answered Jul 3, 2017 by MiroK FEniCS Expert (80,920 points)
...