Adams 2023.
1
Python Interface User's Guide
Americas Europe, Middle East, Africa
5161 California Ave, Suite 200 Am Moosfeld 13
University Research Park 81829 Munich, Germany
Irvine, CA 92617 Telephone: (49) 89 431 98 70
Telephone: (714) 540-8900 Email: [Link]@[Link]
Email: [Link]@[Link]
Japan Asia-Pacific
KANDA SQUARE 16F 100 Beach Road
2-2-1 Kanda Nishikicho, Chiyoda-ku #16-05 Shaw Tower
Tokyo 101-0054, Japan Singapore 189702
Telephone: (81)(3) 6275 0870 Telephone: 65-6272-0082
Email: [Link]@[Link] Email: [Link]@[Link]
Worldwide Web
[Link], [Link]
Support
[Link]
Disclaimer
This documentation, as well as the software described in it, is furnished under license and may be used only in accordance with the
terms of such license.
Hexagon reserves the right to make changes in specifications and other information contained in this document without prior notice.
The concepts, methods, and examples presented in this text are for illustrative and educational purposes only, and are not intended
to be exhaustive or to apply to any particular engineering problem or design. Hexagon assumes no liability or responsibility to any
person or company for direct or indirect damages resulting from the use of any information contained herein.
User Documentation: Copyright © 2023 Hexagon AB and/or its subsidiaries. All Rights Reserved.
This notice shall be marked on any reproduction of this documentation, in whole or in part. Any reproduction or distribution of this
document, in whole or in part, without the prior written consent of Hexagon is prohibited.
This software may contain certain third-party software that is protected by copyright and licensed from third party licensors. Additional
terms and conditions and/or notices may apply for certain third party software. Such additional third party software terms and
conditions and/or notices may be set forth in documentation and/or at Third party software information (or successor website
designated by Hexagon from time to time). Portions of this software are owned by Siemens Product Lifecycle Management, Inc. ©
Copyright 2023.
The Hexagon logo, Hexagon, MSC, MSC Adams, MD Adams, and Adams are trademarks or registered trademarks of Hexagon AB
and/or its subsidiaries in the United States and/or other countries. FLEXlm and FlexNet Publisher are trademarks or registered
trademarks of Flexera Software. Parasolid is a registered trademark of Siemens Product Lifecycle Management, Inc. All other
trademarks are the property of their respective owners.
ADAM:V2023.1:Z:Z:Z:DC-PHY
Documentation Feedback
At Hexagon Manufacturing Intelligence, we strive to produce the highest quality documentation and
welcome your feedback. If you have comments or suggestions about our documentation, write to us.
Please include the following information with your feedback:
Document name
Release/Version number
Chapter/Section name
Topic title (for Online Help)
Brief description of the content (for example, incomplete/incorrect information, grammatical
errors, information that requires clarification or more details and so on).
Your suggestions for correcting/improving documentation
You may also provide your feedback about Hexagon Manufacturing Intelligence documentation by
taking a short 5-minute survey.
Note: The above mentioned e-mail address is only for providing documentation specific
feedback. If you have any technical problems, issues, or queries, please contact Technical
Support.
Introduction 1
Introduction
The Python interface to Adams enables users to interact with Adams using the Python language as an
alternative to the Adams View command language. The Adams Python Interface is a Python API
(Application Programming Interface) that enables creation and modification of modeling objects in Adams.
Python is a general-purpose powerful object-oriented scripting language. For information about Python in
general see: [Link]
The Adams Python interface has been developed as an "object oriented" interface where each entity in Adams
maps to a class in Python having properties and methods.
You can use the Python interface in following ways:
Import a Python script in Adams View
Execute a set of Python commands using the Adams View command window
Run Python scripts in the batch mode by specifying the Python script name in the Adams
command line
The Adams View command line also supports operations available in python integrated
development environments.
Overview of the interface
This section provides an overview of the Python interface and the object model in place.
Introduction to Python
Python is an object oriented interpreted scripting language. This section contains a brief description of the
language. Detailed reference can be obtained at [Link]
Python data types
The following are some of the built-in data types used in the Adams Python Interface. See here for more
information.
Integer
Python's built-in integer type is based on the C long. The following creates a variable that refers to an integer
object:
x = 42
Variables of other types (such as floats or strings) can be converted to integers using int(n).
Float
The built-in float type is based on the C double.
x = 3.14159
2 Adams Python Interface
y = 0.0
Floats can also be declared using exponential notation:
exp = 1.122e-5
Sequences
Sequences are objects containing a series of objects. Python comes with a number of built-in sequence types,
most importantly list, tuple, and string.
List
A list is a sequence that is mutable and heterogeneous. A mutable data type is one that can be modified. This
means that it's possible to add, remove, or change the elements of a list. When we say that lists are
heterogeneous, we mean that the elements of a list don't all need to be of the same type. A list could contain
all integers, or all strings, but it could also contain some combination of floats, Booleans, strings, or whatever
type of object you choose. Lists can contain any type of object.
intList = [1, 2, 3]
floatList = [1.2, 3.4, 5.6, 7.8]
stringList = ["thing_1", "thing_2"]
listList = [[1, 2, 3], ['a', 'b', 'c'], [4, 5, 6]]
You can refer to an individual item inside of a list using the item's index. Indices start at zero, and negative
values count backwards from the end of the list.
>>> floatList[0]
1.2
>>> intList[-1]
3
>>> listList[2]
[4, 5, 6]
>>> listList[2][1]
5
You can modify a list by simply referring to a location in the list, and assigning it a value.
>>> myList = [0, 1, 2, 3]
>>> myList[1] = "foo"
>>> myList
[0, "foo", 2, 3]
The following example shows some useful methods that can be used on lists:
>>> myList = [8, 6, 7, 5, 3, 0, 9]
>>> [Link](55)
>>> myList
[8, 6, 7, 5, 3, 0, 9, 55]
>>> [Link](2, 66)
>>> myList
[8, 6, 66, 7, 5, 3, 0, 9, 55]
>>> [Link]()
>>> myList
[55, 9, 0, 3, 5, 7, 66, 6, 8]
>>> [Link]()
Overview of the interface 3
>>> myList
[0, 3, 5, 6, 7, 8, 9, 55, 66]
Tuple
Tuples are similar to lists in that they are heterogeneous. However, unlike lists, tuples are immutable,
meaning they cannot be modified after they are created. This means that the methods shown above used to
modify lists cannot be used on tuples. Attempting to modify a tuple will result in an AttributeError
being raised. Tuples can be created as follows:
emptyTuple = ()
fullTuple = (0.1, 2.3, 4.5, 6.7)
As with any sequence type, individual elements can be accessed with the elements index.
>>> myTuple = (5, 4, 3, 2, 1)
>>> myTuple[0]
5
>>> myTuple[-2]
2
String
A string is an immutable sequence of characters. Strings can be defined using either single or double quotes.
str1 = "foo"
str2 = 'bar'
Common Operations on Sequences
The following operations can be used on any sequence.
Concatenation
You can concatenate sequences using the "+" operator.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> a = "foo"
>>> b = "bar"
>>> a + " " + b
'foo bar'
Slicing
A slice, or subsequence, from m to n of a sequence can be obtained using the expression mySequence[m:n].
>>> myList = [0, 1, 2, 3, 4, 5, 6]
>>> myList[2:6]
[2, 3, 4, 5]
The first index has a default value of zero. The second index has a default value of the length of the sequence.
4 Adams Python Interface
>>> myString = "This is a string."
>>> myString[:5]
'This '
>>> myString[8:]
'a string.'
Dictionary
Dictionaries map hashable values, which we call the dictionary's keys, to any other object type, which we call
the dictionary's values. The keys of a dictionary can be of any immutable type, such as strings, integers, or
tuples. Mutable types like lists cannot be used as keys. To create a dictionary, place a comma-separates list of
key-value pairs inside of braces.
phone_numbers = {"Jack": "555-5555", "Jill": "444-4444"}
Accessing the values of a dictionary is similar to accessing the values of a sequence. The difference is that
instead of using an index, we use a key.
>>> phone_numbers["Jack"]
"555-5555"
Control structures
Python does not provide any special character to denote bocks of code. Instead, control blocks are denoted
by indentation. The number of tabs and spaces can vary from block to block, but code in the same block
must have the same indentation.
# This is fine
if True:
print("True")
else:
print("False")
# This will generate an error
if True:
x = "True"
print(x)
else:
x = "False"
print(x)
Note: Any text written after a '#' is considered a comment, and is ignored by the interpreter.
Conditional Statements
temp = 72.3
if temp >= 82.2:
print("Too hot!")
elif temp < 62.7:
print("Too cold!")
else:
print("Just right")
Overview of the interface 5
Loops
n = 12
d = 3
while n >= d:
n = n - d
For loops can be used to iterate over any iterable object, such as a list. The built in range function returns a
list of integers, and is commonly used in for loops.
for i in range(10):
print(str(i) + " squared is " + str(i*i))
The break statement breaks out of the smallest containing loop.
for n in range(2, 20):
for x in range(2, n):
if x * x == n:
print(str(n) + " is a perfect square")
break
elif x * x > n:
print(str(n) + " is not a perfect square")
break
The continue statement skips the rest of the loop and moves to the next iteration.
for x in range(25):
if 24 % x != 0:
continue
print("%d divides 24" % x)
Functions
A function is a reusable block of code that can accept arguments and return values. A function definition
starts with the def keyword. The following function accepts two arguments, subtracts the second value from
the first, and then returns the difference:
def difference(a, b):
c = a - b
return c
When you call a function, write the arguments you wish to pass in parenthesis, separated by commas:
>>> difference(13.7, 9.5)
4.2
In the above example, we used the order of the arguments to dictate which value gets assigned to which
variable in the function. These are called positional arguments. Python also lets you use keyword arguments.
Keyword arguments must come after any positional arguments, and allow you to specify the variable the
value should be assigned to:
>>> difference(a=12, b=7)
5
>>> difference(b=12, a=7)
-5
Python functions also allow for optional arguments.
6 Adams Python Interface
def difference(a, b, abs=False):
c = a - b
if abs and c < 0:
c *= -1
return c
The above function can be called with either two or three arguments. If no value is provided for abs, it will
take on the default value of False. When multiple optional values are provided, it is usually useful, and
sometimes necessary, to pass the optional values via keyword arguments.
Using Python scripts in Adams
There are three ways in which Python scripts can be run in Adams.
File Import Dialog
A new option has been added to the dialog for importing Python scripts
Command Window
The command window in Adams now supports both cmd language and Python.
Using Python scripts in Adams 7
On switching to the "py" option in the drop down, the command window starts accepting Python
commands.
Command line
Python scripts can be executed in batch from the Adams command line
On the Windows platform in an Adams shell:
adams2023_1 aview ru-s b [Link]
On Linux platforms in a command shell:
adams2023_1 -c aview ru-s b [Link]
Running a Python script at startup
Two methods are available for executing a Python script during Adams View startup.
1. Set PYTHONSTARTUP environmental variable to the full path of the python script. If
PYTHONSTARTUP gives the path of a readable python file, the Python commands in that file is
executed after [Link] start up file when Adams view is launched. The file is executed in the same
namespace where interactive commands are executed so that Adams view objects defined or imported
in it can be used in the Adams view interactive session.
2. Put the line below in the [Link] file in the working directory.
var set var= int =
(eval(run_python_code("exec(open('<python_file_path>').read())")))
The Adams session object
The Adams class represents the Adams session object. This class can be used to create and lookup models and
also to obtain the current active model.
8 Adams Python Interface
Creation and lookup of objects
While writing a Python script for Adams, some of the things that will done frequently are creation of objects,
lookup of created objects and modification of object properties. The Adams python api documentation has
a complete listing of object managers and properties.
The Adams Python interface provides an easy to use and convenient way for the above. The following section
shows creation of Adams objects using python. These commands are typed in the Adams View command
window.
Object creation
The creation of objects is handled by "managers" designed to create objects of a particular class. Every object
has a handle to these "managers" for types of objects that can be created under them. A model is created in
the current session with this command:
mod = [Link]() # creates a model with an auto generated
name
mod = [Link](name="MODEL3") # creates a new model with a
specified name
Variable mod is the python handle to the model just created. Model class has a handle to the "manager" for
creation of Part objects. A part of type 'RigidBody' can be created under mod with this python command.
p = [Link]()
This will create a rigid body part under the model "mod". Managers that support multiple object types have
create methods of the form create<Class Name> for each class they support. The part manager supports
creation of - RigidBody, FlexibleBody and PointMass objects with corresponding creation methods
createRigidBody, createFlexBody, and createPointMass.
The "create" function can also take in additional optional parameters as below:
p = [Link](name="PART1", adams_id=10)
Object lookup
Object managers implement the [Link] interface, and hence behave like a Dictionary which
maps object names to their corresponding objects. Here are some examples making use of this dictionary-like
behavior:
# Create a part in the current model with 5 child markers
part = [Link]().[Link]()
for i in range(5):
[Link](name="marker_" + str(i))
# Look up the marker named "marker_3"
m3 = [Link]["marker_3"]
# Get a list of markers and marker names
marker_names = [Link]()
markers = [Link]()
Using Python scripts in Adams 9
As with python dictionaries, managers are iterable. It's important to note that, as in python dictionaries,
iterating over the manager iterates over its keys, which are the names of the child objects.
# Print the names of each marker under our part
for name in [Link]:
print(name)
# Shift the location of each marker
for marker in [Link]():
loc = [Link]
loc[0] += 10
loc[1] += 5
[Link] = loc
For managers that support multiple object types, methods related to the dictionary-like behavior accept class
names as strings, allowing you to filter down to specific object types:
# Get a list of all Block and Ellipsoid geometries under our part
g = [Link]("GeometryBlock", GeometryEllipsoid")
Note: The above lookup mechanism is based on the object name. For lookup based on the
object full name, use keys_full().
# Get a list of marker full names under the part
marker_full_names = [Link].keys_full()
The Manager classes also provides items_full(), which is based on the object full
name.
Object Properties
The classes of the Adams Python interface have properties which map to the database attributes of the Adams
object in the database. These properties can be set and/or retrieved by simply accessing the relevant descriptor
with a class object.
p_PART_001.properties #Get all properties for a modeling object
['adams_id', 'cm', 'cm_name', 'comment', 'density', 'exact_phi',…]
Properties can be set and retrieved from the property names
p_PART_001.adams_id = 19910 # set the Adams ID for this part
p_PART_001.adams_id # print property value to verify that
it was set
19910
Defining Array property
Several Adams modeling classes with properties of type array. These properties can be defined by python
objects of one of these types:
List
Tuple
Range
10 Adams Python Interface
Example:
model=[Link]
rcount=10
d1=[0,1,2,3,4,5,6,7,8,9] # values as a list
mat1=[Link](row_count=rcount, column_count=1,
values=d1)
d2=(0,1,2,3,4,5,6,7,8,9) # values as a tuple
mat2=[Link](row_count=rcount, column_count=1,
values=d2)
d3=range(rcount) # values as a range
mat3=[Link](row_count=rcount, column_count=1,
values=d3)
len([Link])==rcount # verify number of values in matrix
True
[Link]==[Link] # verify matrices are identical
True
[Link]==[Link]
True
Using expressions
The Adams Python Interface provides methods to enable setting an expression or the value of an evaluated
expression on properties.
[Link](expression_string) - to set an expression
[Link](expression_string) - to set the evaluated value of an expression
Here are some examples:
# Parameterize the radius of a circle
mod = [Link]
p = [Link](name="PART_1")
m = [Link](name="MAR_1")
c = [Link](name="CIRCLE_1", center_marker=m)
dv1 = [Link](name="DV_1", value=100.0)
#Parameterize the radius property with DV_1
[Link]=[Link](dv1.full_name)
#Evaluate DV_1 and set the value as the radius
[Link]=[Link](dv1.full_name)
# Parameterize the location and orientation of a marker
mod = [Link]
p = [Link](name="PART_1")
m1 = [Link](name="MARKER_1")
m2 = [Link](name="MARKER_2")
#Parameterize the location property with MARKER_1
[Link] = [Link]("(LOC_RELATIVE_TO({0.0, 0.0, 0.0},%s))" %
m1.full_name)
#Evaluate ORI_RELATIVE_TO with respect to MARKER_1 and set as the orientation
[Link] = [Link]("(ORI_RELATIVE_TO({0.0, 0.0, 0.0},%s))" %
m1.full_name)
Examples 11
Using Extended Names
Object creation
mod = [Link](name="MODEL 3") # creates a new model
with a specified name. User can use Unicode String or Special
characters( ~`@# $ ^ ()'%. &-+;',{}[]= ) in name.
p = [Link](name="PART .1", adams_id=10)
Standard Python Command:
bs = [Link](name='Gcurve_1',
ref_marker_name = '.MODEL_1.Part_1.Marker_1', ref_curve_name =
'MODEL_1.Curve_1', segment_count = 20)
If MODEL_1 changed to MODEL.1, Part_1 to Part 1 and Marker_1 to Marker 1 then
Python command syntax with the special characters will be
bs = [Link](name='Gcurve_1',
ref_marker_name = '.\'MODEL.1\'.Part [Link] 1', ref_curve_name
= '.\'MODEL.1\'.Curve 1', segment_count = 20)
If dot('.') character is present in an object name then the object name must be enclosed in single
quotes.
CMD execution using Python command
If executing CMD commands from a Python script, then those commands must follow the CMD
enhanced naming syntax.
Example:
Adams.execute_cmd("interface dialog_box display dialog_box_name
= .gui.design_variable_cremod parameters = \"DV TEST.123\"")
To handle unicode characters, Adams Python scripts should use encoding as "UTF-8"
Open("file_name", "w") should be Open("file_name", "w",
encoding="UTF8")
Examples
Guided tutorials and other example Python scripts can be found within the Adams installation
“<topdir>\adamspy\examples\”. For example, on a Windows installation for Adams version 20XX the
example files are placed in the following location: C:\Program
Files\[Link]\Adams\20XX\adamspy\examples\
Adams python classes reference
For the detailed description and usage of the classes see here.
12 Adams Python Interface