This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

Find elements in a given neighborhood of an element

0 votes

Hi,
Given a radius r and an element e, I would like to find all the elements whose center-to-center distance from e is smaller than r.
I would like to do this for all the elements of the mesh. What I would like to do is similar to the following example, which, however, implies a double loop on all the cells and is not efficient for large numbers of elements.

from dolfin import *
import dolfin as df

mesh = UnitSquareMesh(20,20)
radius = 0.05

k=0
for cell1 in cells(mesh):
    center1 = cell1.midpoint()
    j=0
    for cell2 in cells(mesh):
        center2 = cell2.midpoint()
        if center1.distance(center2) < radius:
              print ('element %i is in neighborhood of element %i'% (j,k))
        j=j+1
    k=k+1

Is there a better way to “identify” which elements are inside a neighborhood of a given radius from the center of a given element?
I have already thought about exploiting the numeration of the elements, but I was wondering whether I have to do it manually or there is a command I could use.
Thank you!

asked Jul 12, 2017 by Fr389 FEniCS Novice (120 points)

If you give a bit more context, people could speculate on avoiding the computation in the first place.

Thank you for your comment. The context may be quite complex, actually... I am working on topology optimization on FEniCS and I am reading a paper regarding a local volume constraint (the paper can be found at https://arxiv.org/pdf/1608.04366.pdf ).
Briefly, the authors consider a neighborhood of radius r around each element. Then, they impose a volume constraint to each of these neighborhoods. Finally, the local constraints are aggregated.

I would like to implement these local constraints. So, I am not sure the computation I described can be avoided, unless changing the formulation (e.g. using something similar to a filter). I will think about this. Thank you again.

...