Access matrix in dolfinx

How can i access the matrix entries of a FEM system matrix?
I found several related questions here, but they were all based on the legacy dolfin version.

My goal is to compute the condition number of the matrix, which I intend to do using numpy.

I tried something like A.array(), but this is only implemented for the solution/function, not for a matrix.

Moroever: If accessing a matrix that was returned from assemble_matrix_block differes from accessing a matrix from simpler matrices, I am interested in both.

This depends on implementation of a matrix you’re using. For example DOLFINx’s in built type dolfinx.la — DOLFINx 0.10.0.0 documentation and PETSc’s Mat petsc4py.PETSc.Mat — Python 3.22.2 documentation.

thank you.

for reference, i will post here a small code example, that converts a PETSc.Mat matrix to a numpy array.

import ufl
import numpy as np
from mpi4py import MPI
from dolfinx import fem, mesh
from dolfinx.fem import locate_dofs_topological, dirichletbc
from dolfinx.fem.petsc import assemble_matrix
from dolfinx.mesh import locate_entities_boundary

def petsc2array(petsc_mat):
    rows, cols = petsc_mat.getSize()
    dense_array = petsc_mat.getValues(range(rows), range(cols))
    return dense_array

# mesh and BC
domain = mesh.create_unit_square(MPI.COMM_WORLD, 3,3)
V = fem.functionspace(domain, ("Lagrange", 1))
u_n, uh = fem.Function(V), fem.Function(V)
facets = locate_entities_boundary(domain, dim=1,
                                marker=lambda x: np.logical_or.reduce((
                                    np.isclose(x[0], 0.0),
                                    np.isclose(x[0], 1.0),
                                    np.isclose(x[1], 0.0),
                                    np.isclose(x[1], 1.0))))
dofsV = locate_dofs_topological(V, entity_dim=1, entities=facets)
bc = dirichletbc(0.0, dofsV, V)

# matrix
u, v = ufl.TrialFunction(V), ufl.TestFunction(V)
a = ( ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx)
bilinear_form = fem.form(a)
A = assemble_matrix(bilinear_form, bcs=[bc])
A.assemble()

# print
np.set_printoptions(threshold=np.inf, precision=3, suppress=True, linewidth=10000)
A_arr = petsc2array(A)
print(A_arr)

1 Like