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

Pass a Mesh created in Python to code written in C++

0 votes

I would like to use the Python interface to select a mesh and element type, but once created I would like to access the mesh functions in C++. That is, I would like to send a FEniCS Python Mesh object to a shared C library defined with ctypes to perform the following operations in C++ (implemented in Python for reference) :

mesh    = UnitSquareMesh(2, 2)
Q       = FunctionSpace(mesh, "CG", 1)
element = Q.element()
dofmap  = Q.dofmap()

# find the cell with point :
x_pt       = Point([0.1, 0.2])
cell_id    = mesh.bounding_box_tree().compute_first_entity_collision(x_pt)
cell       = Cell(mesh, cell_id)
coord_dofs = cell.get_vertex_coordinates()       # local coordinates

# array for all basis functions of the cell :
phi = np.zeros(element.space_dimension(), dtype=float)

# array for values with derivatives of all 
# basis functions, 2 * element dim :
grad_phi = np.zeros(2*element.space_dimension(), dtype=float)

# compute basis function values :
element.evaluate_basis_all(phi, x, coord_dofs, cell.orientation())

# compute 1st order derivatives :
element.evaluate_basis_derivatives_all(1, grad_phi, x,  
                                       coord_dofs, cell.orientation())

# reshape such that rows are [d/dx, d/dy] :
grad_phi = grad_phi.reshape((-1, 2)) 

# get corresponding vertex indices, in dof indicies : 
vrt = dofmap.cell_dofs(cell.index())

return vrt, phi, grad_phi

I would like to use these basis values to compute some stuff on the nodes in C++, then return them back to the python implementation.

In particular, the Mesh I create in Python and send to the C++ implementation of the above operations will be not be distributed, and once the C++ code is finished, the resulting nodal values will go back to the Python code where several FEniCS Functions defined on a distributed Mesh will be updated.

I only need the above mesh and element functions, no form is defined or compiled together with UFL.

Does anyone have any suggestions for doing this?

My first thought is to copy the C++ code generated from compiling a .ufl file with ffc, but I am unsure how the relationship will work with a mesh created with Python! I need the user to be able to choose any mesh they want, and I need the simplicity of the Python interface.

asked May 15, 2017 by pf4d FEniCS User (2,970 points)
edited May 15, 2017 by pf4d

Yes, this is useful, thanks.

...