0% found this document useful (0 votes)
6 views16 pages

Adams 2021 Adams Interface User's Guide

The document is a user's guide for the Python Interface of Adams, detailing how to interact with the software using Python as an alternative to its command language. It covers the basics of Python, including data types, control structures, and how to run Python scripts within the Adams environment. Additionally, it provides information on object creation and manipulation through the Adams Python API.

Uploaded by

mrzarei12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Adams 2021 Adams Interface User's Guide

The document is a user's guide for the Python Interface of Adams, detailing how to interact with the software using Python as an alternative to its command language. It covers the basics of Python, including data types, control structures, and how to run Python scripts within the Adams environment. Additionally, it provides information on object creation and manipulation through the Adams Python API.

Uploaded by

mrzarei12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Adams 2021

Python Interface User's Guide


Corporate Europe, Middle East, Africa
MSC Software Corporation MSC Software GmbH
4675 MacArthur Court, Suite 900 Am Moosfeld 13
Newport Beach, CA 92660 81829 Munich, Germany
Telephone: (714) 540-8900 Telephone: (49) 89 431 98 70
Toll Free Number: 1 855 672 7638 Email: [email protected]
Email: [email protected]

Japan Asia-Pacific
MSC Software Japan Ltd. MSC Software (S) Pte. Ltd.
Shinjuku First West 8F 100 Beach Road
23-7 Nishi Shinjuku #16-05 Shaw Tower
1-Chome, Shinjuku-Ku Singapore 189702
Tokyo 160-0023, JAPAN Telephone: 65-6272-0082
Telephone: (81) (3)-6911-1200 Email: [email protected]
Email: [email protected]

Worldwide Web
www.mscsoftware.com

Support
http://www.mscsoftware.com/Contents/Services/Technical-Support/Contact-Technical-Support.aspx

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.
MSC Software Corporation 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. MSC Software Corporation 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 © 2020 MSC Software Corporation. Printed in U.S.A. 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 MSC Software Corporation is prohibited.
This software may contain certain third-party software that is protected by copyright and licensed from MSC Software suppliers.
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 http://www.mscsoftware.com/thirdpartysoftware (or successor
website designated by MSC from time to time). Portions of this software are owned by Siemens Product Lifecycle Management, Inc.
© Copyright 2020
The MSC Software logo, MSC, MSC Adams, MD Adams, and Adams are trademarks or registered trademarks of MSC Software
Corporation in the United States and/or other countries. Hexagon and the Hexagon logo are trademarks or registered trademarks of
Hexagon AB and/or its subsidiaries. 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:V2021:Z:Z:Z:DC-PHY
Documentation Feedback
At MSC Software, we strive to produce the highest quality documentation and welcome your feedback.
If you have comments or suggestions about our documentation, write to us at: documentation-
[email protected].
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 MSC Software documentation by taking a short 5-minute
survey at: http://msc-documentation.questionpro.com.

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: https://www.python.org/
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 https://www.python.org/

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]
>>> myList.append(55)
>>> myList
[8, 6, 7, 5, 3, 0, 9, 55]
>>> myList.insert(2, 66)
>>> myList
[8, 6, 66, 7, 5, 3, 0, 9, 55]
>>> myList.reverse()
>>> myList
[55, 9, 0, 3, 5, 7, 66, 6, 8]
>>> myList.sort()
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:
adams2021 aview ru-s b testscript1.py
On Linux platforms in a command shell:
adams2021 -c aview ru-s b testscript1.py

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 aview.cmd 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 aview.cmd 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 = Adams.Models.create() # creates a model with an auto generated
name

mod = Adams.Models.create(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 = mod.Parts.createRigidBody()
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 = mod.Parts.createRigidBody(name="PART1", adams_id=10)

Object lookup
Object managers implement the collections.Mapping 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 = Adams.getCurrentModel().Parts.createRigidBody()
for i in range(5):
part.Markers.create(name="marker_" + str(i))

# Look up the marker named "marker_3"


m3 = part.Markers["marker_3"]

# Get a list of markers and marker names


marker_names = part.Markers.keys()
markers = part.Markers.values()
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 part.Markers:
print(name)

# Shift the location of each marker


for marker in part.Markers.values():
loc = marker.location
loc[0] += 10
loc[1] += 5
marker.location = 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 = part.Geometries.values("GeometryBlock", GeometryEllipsoid")

Note: The above lookup mechanism is based on the object name. For lookup based on the
object full name, use keys2().

# Get a list of marker full names under the part


marker_full_names = part.Markers.keys2()
The Manager classes also provide the values2() and items2(), which are 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=Adams.defaults.model
rcount=10
d1=[0,1,2,3,4,5,6,7,8,9] # values as a list
mat1=model.DataElements.createMatrixFull(row_count=rcount, column_count=1,
values=d1)
d2=(0,1,2,3,4,5,6,7,8,9) # values as a tuple
mat2=model.DataElements.createMatrixFull(row_count=rcount, column_count=1,
values=d2)
d3=range(rcount) # values as a range
mat3=model.DataElements.createMatrixFull(row_count=rcount, column_count=1,
values=d3)
len(mat1.values)==rcount # verify number of values in matrix
True
mat1.values==mat2.values # verify matrices are identical
True
mat2.values==mat3.values
True

Using expressions
The Adams Python Interface provides methods to enable setting an expression or the value of an evaluated
expression on properties.
Adams.expression(expression_string) - to set an expression
Adams.eval(expression_string) - to set the evaluated value of an expression
Here are some examples:
# Parameterize the radius of a circle

mod = Adams.defaults.model
p = mod.Parts.createRigidBody(name="PART_1")
m = p.Markers.create(name="MAR_1")
c = p.Geometries.createCircle(name="CIRCLE_1", center_marker=m)
dv1 = mod.DesignVariables.createReal(name="DV_1", value=100.0)

#Parameterize the radius property with DV_1


c.radius=Adams.expression(dv1.full_name)

#Evaluate DV_1 and set the value as the radius


c.radius=Adams.eval(dv1.full_name)

# Parameterize the location and orientation of a marker

mod = Adams.defaults.model
p = mod.Parts.createRigidBody(name="PART_1")
m1 = p.Markers.create(name="MARKER_1")
m2 = p.Markers.create(name="MARKER_2")

#Parameterize the location property with MARKER_1


m2.location = Adams.expression("(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


m2.orientation = Adams.eval("(ORI_RELATIVE_TO({0.0, 0.0, 0.0},%s))" %
m1.full_name)
Examples 11

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:\MSC.Software\Adams\20XX\adamspy\examples\

Adams python classes reference


For the detailed description and usage of the classes see here.
12 Adams Python Interface

You might also like