TAGGED: python, worksheet-access
-
-
September 18, 2021 at 11:44 amciemaSubscriber
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!
September 22, 2021 at 9:57 amNaresh PatreAnsys 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)
September 22, 2021 at 10:12 amErik KostsonAnsys 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
October 18, 2021 at 8:58 amciemaSubscriberThank you !
April 7, 2023 at 12:02 pmedutenorioSubscriberThanks 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)Â
April 7, 2023 at 12:05 pmedutenorioSubscriberMy 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.
Ansys Innovation SpaceTrending discussions- How to apply Compression-only Support?
- At least one body has been found to have only 1 element in at least 2 directions
- Error when opening saved Workbench project
- Script Error Code:800a000d
- Elastic limit load, Elastic-plastic limit load
- Image to file in Mechanical is bugged and does not show text
- Element has excessive thickness change, distortion, is turning inside out
Top Contributors-
1772
-
635
-
599
-
591
-
366
Top Rated Tags© 2025 Copyright ANSYS, Inc. All rights reserved.
Ansys does not support the usage of unauthorized Ansys software. Please visit www.ansys.com to obtain an official distribution.
-