How to add values to a Matrix?

In fenics 2018, I was able to do

A = assemble(...)
A.add(local_tensor, local_to_global_map, local_to_global_map)\

but with fenics 2019 I now get the error “AttributeError: ‘dolfin.cpp.la.Matrix’ object has no attribute ‘add’”

Here is the full example:

from __future__ import division
import numpy as np
import logging

from dolfin import (
    FunctionSpace,
    TestFunction,
    TrialFunction,
    assemble,
    assemble_local,
    cells,
    dx,
    grad,
    inner,
    UnitSquareMesh
)



mesh = UnitSquareMesh(8,8)

V = FunctionSpace(mesh, "Lagrange", 1)
u = TrialFunction(V)
v = TestFunction(V)
a = inner(grad(u), grad(v)) * dx
A = assemble(a)
A.zero()
dof_map = V.dofmap()
dof_coord = V.tabulate_dof_coordinates()

for cell in cells(mesh):
    local_to_global_map = dof_map.cell_dofs(cell.index())
    local_tensor = assemble_local(a, cell)

    A.add(local_tensor, local_to_global_map, local_to_global_map)
    A.apply("insert")

Thank you for your help.

You could try using the petsc4py API to add values to your matrix as suggested here: Add Matrix to Assembled Matrix - #2 by kamensky

from __future__ import division
import numpy as np
import logging

from dolfin import *
from petsc4py import PETSc

mesh = UnitSquareMesh(2,2)

V = FunctionSpace(mesh, "Lagrange", 1)
u = TrialFunction(V)
v = TestFunction(V)
a = inner(grad(u), grad(v)) * dx
A = assemble(a)

mat = as_backend_type(A).mat()
b1 = A.array() # just for a quick comparison (you shouldn't do this)
A.zero()

dof_map = V.dofmap()
dof_coord = V.tabulate_dof_coordinates()
for cell in cells(mesh):
    local_to_global_map = dof_map.cell_dofs(cell.index())
    local_tensor = assemble_local(a, cell)

    mat.setValuesLocal(local_to_global_map.tolist(), local_to_global_map.tolist(), local_tensor, PETSc.InsertMode.ADD)
A.apply("insert")
mat.assemble()

b2 = A.array()
np.testing.assert_allclose(b1,b2)  # True
1 Like