Assign values to a Function where a MeshFunction has been marked

7 weeks ago by
I am trying to assign a value to all cells marked in a MeshFunction. A very similar question has been asked and answered previously here:

The suggested solution does not appear to work in version 2017.2.0 anymore. If I run the MWE from the suggested solution

from fenics import *

mesh = UnitSquareMesh(20, 20)
V = FunctionSpace(mesh, 'CG', 2)

cell_f = CellFunction('size_t', mesh, 0)
AutoSubDomain(lambda x: x[0] > x[1]).mark(cell_f, 1)
domain_cells = SubsetIterator(cell_f, 1)

dofmap = V.dofmap()
# Dofs in domain
dofs = sum((dofmap.cell_dofs(cell.index()).tolist()
           for cell in domain_cells), [])
# Get unique dofs in local numbering that the process sees. Some might not be owned
dofs = set(dofs)
# Where in global vector are dofs owned by the process
my_first, my_last = dofmap.ownership_range()
# Keep only owned ones, ie those whose global index is in ownership range
dofs = filter(lambda dof: my_first <= dofmap.local_to_global_index(dof) < my_last,
# Assign
f = Function(V)
f.vector()[dofs] = 1

interactive() ​

I get

Iterating over subset, found 361 entities out of 800.
TypeError                                 Traceback (most recent call last)
<ipython-input-1-bac6a485bd2e> in <module>()
     21 # Assign
     22 f = Function(V)
---> 23 f.vector()[dofs] = 1
     25 plot(f)

/usr/lib/python3/dist-packages/dolfin/cpp/ in __setitem__(self, indices, values)
   1498     # Check indices
-> 1499             indices = self._check_indices(indices)
   1501     # Check passed values and convert scalar to ndarray of that value

/usr/lib/python3/dist-packages/dolfin/cpp/ in _check_indices(self, indices)
   1422     # Only accpect list and ndarrays
   1423         if not isinstance(indices, (ndarray, list)):
-> 1424             raise TypeError("expected an int or a list or numpy array of "\
   1425                             "integers or a boolean numpy array as indices.")

TypeError: expected an int or a list or numpy array of integers or a boolean numpy array as indices.​

How can I adjust the code to make it work in 2017.2.0?
Community: FEniCS Project

1 Answer

7 weeks ago by
It turns out that this is an issue between Python 2 and 3 rather than Fenics. In Python 2 the filter() function returned the list while in Python 3 filter() returns an Iterator. So adding
dofs = list(dofs)​

fixes it.

Please login to add an answer/comment or follow this question.

Similar posts:
Search »