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

How to find the index of a cell from its midpoint?

+7 votes

I am trying to identify the index of a cell given its midpoint. In order to do this, I used the method detailed in the source at the end of this post (which didn't work as I had hoped). I observe that trying to obtain the closest cell to the midpoint of the cell returns -1, and that obtaining the closest cell to a point slightly displaced from this midpoint returns the actual index of the cell (0 in this case).

My questions are:

  • Why does the first example return '-1'?
  • Is there a more elegant way of doing this?

I am using dolfin version 1.3.0.

import dolfin as df

# Create square mesh with two cells.
mesh = df.UnitSquareMesh(1, 1)

# Obtain the midpoint of the first cell with index zero.
midPoint = df.cells(mesh).next().midpoint()

# Obtain the index of the cell closest to the midpoint (should be zero)
index, distance = mesh.bounding_box_tree().compute_closest_entity(midPoint)

# Print result (-1).
print("Sampling at {} returns index {}".format(midPoint.str(), index))

# Obtain the index of the cell closest to a point very close to the midpoint
# (should be zero)
offPoint = midPoint + df.Point(1e-6, 0, 0)
index, distance = mesh.bounding_box_tree().compute_closest_entity(offPoint)

# Print result (0).
print("Sampling at {} returns index {}".format(offPoint.str(), index))

Upon running this code, I obtain the following result:

Building point search tree to accelerate distance queries.
Computed bounding box tree with 3 nodes for 2 points.
Sampling at <Point x = 0.666667 y = 0.333333 z = 0> returns index -1
Sampling at <Point x = 0.666668 y = 0.333333 z = 0> returns index 0
asked Jan 23, 2014 by MVousden FEniCS Novice (260 points)

1 Answer

+3 votes
 
Best answer

Use

mesh.bounding_box_tree().compute_first_entity_collision(midPoint)
answered Jan 23, 2014 by monien FEniCS Novice (790 points)
selected Jan 24, 2014 by MVousden
...