# Export bifmesh model to file
#

#
# The final step of the bifmesh mesher creates two entries in the
# global pyFormex dict:
#  'CFD_lumen_model':  a volume FE model of hex8 elements
#  'inner_surface_mesh':  a surface FE mesh of guad4 elements
#
# This script shows how these meshes can be exported to a file
# in a format suitable for your simulation program
#

# These are for Abaqus, look at the source to reimplement in other
# format
from plugins.fe_abq import writeNodes,writeElems

M = named('CFD_lumen_model')     # the volume model
S = named('inner_surface_mesh')  # the surface mesh
S = Formex(S).toMesh()    # Fix a mistake in the current bifmesh plugin

def exportMesh(filename,mesh,eltype=None):
    """Export a finite element mesh.

    An FE mesh contains a nodal coordinates block (mesh.coords)
    and an element connectivity table (mesh.elems)
    """
    fil = open(filename,'w')
    writeNodes(fil,mesh.coords)
    if eltype is None:
        eltype = mesh.elems.eltype.name()
    writeElems(fil,mesh.elems,eltype)
    fil.close()

def exportModel(filename,model):
    """Export a finite element model.

    An FE model contains a single nodal coordinates block (model.coords)
    and a list of element connectivity tables (model.elems)
    """
    fil = open(filename,'w')
    writeNodes(fil,model.coords)
    [ writeElems(fil,e,e.eltype.name(),name="Eset%s"%i) for i,e in enumerate(model.elems) ]
    fil.close()

clear()
draw(M.meshes(),color=red)
draw(S)

exportMesh("surface.inp",S)   # write the surface mesh
exportModel("volume.inp",M)   # write the volume model

# End
