How to change values in GenericMatrix/Vector

Hi, I try to change the values of an assembled matrix with the following script :

#----------------------------
from fenics import *
import numpy as np

Create mesh and define function space

mesh = UnitSquareMesh(8, 8)
V = FunctionSpace(mesh, ‘P’, 1)

Define boundary condition

u_D = Constant(0.0)
def boundary(x, on_boundary):
return on_boundary

bc = DirichletBC(V, u_D, boundary)

Define variational problem

u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-6.0)
a = dot(grad(u), grad(v))dx + uvdx
L = f
v*dx

A = assemble(a,finalize_tensor=False)
#A = assemble(a)

block = np.ones((2,3), dtype=np.float_)
rows = np.array([4,7], dtype=np.uintc)
cols = np.array([0,3,5], dtype=np.uintc)
A.set(block,rows,cols)
#A.apply(‘add’)

#----------------------------

The issue is:

File “/Users/jf/Fenics/test1.py”, line 37, in
A.set(block,rows,cols)

RuntimeError:

*** ------------------------------------------------------------------------- ***
DOLFIN encountered an error. If you are not able to resolve this issue
*** using the information listed below, you can ask for help at


*** fenics-support@googlegroups.com


*** Remember to include the error message listed below and, if possible,
*** include a minimal running example to reproduce the error.


*** -------------------------------------------------------------------------
*** Error: Unable to successfully call PETSc function ‘MatSetValues’.
*** Reason: PETSc error code is: 63 (Argument out of range).
*** Where: This error was encountered inside /usr/local/miniconda/conda-bld/fenics-pkgs_1582286161246/work/dolfin/dolfin/la/PETScMatrix.cpp.
*** Process: 0


*** DOLFIN version: 2019.1.0
*** Git changeset:
*** -------------------------------------------------------------------------

I’ve also tried to use ‘finalize_tensor=True’ without success. Thanks you in advance for your help.

PETSc stores sparse matrices, so you cant set values in arbitrary posistions without modifiying the underlying sparsitypattern. You can convert the PETScMatrix to a dense matrix, see: Transform dolfinx assemble matrix to numpy array (Note that the syntax in dolfinx is slightly different from dolfin, But the idea is the same).

You can Also see the discussion Add Matrix to Assembled Matrix