How do I get a NamedSelection by name in Mechanical?

Landon Mitchell Kanner
Landon Mitchell Kanner Member, Employee, GitHub-issue-creator Posts: 319
50 Answers 100 Comments Second Anniversary 25 Likes
✭✭✭✭
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, GitHub-issue-creator Posts: 319
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭
    edited December 2022 Answer ✓
    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 ✓

    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: 283
    Ancient Membership 100 Comments 100 Likes 25 Answers
    admin

    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, GitHub-issue-creator Posts: 319
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭

    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()]