How to create lists of cell neighbours?

Hi,
Is it possible to create a list for each cell, which contains the cells that share an edge with the original cell? Thus, to list the neighbours for each cell?

It seems to be answered here, but I cannot make it work, https://fenicsproject.org/qa/3843/cell-neighbours/index.html

Thanks!

Instead of using the filter function, you can simply unwrap it in multiple loops:

from dolfin import *

mesh = UnitSquareMesh(2, 2)

# Init facet-cell connectivity
tdim = mesh.topology().dim()
mesh.init(tdim - 1, tdim)

# For every cell, build a list of cells that are connected to its facets
# but are not the iterated cell
cell_neighbours = {}
for cell in cells(mesh):
    index = cell.index()
    cell_neighbours[index] = []
    for facet in facets(cell):
        facet_cells = facet.entities(tdim)
        for facet_cell in facet_cells:
            if (index!=facet_cell):
                cell_neighbours[index].append(facet_cell)
print(cell_neighbours)
4 Likes

filter returns a filter object. You can either pass it to a list constructor as

cell_neighbors = {cell.index(): sum(( list(filter(lambda ci: ci != cell.index(),
                                            facet.entities(tdim)))
                                    for facet in facets(cell)), [])
                for cell in cells(mesh)}

or use a much more discernible approach as @dokken suggested above.

3 Likes

Thanks a lot for your help!