General Mechanical

General Mechanical

Topics related to Mechanical Enterprise, Motion, Additive Print and more.

Access to Worksheet Named Selection via Python console

    • ciema
      Subscriber

      Hello,

      it is very hard to find any materials how to achieve access and use Python to create Named Selections via Python Console in ANSYS Workbench Mechanical. Can anyone help me and tell how to make impact on creation named selection via Python Scripting and console button? Any tutorials, documetns, pdfs connected with Named Selection creation via Python scripting would be much appreciated!

    • Naresh Patre
      Ansys Employee

      Please check out below discussion on assigning items to Named Selection:
      ACT Script: Assign items to a named selection ÔÇö Ansys Learning Forum
      I would also suggest checking out the Scripting Examples section from theMechanical Application 2021 R2help document:
      Scripting Examples (ansys.com)
    • Erik Kostson
      Ansys Employee


      if you mean how to access the worksheet of the named selection as shown below , then this sample code will provide some clues on how to do it on releases after 2020 R2:


      sample code:
      ns = Model.AddNamedSelection()
      ns.ScopingMethod=GeometryDefineByType.Worksheet
      Criteria = ns.GenerationCriteria
      Criteria.Add(None)
      Criteria[0].EntityType = SelectionType.GeoVertex
      Criteria[0].Criterion = SelectionCriterionType.LocationY
      Criteria[0].Operator = SelectionOperatorType.Equal
      Criteria[0].Value = Quantity('400 [mm]')
      Criteria.Add(None)
      Criteria[1].Action=SelectionActionType.Filter
      Criteria[1].EntityType = SelectionType.GeoVertex
      Criteria[1].Criterion = SelectionCriterionType.LocationX
      Criteria[1].Operator = SelectionOperatorType.Equal
      Criteria[1].Value = Quantity('30 [mm]')
      ns.Generate
    • ciema
      Subscriber
      Thank you !
    • edutenorio
      Subscriber

      Thanks for the sample code, I've been searching for something like this for a long time. I listed below the possible enumerations for the parameters action, entity type, criterion and operator, hope it helps:

       

      # Action
      # ------
      # enum SelectionActionType, values:
      #   Add (4),
      #   Convert (5),
      #   Filter (1),
      #   Invert (3),
      #   Remove (2)

      # Entity Type
      # -----------
      # enum SelectionType, values:
      #   GeoBody (1),
      #   GeoEdge (3),
      #   GeoFace (2),
      #   GeoVertex (4),
      #   MeshEdge (8),
      #   MeshElement (6),
      #   MeshElementFace (9),
      #   MeshFace (7),
      #   MeshNode (5)

      # Criterion
      # ---------
      # enum SelectionCriterionType, values:
      #   AllEdges (35),
      #   AllNodes (18),
      #   AllVertices (33),
      #   AnalysisPly (27),
      #   AnyEdge (34),
      #   AnyNode (17),
      #   AnyVertex (32),
      #   Area (26),
      #   AspectRatio (19),
      #   CADAttribute (7),
      #   CrossSection (42),
      #   Distance (14),
      #   EdgeConnections (31),
      #   ElementConnections (30),
      #   ElementNumber (15),
      #   ElementQuality (16),
      #   FaceConnections (6),
      #   ImportedTrace (36),
      #   JacobianRatio (20),
      #   JacobianRatioCornerNodes (40),
      #   JacobianRatioGaussPoints (41),
      #   LocationX (3),
      #   LocationY (4),
      #   LocationZ (5),
      #   Material (11),
      #   MaximumCornerAngle (38),
      #   MinimumLength (39),
      #   Name (29),
      #   NamedSelection (9),
      #   NodeNumber (10),
      #   NormalTo (43),
      #   OffsetMode (13),
      #   OrthogonalQuality (24),
      #   ParallelDeviation (22),
      #   Radius (8),
      #   SharedAcrossBodies (37),
      #   SharedAcrossParts (28),
      #   Size (1),
      #   Skewness (23),
      #   Thickness (12),
      #   Type (2),
      #   Unknown (0),
      #   Volume (25),
      #   WarpingFactor (21)

      # Operator
      # --------
      # enum SelectionOperatorType, values:
      #   Contains (13),
      #   Equal (1),
      #   GreaterThan (5),
      #   GreaterThanOrEqual (6),
      #   Largest (10),
      #   LessThan (3),
      #   LessThanOrEqual (4),
      #   No (12),
      #   NotEqual (2),
      #   RangeExclude (7),
      #   RangeInclude (8),
      #   Smallest (9),
      #   Unknown (0),
      #   Yes (11)

       

    • edutenorio
      Subscriber

      My objective was to find a way to transfer Named Selections from a model to another model, never managed to find it. Thanks to Erik code I could finally create something that works, which I share below and hope it's useful for someone.

      FILE_NAME = 'named_sel_export.py'

      model = ExtAPI.DataModel.Project.Model

      object_lists = {
          # 'Ansys.ACT.Automation.Mechanical.AnalysisPly': 'model.???',
          # 'Ansys.ACT.Automation.Mechanical.CrossSection': 'model.???',
          'Ansys.ACT.Automation.Mechanical.Material': 'model.Materials.Children',
          'Ansys.ACT.Automation.Mechanical.NamedSelection': 'model.NamedSelections.Children',
          'Ansys.ACT.Automation.Mechanical.CoordinateSystem': 'model.CoordinateSystems.Children',
      }

      with open(FILE_NAME, 'w') as f:
          lines = []
          lines.append("def get_entity_by_name(entity_list, name):")
          lines.append("    for x in entity_list:")
          lines.append("        if x.Name == name:")
          lines.append("            return x")
          lines.append("    return None")
          lines.append("")
          lines.append("model = ExtAPI.DataModel.Project.Model")
          lines.append("")
          for ns in model.NamedSelections.Children:
              lines.append("ns = Model.AddNamedSelection()")
              lines.append("ns.Name = '{}'".format(ns.Name))
              lines.append("ns.ScopingMethod = GeometryDefineByType.{}".format(ns.ScopingMethod))
              if ns.ScopingMethod == GeometryDefineByType.Worksheet:
                  lines.append("criteria = ns.GenerationCriteria")
                  for i, criteria in enumerate(ns.GenerationCriteria):
                      lines.append("criteria.Add(None)")
                      lines.append("criteria[{}].Active = {}".format(i, criteria.Active))
                      lines.append("criteria[{}].Action = SelectionActionType.{}".format(i, criteria.Action))
                      lines.append("criteria[{}].EntityType = SelectionType.{}".format(i, criteria.EntityType))
                      if criteria.Action in [SelectionActionType.Invert, SelectionActionType.Convert]:
                          # No further parameters necessary for Invert or Convert
                          continue
                      lines.append("criteria[{}].Criterion = SelectionCriterionType.{}".format(i, criteria.Criterion))
                      lines.append("criteria[{}].Operator = SelectionOperatorType.{}".format(i, criteria.Operator))
                      if criteria.Operator in [SelectionOperatorType.RangeExclude, SelectionOperatorType.RangeInclude]:
                          # Define lower and upper bound only, do not define value
                          if criteria.IsUnitless():
                              lines.append("criteria[{}].LowerBound = {}".format(i, criteria.LowerBound))
                              lines.append("criteria[{}].UpperBound = {}".format(i, criteria.UpperBound))
                          else:
                              lines.append("criteria[{}].LowerBound = Quantity('{}')".format(i, criteria.LowerBound))
                              lines.append("criteria[{}].UpperBound = Quantity('{}')".format(i, criteria.UpperBound))
                      else:
                          # Define value, do not define lower and upper bound
                          if criteria.IsString():
                              lines.append("criteria[{}].Value = '{}'".format(i, criteria.Value))
                          elif criteria.IsObject():
                              lines.append("criteria[{}].Value = get_entity_by_name({}, '{}')".format(i, object_lists[str(criteria.Value.GetType())], criteria.Value.Name))
                          elif criteria.IsUnitless():
                              lines.append("criteria[{}].Value = {}".format(i, criteria.Value))
                          else:
                              lines.append("criteria[{}].Value = Quantity('{}')".format(i, criteria.Value))
                      if criteria.CoordinateSystem.CoordinateSystemID != 0:
                          lines.append("criteria[{}].CoordinateSystem = get_entity_by_name(model.CoordinateSystems.Children, '{}')".format(i, criteria.CoordinateSystem.Name))
                      # lines.append("# criteria[{}].IsObject() == {}".format(i, criteria.IsObject()))
                      # lines.append("# criteria[{}].IsString() == {}".format(i, criteria.IsString()))
                      # lines.append("# criteria[{}].IsUnitless() == {}".format(i, criteria.IsUnitless()))
                  lines.append("ns.ToleranceType = ToleranceType.Manual")
                  lines.append("ns.ZeroTolerance = 1E-3")
                  lines.append("ns.RelativeTolerance = 1E-3")
                  lines.append("ns.Generate()")
              lines.append("")
          f.write('\n'.join(lines))
          f.close()

Viewing 5 reply threads
  • The topic ‘Access to Worksheet Named Selection via Python console’ is closed to new replies.