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