Traversing the Mesh

The API for mesh data provides access to the underlying mesh in Mechanical.

An example Python function to traverse mesh data follows. Here, an object of type IMeshData is obtained from the object Analysis using the property MeshData. The object IMeshData is then used to access the list of element IDs with the property Elements. Using each of the element IDs in the returned list, the method ElementbyId is called to access the element data with IElement. This pattern is repeated for all of the nodes for each element. Finally, the coordinates of the nodes are queried.

import datetime
def traversemesh(analysis):
    now = datetime.datetime.now()
    f = open("C"\\MeshDump.txt",'w')    
    f.write("*.*.*.*.*.*.*.*\n")
    f.write(str(now)+"\n")
    # --- IMesh Interface
    # +++ Properties and Methods
    # +++ MeshRegion   
    # +++ Node   
    # +++ Element   
    # +++ Nodes   
    # +++ Elements   
    # +++ NumNodes   
    # +++ NumElements   
    mesh = analysis.MeshData
    elementids = mesh.ElementIds
    # --- IElement Interface
    # +++ Properties and Methods
    # +++ Id   
    # +++ Type   
    # +++ Nodes
    for elementid in elementids:
        element = mesh.ElementById(elementid)
        nodeids = element.NodeIds
        # --- INode Interface
        # +++ Properties and Methods
        # +++ Id   
        # +++ X   
        # +++ Y   
        # +++ Z   
        # +++ Elements
        for nodeid in nodeids:
            node = mesh.NodeById(nodeid)
            nodex = node.X
            nodey = node.Y
            nodez = node.Z
            try:
                f.write("      Element: "+elementid.ToString()+"  Node: "+nodeid.ToString()+", X = "+nodex.ToString()+", Y = "+nodey.ToString()+", Z = "+nodez.ToString()+"\n")
            except:
                continue
    f.close()
    return

Another example of traversing the mesh data follows. Only the elements of user-selected geometry entities are considered. The property CurrentSelection on the Selection Manager can be used to query the IDs of the selected geometry entities.

def elementcounter(analysis):
    with open("C:\\SelectedMeshEntities.txt”,'w') as f:
        geometry = analysis.GeoData
        smgr = ExtAPI.SelectionManager
        selectedids = smgr.CurrentSelection.Ids
        mesh = analysis.MeshData
        if selectedids.Count == 0:
           fwrite("Nothing Selected!")
           return
        for selectedid in selectedids:
            entity = geometry.GeoEntityById(selectedid)
            meshregion = mesh.MeshRegionById(selectedid)
            try:
                numelem = meshregion.ElementCount
                f.write("Entity of type: "+entity.Type.ToString()+
                                " contains "+numelem.ToString()+
                                " elements.")                
            except:
                f.write("The mesh is empty!")
        return