Working with Mesh/FE Data in Mechanical

Options
Mike.Thompson
Mike.Thompson Member, Employee Posts: 283
First Anniversary First Comment 5 Likes Ansys Employee

Ever wanted to know how to get, sort, and write mesh information to a file? How about know what mesh nodes/elements are attached to geometry selections. All of this and more in the example attached.

#imports
import csv
from os.path import join
#Gather basic data
SM = ExtAPI.SelectionManager
CurrentSelection=SM.CurrentSelection
Model.Mesh.GenerateMesh()
SM.NewSelection(CurrentSelection)
Analysis=Model.Analyses[0]
MeshData = Analysis.MeshData
#Validate the selections
if not SM.CurrentSelection.SelectionType==SelectionTypeEnum.GeometryEntities:
print "Please select geometry entities. You do not have geometry selected."
if len(SM.CurrentSelection.Ids)==0:
print "Please select geometry entities. You have nothihng selected." #Collect node, body names and element ids
GeoIds = SM.CurrentSelection.Ids
NodeIds = set()
EntityNames = set()
for GeoId in GeoIds:
MeshRegion=MeshData.MeshRegionById(GeoId)
NodeIds.update(MeshRegion.NodeIds) ElemIds = MeshData.ElementIdsFromNodeIds(NodeIds) #report back information
print "Mesh Region for GeoIds: %s" % GeoIds
print "Bodies: %s" % EntityNames
print "Mesh Unit: %s" % MeshData.Unit
print "Nodes: %s" % len(NodeIds)
print "Elements: %s" % len(ElemIds) #Sort nodes by X, Y, Z
Nodes = [MeshData.NodeById(Id) for Id in NodeIds]
Nodes=sorted(Nodes , key=lambda N: [N.X, N.Y, N.Z])
Lines = []
Header = ["Node Id", "X", "Y", "Z"]
Lines.append(Header)
for N in Nodes:
NodeData=[N.Id, N.X, N.Y, N.Z]
Lines.append(NodeData) #Write output to file
CsvOutPath=join(Analysis.WorkingDir,"Mesh Data.csv")
print "Mesh Region Data written to: %s" % CsvOutPath
with open(CsvOutPath, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for Line in Lines:
writer.writerow(Line) Entity = ExtAPI.DataModel.GeoData.GeoEntityById(GeoId)
if hasattr(Entity, "Name"):
EntityNames.add(Entity.Name)
else:
EntityNames.add(Entity.Bodies[0].Name)