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

Create diagonal matrix with values at prescribed dofs

+1 vote

Hello,

I want to build a diagonal matrix which only contains values at nodal points corresponding to degrees of freedom at which particular Dirichlet BCs are prescribed.

I am trying with the following code :

from dolfin import *
from petsc4py import PETSc

#Functionspace and Dirichlet Bcs
V = VectorFunctionSpace(MyMesh, "Lagrange", 1)
bcs = DirichletBC(V, imposed_displacement, definedSubDomain)

# Extraction of dofs at which displacement is not prescribed (correspond to 0 in final matrix)
bc_keys = [set(bc.get_boundary_values().keys()) for bc in bcs]
bc_dofs  = list(sorted(reduce(lambda x, y: x.union(y), bc_keys)))
ownership_range = V.dofmap().ownership_range()
vol_dofs = [x for x in range(ownership_range[0], ownership_range[1]) if x not in bc_dofs]

isrow = PETSc.IS()
isrow.createGeneral(vol_dofs)

#create the matrix, Vec1 is a vector that contains 1 at the dogs with prescribed displacement
A = PETScMatrix()
Vec1, Vec2 = Mat.createVecs()
Vec1.set(1)
Vec1red = Vec1.getSubVector(isrow)
Vec1red.set(0)
A.setDiagonal(Vec1)

Since I am not familiar with PETSC, I wonder if the last part of my code does the job correctly, and if the matrix A is sparse ?

Many thanks in advance !

asked Feb 10, 2016 by Claire L FEniCS User (2,120 points)
...