How do I get a NamedSelection by name in Mechanical?

Options
Landon Mitchell Kanner
Landon Mitchell Kanner Member, Employee Posts: 221
First Answer First Comment 5 Likes First Anniversary
edited June 2023 in Structures

I would like a script that takes the name of a NamedSelection as input and returns the NamedSelection

Best Answers

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee Posts: 221
    First Answer First Comment 5 Likes First Anniversary
    edited December 2022 Answer ✓
    Options
    def GetNSbyName(name,AcceptPartial = False):
    	    try:
    	        NSs = ExtAPI.DataModel.Project.Model.NamedSelections.Children
    	    except:
    	        return None
    	    for ns in NSs:
    	        if ns.Name.ToLower() == name.ToLower():
    	            return ns
    	        if AcceptPartial and  (name.ToLower() in ns.Name.ToLower()):
    	            return ns
    	    ExtAPI.Log.WriteWarning("Named Selection not found: "+str(name))
    	    return None
    


  • Pavel
    Pavel Member Posts: 9
    5 Likes Name Dropper First Answer Photogenic
    edited December 2022 Answer ✓
    Options

    This function:

    def ns_by_name(ns_name):
        return [o for o in DataModel.GetObjectsByType(DataModelObjectCategory.NamedSelection) if o.Name == ns_name]
    
    • case sensitive
    • Returns list matching any named selections matching the name, if you want the first one just add [0] at the end ns_by_name('name')[0] or have it return 1st member altogether. Returning list is best because no checking is needed and it's simple.

Answers

  • James Derrick
    James Derrick Administrator, Employee Posts: 248
    First Anniversary Solution Developer Community of Practice Member Ansys Employee 5 Up Votes
    admin
    Options

    Hi @Landon Mitchell Kanner Can you include the code in your post? It is best practice to avoid just linking to external resources because the answer is quite fragile and depends on the link's persistence, as well as user access. For example, if that GitHub repo goes private next week, then people won't be able to check out GetNSbyName.

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee Posts: 221
    First Answer First Comment 5 Likes First Anniversary
    Options

    Combining both answers (untested):

    def GetNSbyName(name,AcceptPartial = False):
      NSs = DataModel.GetObjectsByType(DataModelObjectCategory.NamedSelection)
      if AcceptPartial:
        return [ns for ns in NSs if name.ToLower() in ns.Name.ToLower()]
      else:
        return [ns for ns in NSs if ns.Name.ToLower() == name.ToLower()]