How to access neighbor nodes and elements (fenicsx)

I saw some old questions on how to access neighbors but they don’t seem working for fenicsx. I simply want to see the indices of adjacent vertices around one particular node. Is there a way to do it?

This is one example which does not work for if I change from dolfin to dolfinx (mainly because of vetices command whose equivalent I did not find for fenicsx) (found here: https://fenicsproject.org/qa/3145/how-to-get-a-node-neighbourhood/)

from dolfin import *
import numpy as np

mesh = UnitCubeMesh(4,4,4)

# Init vertex-edge connectivity
mesh.init(0,1)

for v in vertices(mesh):
    idx = v.index()
    neighborhood = [Edge(mesh, i).entities(0) for i in v.entities(1)]
    neighborhood = np.array(neighborhood).flatten()

    # Remove own index from neighborhood
    neighborhood = neighborhood[np.where(neighborhood != idx)[0]]

    print "Vertex %d neighborhood: " %idx, neighborhood

Thank you

Your question is quite vague, please follow the guidelines of Read before posting: How do I get my question answered?
Please also refer to the previous posts,

and explain what is not working with them for your application.

I added some explanations. I hope it is more clear now. Thank you

1 Like

The vertex indices can be access by calling

vertex_map = mesh.topology.index_map(0)
vertex_indices = np.arange(vertex_map.size_local + vertex_map.num_ghosts)
mesh.topology.create_connectivity(0, 1)
mesh.topology.create_connectivity(1, 0)
vertex_to_edge = mesh.topology.connectivity(0, 1)
edge_to_vertex = mesh.topology.connectivity(1, 0)
for vertex in vertex_indices:
      adjacent_edges = vertex_to_edge.links(vertex)
      for edge in adjacent_edges:
            adjacent_vertices = edge_to_vertex.links(edge)
            # Add these to neighbourhood
            #....

2 Likes

Thank you very much! It seems what I was looking for. But I had some errors. This modified code works for me:

domain = mesh.create_unit_square(MPI.COMM_WORLD, 10, 10)
vertex_map = domain.topology.index_map(0)
vertex_indices = np.arange(vertex_map.size_local + vertex_map.num_ghosts)
domain.topology.create_connectivity(0, 1)
domain.topology.create_connectivity(1, 0)
vertex_to_edge = domain.topology.connectivity(0, 1)
edge_to_vertex = domain.topology.connectivity(1, 0)

    for vertex in vertex_indices:
        adjacent_edges = vertex_to_edge.links(vertex)
        neighborhood = []
        for edge in adjacent_edges:
                adjacent_vertices = edge_to_vertex.links(edge)
                neighborhood.append(adjacent_vertices)
        print(neighborhood)
1 Like