Create Material Assignment from Body Materials

Goal

The following script example creates a Material Assignment object, specifies object properties, and assigns a material to all bodies of your model.

Code

# Clears generated mesh
# Single line script to be used to create a user button and possibly a keyboard shortcut

# Create dictionary with materials and corresponding bodies
bodies = DataModel.GetObjectsByType(DataModelObjectCategory.Body)
listMaterials={}
for body in bodies:
    if body.Material in listMaterials.keys():
        listMaterials[body.Material].append(body.ObjectId)             
    else:
        listMaterials[body.Material]=[body.ObjectId]


# Now create (or update) material assignments
matFolder=ExtAPI.DataModel.GetObjectsByType(Ansys.ACT.Automation.Mechanical.Materials)[0]
# first find existing material assignment
existingMatAssg={}
for ch in matFolder.Children:
    if ch.GetType()==Ansys.ACT.Automation.Mechanical.MaterialAssignment:
        if ch.Material in existingMatAssg.keys():
            existingMatAssg[ch.Material].append(ch.ObjectId)             
        else:
            existingMatAssg[ch.Material]=[ch.ObjectId]

# Now loop of body materials and create or update assignment
for mat in listMaterials.keys():
    # Select corresponding bodies
    ExtAPI.SelectionManager.ClearSelection()
    geoBodyList=[]
    temp_sel= ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
    for item in listMaterials[mat]:
        geoBodyList.append(ExtAPI.DataModel.GetObjectById(item).GetGeoBody().Id)
    temp_sel.Ids=geoBodyList
    ExtAPI.SelectionManager.NewSelection(temp_sel)
    if mat in existingMatAssg.keys(): # assignment already exist, update scoping
        assg=ExtAPI.DataModel.GetObjectById(existingMatAssg[mat][0])
        assg.Location=temp_sel
    else: # create new assignment
        newAssg=matFolder.AddMaterialAssignment()
        newAssg.Material=mat
        newAssg.Location=temp_sel