How can I group the bodies under Geometry using the first component in their name?
In Mechanical, I’d like to create groups based on the first component of the body names under the ‘Geometry’ section. For instance, if I have a body named ‘Test_1/Solid,’ I want to create a group named ‘Test_1’ and move the body into that group. If the group already exists, I’d like to move the body into that existing group.
Best Answer
-
Assume a Tree structure like the one below:
Mechanical Scripting can be used for the purpose described:
foldersList = ExtAPI.DataModel.Project.Model.Geometry.GetChildren(DataModelObjectCategory.TreeGroupingFolder,True) foldersNameList = [item.Name for item in foldersList] bodiesList = ExtAPI.DataModel.Project.Model.Geometry.GetChildren(DataModelObjectCategory.Body,True) folders = {} if foldersList: for f in foldersList: folders[f.Name] = [] for b in bodiesList: components = b.Name.Split("\\") folder_name = components[0] if folder_name not in folders: folders[folder_name] = [b] else: folders[folder_name].append(b) for fol, bod in folders.items(): if bod and fol in foldersNameList: foldersList[foldersNameList.index(fol)].Ungroup() elif not bod: del(folders[fol]) for fol, bod in folders.items(): newFolder = ExtAPI.DataModel.Tree.Group(bod) newFolder.Name = fol
By using this code:
- If a folder does not exist, then one is created and the related bodies are grouped.
- If a folder already exists, then it's Ungrouped and Grouped again using the bodies with the relevant names. This is because a Move functionality does not exist.
0
Answers
-
We seem to be trying to solve the same problem. I have been able to create groups based on the name forward of the back splash but haven't been able to move the other geometries into the folder this is what I have so far:
# Get all bodies in the geometry bodies = ExtAPI.DataModel.Project.Model.Geometry.GetChildren(DataModelObjectCategory.Body, True) folders={} group_name = [] for item in bodies: #bodies = ExtAPI.DataModel.GetObjectsByName(body.Name) components = item.Name.split("\\") folder_name = components[0] if folder_name not in folders: folders[folder_name]=ExtAPI.DataModel.Tree.Group([item]) folders[folder_name].Name = folder_name print("folder made", folder_name) else: #ExtAPI.DataModel.Project.Model.Geometry. #existing_bodies = list(folders[folder_name].Children) #more_bodies = ExtAPI.DataModel.Tree.Group(existing_bodies +[item]) #more_bodies.Name = folder_name name=DataModel.GetObjectsByName(folder_name) folder_name=name.Add(item) #print("object name",name)
The code after the else statement is meant to move the other geometries but doesn't work yet. hope this helps. Please let me know if you manage to move the bodies into the pre made folders
0 -
Hi
The problem with the above code is that there is no Add method for a TreeGroup. Hence why my colleague did the workaround as we can not Move parts into an existing Group (see his explanation below).
Erik
0