The seminar includes use of Python for accessing Abaqus results on the output
database ... and Abaqus/Viewer, and general use of Python to accomplish varied.
Introduction to Python and Scripting in Abaqus
2
Agenda • Overview • Python • Scripting in Abaqus • Specialized Postprocessing • Advanced Topics
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Overview
4
Overview • The goal of this advanced seminar is to introduce you to the Abaqus Scripting Interface. The Abaqus Scripting Interface allows you to customize Abaqus to suit your specific requirements. • Abaqus Version 6 makes extensive use of Python, a powerful, widely used scripting language. This seminar covers Python’s basic syntax and provides numerous worked examples. • The seminar includes use of Python for accessing Abaqus results on the output database (.odb) file, use of Python for scripting with Abaqus/CAE and Abaqus/Viewer, and general use of Python to accomplish varied programming tasks.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
5
Overview • Motivation: Why customize Abaqus? • Automate repetitive tasks • Model building
Provides automated environment for experienced analysts
• Postprocessing • Prescribe default behavior • Extend functionality
Customized versions of Abaqus provide an effective analysis tool for a wide range of user expertise …
Customized application
• Job submission and monitoring
• Enhance the interface • Graphical • Nongraphical
Provides advanced analysis functionality to non-FE users
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
6
Overview
Abaqus Scripting predominantly affects Abaqus/CAE customization
• Abaqus/CAE customization • The ASI allows you to customize much of the behavior of Abaqus preand post-processing to suit your specific requirements. • Scripts that affect the Graphical User Interface are called GUI scripts. Those that do not are called kernel scripts. • Solver Customization • The Abaqus solvers may be customized with user subroutines. • Site Customization • Hardware, operating system, batch queuing, etc. may be tuned for Abaqus performance.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
7
Overview • Two manuals* are presently available for scripting
* these two manuals are available in electronic format only. Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
8
Legal Notices The information in this document is subject to change without notice and should not be construed as a commitment by ABAQUS, Inc. ABAQUS, Inc., assumes no responsibility for any errors that may appear in this document. The software described in this document is furnished under license and may be used or copied only in accordance with the terms of such license. No part of this document may be reproduced in any form or distributed in any way without prior written agreement with ABAQUS, Inc. Copyright © Dassault Systèmes 2007. Printed in U.S.A. The following are trademarks or registered trademarks of ABAQUS, Inc. or its subsidiaries in the United States and/or other countries: Abaqus, Abaqus/Standard, Abaqus/Explicit, Abaqus/CAE, Abaqus/Viewer, Abaqus/Aqua, Abaqus/Design, Abaqus/Foundation, Abaqus/AMS, Abaqus for CATIA V5, VCCT for Abaqus, DDAM for Abaqus, Unified FEA, ABAQUS and the ABAQUS Logo. The 3DS logo and SIMULIA are trademarks of Dassault Systèmes. Other company, product, and service names may be trademarks or service marks of their respective owners. For additional information concerning trademarks, copyrights, and licenses, see the Legal Notices in the Abaqus Version 6.7 Release Notes and the notices at: http://www.simulia.com/products/products_legal.html.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
9
Revision Status
Lecture 1
5/07
Updated for V6.7
Lecture 2
5/07
Updated for V6.7
Lecture 3
5/07
Updated for V6.7
Lecture 4
5/07
Updated for V6.7
Workshop 1.1
5/07
Updated for V6.7
Workshop 1.2
5/07
Updated for V6.7
Workshop 2.1
5/07
Updated for V6.7
Workshop 2.2
5/07
Updated for V6.7
Workshop 3.1
5/07
Updated for V6.7
Workshop 3.2
5/07
Updated for V6.7
Workshop 4.1
5/07
Updated for V6.7
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Python
Lecture 1
Copyright 2007 Dassault Systèmes
L1.2
Overview • Basics • Types • Programming Constructs • Namespaces • Modules • Exceptions • Examples • Workshops
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Basics
Copyright 2007 Dassault Systèmes
L1.4
Basics • Python features Free:
Open Source Software (no restrictions on copying, embedding, selling, etc.)
Portable:
It runs on all major platforms
Interpreted:
No lengthy compile and debug cycle; useful for rapid prototyping
Mixable:
Can be used with components written in other languages
Easy:
Simple easy to read syntax
Powerful:
Incorporates dynamic typing, built-in objects and tools, library utilities, 3rd party extensions, automatic memory management, modules, classes, exceptions
Object oriented:
Class model supports encapsulation, polymorphism, and multiple inheritance
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.5
Basics • Python references • Official Python web site: www.python.org • Online tutorial www.python.org/doc/current/tut/tut.html
• News groups comp.lang.python comp.lang.python.announce
• Many books are available. www.rmi.net/~lutz/pybooks.html
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.6
Basics • How to run Python • Interactive $ abaqus python >>> print 5**4 625 >>> To exit: Ctrl-D (on UNIX), Ctrl-Z & Return (on Windows) To exit on both: import sys; sys.exit()
• Command line $ abaqus python -c "print 5**4" 625
• Top-level Script $ abaqus python mytest.py 625
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
a = 5; b = 4 c = a ** b print c
L1.7
Basics • How to run Python (cont.) • Unix-style script file #!/prog/python a = 5; b = 4 c = a ** b print c
$ mytest.py 625
• Embedded in another system • E.g., Abaqus/CAE
Run as top level script
Run in interactive mode
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.8
Basics • How to run Python (cont.) • Windows-style script file D:\ mytest 625
a = 5; b = 4 c = a ** b print c
• The interactive mode will echo data by default. Running from files will not.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.9
Basics • Syntax • Indentation delimits blocks (not braces { } as in C++ or Perl). • Comments start with # and continue to the end of the line. • Names are case-sensitive. • More than one noncompound statement per line: Use semicolon. • Line continuation: Use backslash (not necessary within parentheses).
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.10
Basics • Example using common syntax rules: Comments start with # and continue to the end of the line
# simple example max = 5; i = 0 x, y, z = 1, 2, 3
Semicolon for two statements blank lines ignored
Indentation delimits blocks (such as loops) The amount of indentation is arbitrary but must be consistent for a block
The syntax forces the while i >> x = 4
# variable name x refers to the integer 4
– x is the variable name; it refers to an integer object 4.
• There are no declarations for variable names. • Any number of identifiers can assigned to the same object: >>> a = b = 'test' >>> print a, b 'test' 'test'
• When there are no references to an object, the object is deleted automatically.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.12
Basics • Objects • An object is an entity that has properties (data) and functions bound to it. • In Python the properties bound to an object are called members and the functions bound to an object are called methods. The attributes called • Example: file object >>> f = open('tmp.txt') >>> f.close() >>> f.closed
method member
__members__ and __methods__ are discontinued in Python v2.2 but will be maintained in Abaqus Python.
True
• The members and methods of an object can be queried. >>> mdb.__members__ ['acis', 'adaptivityProcesses', 'annotations', …] >>> mdb.__methods__ ['AdaptivityProcess', 'Annotation', 'Arrow', …]
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.13
Basics • Functions • A function encapsulates code to perform a specific task. >>> def test(arg1, arg2): ... print 'arg1=', arg1 ... print 'arg2=', arg2 ... >>> test('pink', 'bicycle') arg1= pink arg2= bicycle
• A function can return any object. >>> def distance(point1, point2): ... x1, y1 = point1[0], point1[1] ... x2, y2 = point2[0], point2[1] ... sq = (x2 - x1)**2 + (y2 - y1)**2 ... return sq**(0.5) ... >>> distance((0,0),(4,6)) 7.2111025509279782 Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.14
Basics • Keyword arguments • You can specify arguments in any order by using keywords. >>> test(arg2='bicycle', arg1='blue') arg1= blue arg2= bicycle
• If a function has default arguments, you can omit arguments: >>> def distance(point1, point2=(0,0)): ... x1, y1 = point1[0], point1[1] ... x2, y2 = point2[0], point2[1] ... sq = (x2 - x1)**2 + (y2 - y1)**2 ... return sq**(0.5) ... >>> distance((4,6)) 7.2111025509279782
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.15
Basics • Recursion • A function may be used to call itself • Python has a limit on the depth of recursive function calls (default is 1000). • Example: factorial function • The definition is often written as: 0! = 1 n! = n*(n-1)!
• This may be replicated with a recursive function def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) >>> factorial(69) 1711224524281413113724683388812728390922705448935203693936480 0923257279754140647424000000000000000L
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.16
Basics • Operators Mathematical: +, -, *, **, /, % >>> (5 + 3)/2 4
Logical: and, or, not >>> 1 or 0 1
Comparison: =, != (!= same as ) >>> 5 != 6 1
Bitwise: |, ^, &, >>> 1 >> list1 = [1,2,3] >>> list1 [1, 2, 3] >>> list2 = list1.append(4) >>> list2 >>> list1 [1, 2, 3, 4] >>> type(list2)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Types
Copyright 2007 Dassault Systèmes
L1.21
Types • Number:
int, long, float, complex, bool
• Sequence: string, list, tuple, array • Map:
dictionary
• Other:
file, module, function, class
• An int is based on a C long. (Compare FORTRAN integer*4 or *8.) • A long has unlimited size. • A float is based on a C double. (Compare FORTRAN real*8.) • A sequence can be indexed and sliced. • Abaqus defines many additional types. • To query the type of an object, use this built-in function: type(object).
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.22
Types • Number types
Numbers
• Integer (decimal, octal, hexadecimal)* Example: 1234, 0644, 0x100fea8
• Long Example: >>> 17643L**11111
Integers
Float
Integer
Complex
Long Integer
463783748290623436091218...
• Float Examples: 3.1415, .0314e2, .0314e+2, .0314e-2
• Complex Examples: z = 2 + 3j, 12.34j z.real, z.imag
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
* To specify octal or hexadecimal, precede the value with 0 or 0x respectively.
L1.23
Types • Type coercion • If number types differ in an operation, a coercion operation is automatically performed to convert one of the types to the other • Operations between an integer and a float create a float. >>> 5*2.0 10.0
• Operations between integers resulting in fractions do not create a float. >>> 3/2 1 >>> 2/3 0
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.24
Types • Sequence types • There are three built-in sequence types in Python and an array type implemented in a separate module. Type
Mutable
Homogeneous
Methods
Syntax
list
Yes
No
Yes
[9.0,'b'] ('a',45,)
tuple
No
No
No
string
No
Yes
Yes
'wxyz'
array
Yes
Yes
Yes
array((2.3,5.6))
• Mutable:
Elements may be added, changed, and removed.
• Homogeneous: Elements must be of the same type. • Methods:
The type has methods that can be used to manipulate the contents of the array (e.g., sort(), reverse()).
• Syntax:
Syntax used to construct the object.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.25
Types •Sequence operation examples •Indexing • All sequence types can be indexed. Indices are zero-based. >>> a = ['a','b','c',('A','B','C')] >>> a[0] ’a’ >>> a[3] ('A', 'B', 'C') >>> a[3][1] 'B'
Negative indices—count backward from the end. >>> a[-1] ('A', 'B', 'C') >>> a[-1][-2] 'B'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.26
Types • Slicing • All sequence types can be sliced. s[m:n] • m and n are integers. Default values are [0:len(s)].
• Slicing returns a copy of the sequence from m to just before n. >>> s = [0, 1, 2, 3, 4] >>> s[1:4] [1, 2, 3]
• The copy is of the same type as the sequence being copied. >>> myTuple (175, 999, 'A', 'B') >>> myTuple[1:3] (999, 'A') >>> welcome = 'Hello World' >>> welcome[0:3] + welcome[5:-1] 'Hel Worl'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.27
Types • Repeat >>> a = [0,1] * 3 >>> a [0, 1, 0, 1, 0, 1]
• Length of a sequence >>> len(a) 6
• Concatenation >>> [1,2] + [6,7] [1, 2, 6, 7] >>> (1,2) + (6,7) (1, 2, 6, 7) >>> 'Dead' + 'Parrot' 'DeadParrot'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.28
Types • Sequence types: list • A list is a mutable heterogeneous ordered sequence >>> myList = [175, 999, 'A', 3.14159] >>> myList.append(2003.567) >>> myList [175, 999, 'A', 3.14159, 2003.567] >>> del myList[3] >>> myList [175, 999, 'A', 2003.567] >>> myList.sort() >>> myList [175, 999, 2003.567, 'A']
• List data types have a number of different methods: >>> dir(myList) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.29
Types • Sequence types: tuple • A tuple is an immutable heterogeneous ordered sequence >>> myTuple = (175, 999, 'A', 'B')
• By immutable, we mean that it is not possible to make assignments to the individual items, For example : >>> myTuple[3] = 'W' Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment
• Note: An element of a tuple can be mutable; e.g., a list: >>> myTuple = (175, 999, [1,2,3,4])
• Here myTuple[2] is a list object. Since a list is mutable sequence, it can be changed. The tuple will still contain the same three objects.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.30
Types • Sequence types: string • A string is an immutable sequence of characters • Syntax 'a' "a" """a""". We use 'a' and """a""". >>> name = 'Norwegian' >>> name[3] 'w'
• Manipulation of the string contents is done by making a copy. • The concatenation operator does just that. >>> name = name + ' Blue' >>> name 'Norwegian Blue'
• Triple quoted strings can contain embedded new lines. >>> doc = """This program is designed ... to be all things to all men"""
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.31
Types • Sequence types: array • An array is a mutable homogeneous sequence • Module multiarray defines a multi-dimensional homogeneous array. • The last argument (optional) defines the type; otherwise, the type is based on the contents of the array. >>> from multiarray import array >>> a = array(((4.0,5.0),(2.0,3.0))) >>> a 4. 5. 2. 3.
• Array methods: astype() byteswapped() iscontiguous() itemsize() tolist() tostring() typecode()
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.32
Types • Mapping types: dictionary • A dictionary (also called associative array) is an unordered collection of objects that provides a means of mapping from one set of arbitrary objects to an associated set of objects. • Keys provide the symbolic location of items. All keys must be immutable objects. • A dictionary maps keys to values. For example: >>> myDict = {} # create an empty dictionary >>> myDict['eric'] = 'Eric Idle' >>> myDict['PI'] = 3.14159265359 >>> myDict[2001] = 'Beginning of the century' >>> type(myDict) >>> myDict {'eric': 'Eric Idle', 2001: 'Beginning of the century', 'PI': 3.14159265359} >>> myDict['PI'] 3.14159265359 Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.33
Types • Dictionary data types have a number of different methods: has_key() clear()
keys() copy()
values()
items()
get() update() setdefault()
• Here are a few methods at work: >>> myDict.keys()
['eric', 2001, 'PI'] >>> myDict.has_key('Turnip') 0 >>> myDict.values() ['Eric Idle', 'Beginning of the century', 3.14159265359] >>> myDict.items() [(’eric’, ’Eric Idle’), (2001, 'Beginning of the century'), (’PI’, 3.14159265359)]
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.34
Types • String substitution using tuples and dictionaries • String % Tuple substitution • This is similar to sprintf in C. The format specifiers are the same. • If in doubt, use '%s' (Python will convert the object to its string representation). >>> '%s weighs %5.2f pounds' % ('Eric', 67) 'Eric weighs 67.00 pounds' >>> '%s weighs %s pounds' % ('Eric', 67) 'Eric weighs 67 pounds'
• String % Dictionary substitution • Use variable names as format specifiers. >>> d = {'name': 'Eric', 'number': 67} >>> '%(name)s weighs %(number)5.2f pounds' % d 'Eric weighs 67.00 pounds'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.35
Types • Truth tests • In general, any nonzero number or nonempty object is true. • A zero number, empty object, or the None object is false. • These objects are considered false in Python: 0, 0.0, (,), [], {}, "", and None
• These objects are considered true in Python: 1, 2.3, (1,2), and 'xyz'
• A boolean expression returns a Python bool, True or False >>> (1 == 0) False
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Programming Constructs
Copyright 2007 Dassault Systèmes
L1.37
Programming Constructs • Branching (conditionals) if
elif
else
if grade > 90: print 'you got an A' elif grade > 80: print 'you got a B' elif grade > 70: print 'you got a C' elif grade > 60: print 'you got a D' elif grade > 50: print 'you got an E' else: print 'you failed' Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.38
Programming Constructs • Looping while—similar to C, will continue while expression is true. while expression: do something
for—iterates through a sequence. >>> ... ... 2 3 >>> >>> ... ... a b C
for i in range(2, 6): print i, 4 5 myList = ['a', 'b', 'c'] for letter in myList: print letter
•The range function is convenient for generating a list to iterate through.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.39
Programming Constructs break—break out of the loop. i, max = 0, 50 while 1: if i > max: break else: print i i = i + 1
continue—skip the rest of the code in the loop and go to next iteration. else—execute this if the end of the loop is reached without calling break. for i in range(10): if i < 0: break else: print 'There are no negative values in range(10)'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.40
Programming Constructs • Example: Print a graph in the terminal window for x in range(-21, +19): # skip the case of x = 0 if x == 0: continue # evaluate an expression y = 30 + 30/x # print (x,y) followed by y spaces and a marker print '(%03d,%03d):' % (x,y), ' '*y, 'o'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Namespaces
Copyright 2007 Dassault Systèmes
L1.42
Namespaces • Namespace rules resolve ambiguities when there are multiple occurrences of a name. • Each object has its own namespace (strings, dictionaries, lists, etc.). • Names in an object’s namespace are called qualified names because they are qualified by a dot (“.”). >>> myList = [1, 2, 3] >>> myList.reverse()
• The name myList is unqualified, and the name reverse is qualified.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.43
Namespaces • The Python interpreter first searches scopes lexically to resolve unqualified names, from the local namespace out to the global (module) namespace. It then searches the built-in names (in module __builtin__). 1. Local (function) … Global (module) 2. Built-in (reserved names used by Python) • Example >>> len = 5 >>> def test(): >>> len = 6 >>> print len
• Does this print 5, 6, or ? • The interactive interpreter executes in the namespace of a special module named __main__. • Before Python-2.2, intermediate scopes were ignored.
• A longer example follows
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Modules
Copyright 2007 Dassault Systèmes
L1.45
Modules • A module is a collection of functions and variables that can be reused. • Modules implemented in the Python language are implemented in a file with the extension .py. • A module must be imported to be used. >>> import math >>> x = math.sin(7)
• Names from the module can be copied into the importer’s namespace. >>> from math import sin >>> x = sin(7)
• All the names can be copied into the importer’s namespace. This is not normally recommended, as names can be overwritten. In addition, this style is valid only at module level, not inside functions and methods. >>> from math import *
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.46
Modules • The code in a module is executed when it is imported. • A second import does nothing—use reload(module) if needed. • The names and functions are defined, and the syntax is checked. • Many Python modules are available for use with Abaqus. • Standard modules (httplib) • Contributions from the Internet (Numeric) • Example: # module hworld print 'importing hworld' hw = 'Hello World' c = 76 def pr(x): print x
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
$ abaqus python >>> import hworld importing hworld >>> print hworld.hw Hello World >>> print hworld.c 76 >>> hworld.pr(58) 58
L1.47
Modules • The Python module search path • Python searches the list of directories given in sys.path when looking for requested modules. • The first module found in a path that satisfies the import request is used. • If the module is not found in the search path, an ImportError exception is raised. • The sys.path variable is initialized to directories determined when Abaqus was installed. The search path is augmented using the environment (operating system) variable PYTHONPATH. • The following lines will return a list of directories that are present in sys.path: >>> import sys >>> sys.path
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.48
Modules • Ways of changing the Python module search path for site specific modules: • Modify sys.path directly. • Example: import sys sys.path += ['d:/system/pythonStuff']
• Not generally recommended because hard coding the path may restrict behavior or require constant maintenance. • Assign additional directories to search using PYTHONPATH environment variable value. Note. In Windows, forward directory slashes can be used in Python. If backslashes are used, they must be escaped, or a raw string must be used. i.e. sys.path += ['d:\\system\\pythonStuff'] sys.path += [r'd:\system\pythonStuff']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.49
Modules • Writing a test function • At the command line you are in a built-in module called __main__. • Even for modules that are not intended to run as top-level scripts, it is helpful to include a self-test function and add a line to call it if the file is run as a script. • This is easy to do because when a module is run as a script, its statements are executed in the __main__ module.
Example module format incorporating a self-test using __main__ < exported objects > def test(): < test my exports > if __name__ == '__main__': test()
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.50
Modules • Some convenient module and namespace Python utilities modulename.__file__
• Returns the name of the file from which the module was loaded. globals()
• Returns a dictionary representing the present global symbol table (i.e., the global namespace). This is a misnomer; "global" in this case refers to the current module namespace locals()
• Returns a dictionary representing the present local symbol table (i.e., the local namespace). For example, the namespace of the current function. dir(object)
• Returns a list of attributes for an object (e.g., dir(__builtins__)). sys.modules
• Returns a dictionary of all the loaded modules.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Exceptions
Copyright 2007 Dassault Systèmes
L1.52
Exceptions • What are they? • Exceptions are used for error handling. • An exception is a Python object that can be “raised.” • Raising an exception causes a jump in program execution. • If an exception is not “caught,” it will stop the program and print a stack trace. • Why exceptions? • Exceptions allow an error to be located easily. • Exceptions are more sophisticated and easier to use than return status codes. • Exceptions tell the user the cause of an error. • Exceptions can be raised, caught, and handled by user code.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.53
Exceptions • When the exception is raised, it will stop the program unless caught by the caller. • Examples >>> 1/0 Traceback (most recent call last): File "", line 1, in ? ZeroDivisionError: integer division or modulo by zero def inverse(x): try: print 1/x except ZeroDivisionError: print x, 'has no inverse'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Examples
Copyright 2007 Dassault Systèmes
L1.55
Example 1-1: String Manipulation import sys
# to access command line arguments
def isAnagram(string1, string2): """Return TRUE if string1 is an anagram of string2. Returns FALSE if not an anagram""" if len(string1) != len(string2): return 0 for c in string1: if string1.count(c) != string2.count(c): return 0 else: return 1 if isAnagram(sys.argv[1], sys.argv[2]): print sys.argv[1], 'is an anagram of', sys.argv[2] else: print sys.argv[1], 'is not an anagram of', sys.argv[2]
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.56
Example 1-2: File Manipulation # open a file for reading, and print it out f = open('fileManipulation.txt') text = f.readlines() for line in text: print line[:-1] # chop off the newline char # reverse the order of the lines and save it text.reverse() f = open('temp.txt', 'w') f.write('Reversed file\n') for line in text: f.write(line) f.close() # now print the new file print open('temp.txt').read()
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Workshops
Copyright 2007 Dassault Systèmes
L1.58
Workshop 1-1: Fibonacci Series 1. Print the Fibonacci series up to 10,000. – kn = kn-1 + kn-2 •
For example: 0, 1, 1, 2, 3, 5, 8, 13,. . .
2. Create a function that prints the Fibonacci series between any two (possibly large) numbers:
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L1.59
Workshop 1-2: Circle Module 1. Write a module named circle containing a function that returns the circumference of a circle, given the radius and a function that returns the area of a circle, given the radius. Use the math module to get the value of π. 2. Write a script that imports the circle module and uses it to print the circumference and area of the following series of radii: (5, 6, 7, 8, 9). The results should be formatted into a table as follows: radius
circumference
5.00
31.416
78.5398
6.00
37.699
113.0973
7.00
43.982
153.9380
8.00
50.265
201.0619
9.00
56.549
254.4690
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
area
Scripting in Abaqus
Lecture 2
Copyright 2007 Dassault Systèmes
L2.2
Overview • The Abaqus Scripting Interface • Abaqus Object Model • Abaqus Types • Abaqus Modules • Setting Abaqus Defaults • Getting Interactive Input • Examples • Workshops
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
The Abaqus Scripting Interface
Copyright 2007 Dassault Systèmes
L2.4
The Abaqus Scripting Interface • The Abaqus Scripting Interface • The Abaqus Scripting Interface (ASI) is a Python-based application programming interface (API) to Abaqus. • You can use the Abaqus Scripting Interface to: • Customize your Abaqus environment via the Version 6 environment file (abaqus_v6.env). • Create macros and scripts to automate repetitive pre- and postprocessing tasks. • Read from and write to an output database file (ODB). • Perform parameter studies. • Create Abaqus Plug-ins
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.5
The Abaqus Scripting Interface Abaqus/CAE
• Executing Scripting Interface commands
1 GUI
• Commands are issued by the GUI, via the command line interface, and from scripts.
2
command line interface (CLI)
3 script
commands
• Commands go to the kernel that creates an internal representation of your model.
Python interpreter
replay files
Abaqus/CAE kernel
input file
Abaqus/Standard Abaqus/Explicit Abaqus/Design
output database file Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.6
The Abaqus Scripting Interface • Aside: Terminology • The message area and CLI window • Switch between them using tabs.
The message area tab
The command line interface (CLI) tab Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
The CLI is currently displayed
L2.7
The Abaqus Scripting Interface • Executing scripting commands from the CLI • Python can be accessed by embedding the interpreter in another system. • This has been done in Abaqus/CAE. • The Python interpreter is started when Abaqus/CAE is started. • In the examples below, it is accessed directly by typing in the CLI.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.8
The Abaqus Scripting Interface • When accessing the functionality of any Abaqus/CAE module: • The script must be interpreted by the Abaqus/CAE kernel. (1) You may run the script from within Abaqus/CAE: • From the File menu • Using the Python execfile() at the command line interface. • From the start-up screen. • From the system command line. abaqus cae startup = myscript.py abaqus cae script = myscript.py abaqus viewer startup = myscript.py
(2) You may not bypass the Abaqus/CAE kernel abaqus python myscript.py like this: abaqus script myscript.py
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.9
The Abaqus Scripting Interface •Two simple ways of building new scripts 1. You can use the Macro Manager to record a sequence of the generated You may specify a Abaqus commands in a macro file. location for the macro file when creating a macro.
The filename is abaqusMacros.py. The file always gets appended.
2. You can also use the Abaqus replay file as the basis for a new script. •
The filename for the current session is always abaqus.rpy.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.10
The Abaqus Scripting Interface Example: Creating a script that rotates the model in current display Steps: 1) In Abaqus/CAE rotate the model by a specifying an increment in the View/Specify… dialog box. The Python command for this will be automatically written to the replay file: session.viewports['Viewport:1'].view.rotate(xAngle=10, yAngle=0,zAngle=0,mode=MODEL)
Cut and paste this command into a new text file. 2) Add a Python statement to loop over the command: for x in range(36): session.viewports['Viewport:1'].view.rotate(xAngle=10, yAngle=0,zAngle=0, mode=MODEL)
Save the script as rotate.py. Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.11
The Abaqus Scripting Interface 3) Run the script in Abaqus/CAE by selecting File→Run Script
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.12
The Abaqus Scripting Interface • Abaqus namespaces • Journaling namespace • A private namespace in which commands issued from the GUI are executed. • CLI namespace • The namespace in which commands typed at the CLI are executed. These commands are executed in the Python __main__ module’s namespace. • The journaling and CLI namespaces are not the same! • For example, if this is journaled in the replay file, vp = session.viewports['Viewport: 1']
• The variable vp will not be available in the CLI namespace.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
The Abaqus Object Model
Copyright 2007 Dassault Systèmes
L2.14
The Abaqus Object Model • Overview • The Abaqus Scripting Interface extends Python with new types of objects. • The hierarchy and the relationship between these objects is called the Abaqus Object model. There are three roots in the Abaqus object model: the Session, the Mdb, and the Odb objects. Taken from the Abaqus Scripting User's Manual (available online only)
The complete Abaqus object model is too complex to easily present in a single figure. A container is either a sequence or a repository of like objects.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.15
The Abaqus Object Model • Basics • The object model describes the relationships between objects.
A Part owns features, datums, etc. A Model owns parts
Ownership implies that if an object is copied, everything owned by that object is also copied. Similarly, if an object is deleted, everything owned by the object is deleted. This concept is known as a parent-child relationship in Abaqus/CAE.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.16
The Abaqus Object Model • Using the object model • Recall that the data encapsulated by an object are called the members of the object. • Recall that the functions that manipulate the data are called methods. • A method that creates an object is called a constructor. • Ownership defines the access path to the objects. • Any Python statement that accesses the Session, Mdb, or Odb is called a command.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.17
The Abaqus Object Model • Use commands to access objects by stepping through the hierarchy of objects in the object model. All commands mirror the structure of the object model. • Examples: vp = session.viewports['Viewport: 1'] vp.setValues(origin=(200,0)) cell4 = mdb.models['block'].parts['crankcase'].cells[4] Variable Model cell4 database mdb
model named block
part named crankcase
cell with index 4
• The cell with an index of 4 in the part named crankcase in the model named block in the model database mdb is assigned to the variable cell4.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.18
The Abaqus Object Model • Documentation • Two online manuals are available: • Abaqus Scripting User's Manual: • Overview, descriptions, examples. • Very readable! • Abaqus Scripting Reference Manual: • Details of Abaqus API. • The reference manual describes how to access existing objects via an Access section and how to create new objects via a Path section.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.19
The Abaqus Object Model • The Access and Path descriptions in the Abaqus Scripting Reference Manual describe the access to and interface for each Abaqus object.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.20
The Abaqus Object Model •Constructor example p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=THREE_D, type=DEFORMABLE_BODY)
•The path to the constructor is •mdb.models['Model-1'].Part
•The new Part object is placed into the parts repository •mdb.models['Model-1'].parts['Part-1']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.21
The Abaqus Object Model •Objects without constructors •Some objects have no constructor; Abaqus creates the object for you. •For such objects the initial value of each member can be found in the documentation for setValues. See the default value.
•The following statement modifies the rendition member of the printOptions object (values of other members are not changed): session.printOptions.setValues(rendition=GREYSCALE) Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.22
The Abaqus Object Model • The Session object model
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.23
The Abaqus Object Model • The Session object model (cont.) • Session objects are not persistent† (i.e., not saved between Abaqus/CAE or Abaqus/Viewer sessions). • Session objects include things such as viewport definitions, remote queues, and user-defined views. • The Session objects are normally available only from inside of Abaqus/Viewer or Abaqus/CAE. • Either of the following statements imports the Session objects: from abaqus import * from abaqus import session
†There
is one exception to this rule: XYData session objects may be written to the ODB
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.24
The Abaqus Object Model • The Mdb object model Mdb objects are persistent. The Mdb objects are normally available only from inside Abaqus/Viewer or Abaqus/CAE. Either of the following statements imports the Mdb objects from abaqus import * from abaqus import mdb
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.25
The Abaqus Object Model • Output Database object model • Odb objects are persistent. • The following statement imports the Odb constructors: from odbAccess import * from odbAccess import openOdb, Odb
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.26
The Abaqus Object Model • Object model interrogation • If you are unsure of the contents and/or relationships used within the object model, use Python tools to query actual .cae or .odb databases: • Use type() to determine the object type. • If the object type is part of the Abaqus extension: • Use object.__members__ to view the members of an object. • Use object.__methods__ to view the methods of an object. • Example: >>> vp = session.viewports['Viewport: 1] >>> type(vp) >>> vp.__members__ ['activeColorModes', 'animationConnect', 'animationPlayer', … ] >>> vp.__methods__ ['Layer', 'bringToFront', 'disableMultipleColors', … ]
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.27
The Abaqus Object Model • Object model interrogation • Abaqus commands have a __doc__ string that can be accessed at run-time. • For example >>> from odbAccess import openOdb >>> print openOdb.__doc__ sys.modules['odbAccess'].openOdb(path) -> This method opens an existing output database (.odb) file and creates a new Odb object. You typically execute this method outside of Abaqus/CAE when, in most cases, only one output database is open at any time. For example, import odbAccess shockLoadOdb = odbAccess.openOdb(path='myOdb.odb') >>>
• Tab completion is available at the interactive prompt in Abaqus Python (not available in standard Python).
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Abaqus Types
Copyright 2007 Dassault Systèmes
L2.29
Abaqus Types • Abaqus extends Python with Abaqus-specific types. All the Python types are still available. • Repository (a keyed container) • Mapping type, like a dictionary. • Objects in a repository are of a similar type. • Repositories are typically used for models, parts, materials, etc. • Objects are added to a repository using a constructor. mdb.models['engine'].Material('steel') steel = mdb.models['engine'].materials['steel']
• Abaqus Array Types (indexed containers) • Sequence type, like a tuple. • For example, nodes and elements in meshes are stored in Abaqus in MeshNodeArrays and MeshElementArrays. Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.30
Abaqus Types • SymbolicConstant • Used as an argument to Abaqus methods and as member value in Abaqus objects. • SymbolicConstant variables are ALL_CAPS. • Examples: QUAD, SAX2T, RB2D2, DEFORMABLE, D_2D, DEFORMABLE_BODY a.setMeshControls(elemShape=QUAD)
• Boolean • Similar to a SymbolicConstant but has a value that can be tested. • Example: A viewport object has a Boolean member named titleBar that specifies if the title bar will be displayed. if vp.titleBar: print "The title bar will be displayed"
• Boolean will be phased out in future versions of Abaqus and replaced by Python bool. Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.31
Abaqus Types • Other Abaqus types • Currently there are about 280 different types. • Examples: Material, HomogeneousSolidSection type(mdb.models['Model-1'].materials['Steel'])
• Note: To test for a specific type, use the Type Object: s = mdb.models['Model-1'].sections['sec-1'] ... ... if type(s) == HomogeneousSolidSection: print 'This object is of type HomogeneousSolidSection'
• Type objects can be found in the appropriate module. i.e. from section import HomogeneousSolidSection
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.32
Abaqus Types • Keywords • Methods on Abaqus objects accept keyword arguments. • Example: Change model shape on which contours are plotted. vp = session.viewports['Viewport: 1'] vp.odbDisplay.display.setValues(plotState=(CONTOURS_ON_UNDEF, ))
• We highly recommend that keyword arguments be used. • Deleting objects • Use the del statement to delete objects. • To delete the name vp from the current namespace del vp
• To delete the viewport named Viewport: 1 del session.viewports['Viewport: 1']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.33
Abaqus Types • Example: The section object >>> s = mdb.models['Model-1'].sections['sec-1'] >>> type(s) >>> s.__members__ ['material', 'name', 'thickness'] >>> s.__methods__ ['setValues'] >>> for member in s.__members__: ... print 's.%s = %s' % (member, getattr(s, member)) s.material = mat-1 s.name = sec-1 s.thickness = 1.0 >>> del mdb.models['Model-1'].sections['sec-1']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Abaqus Modules
Copyright 2007 Dassault Systèmes
L2.35
Abaqus Modules Kernel Module
Functionality
part
Creating and modifying parts
material
Creating and modifying materials
section
Creating and modifying sections
assembly
Creating and modifying assemblies
step
Creating and modifying steps
interaction
Creating and modifying interactions
load
Creating and modifying loads and boundary conditions
mesh
Meshing part instances
job
Creating, submitting, and monitoring jobs
visualization
Visualizing results
odbAccess
Accessing the output database file
sketch
Creating and modifying sketches
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.36
Abaqus Modules • Importing a module • Modules are imported using the import statement, the same as any other Python module. • Abaqus imports all the modules using the module caeModules: from caeModules import *
• Importing a kernel module has no effect on the Abaqus GUI.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Setting Abaqus Defaults
Copyright 2007 Dassault Systèmes
L2.38
Setting Abaqus Defaults • The Abaqus Environment File • The name of the file is abaqus_v6.env • This file is run when Abaqus starts. Uses Python/ASI syntax. • It can be used to set defaults for display options, etc. • It may contain some optional Python functions that are called by Abaqus, such as: onCaeStartup() onCaeGraphicsStartup() onJobStartup() onJobCompletion()
• Abaqus looks for a file named abaqus_v6.env in site_dir, home_dir, and local_dir and will execute each one in turn. • If more than one version of the above Python functions is found, each one will be called. In the case of environment variables, a subsequent definition will overwrite a former definition. Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.39
Setting Abaqus Defaults
• Abaqus environment file: abaqus_v6.env def onCaeStartup(): # Compatibility issues backwardCompatibility.setValues(includeDeprecated=OFF) # Graphics preferences session.graphicsOptions.setValues(displayLists=ON, dragMode=AS_IS) # Print preferences session.printOptions.setValues(vpDecorations=OFF, vpBackground=OFF, rendition=COLOR, printCommand='lpr') # Visualization preferences def setVisPreferences(module, userData): from visualization import SHADED, EXTERIOR, CONTINUOUS session.defaultOdbDisplay.commonOptions.setValues( renderStyle=SHADED, visibleEdges=EXTERIOR) session.defaultOdbDisplay.contourOptions.setValues( contourStyle=CONTINUOUS) addImportCallback('visualization', setVisPreferences) # Material properties - read them from a file execfile('my_material_library.py') Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.40
Setting Abaqus Defaults abaqus_v6.env (continued) Certain variables are predefined in onJobCompletion and onJobStartup. These include: savedir, id, scrdir, analysisType, applicationName, abaqus_version. def onJobCompletion(): import os extensions = ('res','stt','mdl','prt','abq','pac') restartDir = savedir + id + '_restart' + os.sep if (not os.path.exists(restartDir)): os.mkdir(restartDir) for extension in extensions: fileName = id + '.' + extension if (os.path.exists(savedir + fileName)): os.rename(savedir + fileName, restartDir + fileName) def onJobStartup(): import os, osutils restartDir = savedir + id + '_restart' if (os.path.exists(restartDir)): osutils.removeTree(restartDir)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.41
Setting Abaqus Defaults • Execution environment
• Note that abaqus_v6.env is not a module, and names defined at the top level are not available within the functions. The functions are defined by reading abaqus_v6.env, but are executed in a different namespace. • Predefined names
• In the onCaeStartup function, you may omit the lines from abaqus import * from abaqusConstants import *
• To find all variables in the namespace, do the following: for name in globals().keys(): if name != '__builtins__': print '%s = %s' % (name , eval(name)) (this code be used at top level or within one of the functions)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Getting Interactive Input
Copyright 2007 Dassault Systèmes
L2.43
Getting Interactive Input • The getInput function displays a simple dialog box with a specified label and a single text field in which the user enters the requested value or values. • The getInputs function displays a simple dialog box with multiple label/text field pairs. • The values are returned to the executing script as strings after the user presses the [Enter] key or clicks OK. • Optionally, you can specify a default value to be displayed in a text field in the dialog box. • The getInput and getInputs functions do not provide any error checking; it is the script author's responsibility to verify the user input. • The Abaqus GUI must be running to use getInput or getInputs . • The getInput functions may not be used with -start or -script.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.44
Getting Interactive Input • Example The getInput function allows the user to enter a value: from abaqus import * from math import sqrt input = getInput('Enter a number', '9') number = float(input) print sqrt(number)
• The float function converts the string returned by getInput into a floating point number. • The getInputs function will get several values. x = getInputs((('Enter first', '1'), ('Enter second', '2'), ('Enter third', '3'))) print x
• A list is returned:
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Examples
Copyright 2007 Dassault Systèmes
L2.46
Example 2-1: Multiple Viewport Create and Tile • Create an array of viewports. The scr_viewport_tiler.py script defines two functions: createViewports() tileViewports()
The createViewports() function creates the specified number of viewports. The tileViewports() function arranges the viewports based on the the number of user-specified rows. Both functions are accessible at the command line interface (CLI). Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Viewport widths and heights are automatically calculated by the script to fit inside the drawing area.
L2.47
Example 2-2: “A” Shaped Part • Create a part in the form of the letter A. 1 Import modules and create the mdb object. from abaqus import * from abaqusConstants import * from caeModules import * Mdb()
This constructor creates the mdb object
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.48
Example 2-2: “A” Shaped Part 2
Draw a two-dimensional sketch. myModel = mdb.Model(name='Model A') mySketch = myModel.ConstrainedSketch( name='Sketch A', sheetSize=200.0) xyCoordsInner = ((-5 , 20), (5, 20), (15, 0), (-15, 0), (-5, 20)) xyCoordsOuter = ((-10, 30), (10, 30), (40, -30), (30, -30), (20, -10), (-20, -10), (-30, -30), (-40, -30), (-10, 30)) for i in range(len(xyCoordsInner)-1): mySketch.Line(point1=xyCoordsInner[i], point2=xyCoordsInner[i+1]) for i in range(len(xyCoordsOuter)-1): mySketch.Line(point1=xyCoordsOuter[i], point2=xyCoordsOuter[i+1])
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.49
Example 2-2: “A” Shaped Part 3 Create a part, and add a base feature using the sketch. myPart = myModel.Part(name='Part A', dimensionality=THREE_D, type=DEFORMABLE_BODY) myPart.BaseSolidExtrude(sketch=mySketch, depth=20.0)
4 Instance the part in the root assembly. myAssembly = mdb.models['Model A'].rootAssembly myInstance = myAssembly.Instance(name='Part A-1', part=myPart, dependent=OFF)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.50
Example 2-2: “A” Shaped Part 5 Mesh the instance. partInstances = (myInstance,) myAssembly.seedPartInstance( regions=partInstances, size=5.0) myAssembly.generateMesh(regions=partInstances)
6 Plot the meshed instance in a new viewport. myViewport = session.Viewport(name='Viewport for Model A', origin=(20, 20), width=150, height=100) myViewport.assemblyDisplay.setValues(renderStyle=SHADED, mesh=ON) myViewport.setValues(displayedObject=myAssembly)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.51
Example 2-3: Parameter Study Example • Implementation of Abaqus Benchmark Problem 2.3.4: Skew sensitivity of shell elements
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Workshops
Copyright 2007 Dassault Systèmes
L2.53
Workshop 2-1: Session Commands 1. Examine the documentation for the canvas commands. 2. Write a script that defines a function that takes an ODB name as an argument and creates a layout of four viewports with the following views: Top, Left, Front, and Iso.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L2.54
Workshop 2-2: Macro to Create a Library 1. Record a macro using Abaqus/CAE that adds material definitions to the model for Steel, Copper, and Aluminum. 2. Edit the macro you just created in the abaqusMacros.py file so that it prompts the user for the name of the model to which to add the Steel, Copper, and Aluminum materials.
3.
Run the macro in a new Abaqus/CAE session, then demonstrate that the materials were created by examining the Material Manager in the Property GUI module.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Specialized Postprocessing
Lecture 3
Copyright 2007 Dassault Systèmes
L3.2
Overview • The Abaqus Output Database • Automating Postprocessing Tasks • Postprocessing External Data • Examples • Workshop
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
The Abaqus Output Database
Copyright 2007 Dassault Systèmes
L3.4
The Abaqus Output Database • A portion of the Output Database object model: Model and result data
Field Data
History Data
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.5
The Abaqus Output Database • Opening an output database from odbAccess import * odb = session.openOdb(r'd:\smith\data\axle.odb')
• Step object • An Abaqus analysis contains a sequence of one or more analysis steps. • Each step is associated with an analysis procedure. • Accessing a step crushStep = odb.steps['Crush']
• Frame object • Each step contains a sequence of frames, where each increment of the analysis that resulted in output to the output database is called a frame. • In a frequency or buckling analysis each eigenmode is stored as a separate frame.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.6
The Abaqus Output Database • Accessing the last frame of crushStep crushFrame = crushStep.frames[-1]
• FieldOutput object • A FieldOutput object contains a “cloud of field values” (e.g., stress tensors at each integration point for all elements). • Each field value has much information (members) associated with it, for example: elementLabel, nodeLabel, position, face, integrationPoint, sectionPoint, type, data, magnitude, mises, tresca, press, inv3, maxPrincipal, midPrincipal, etc.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.7
The Abaqus Output Database • Accessing field output (stress) stress = crushFrame.fieldOutputs['S']
• One statement access to the stress results stress = odb.steps['Crush'].frames[-1].fieldOutputs['S'] Variable stress
Output database odb
Step named Crush
The last frame
Field output named S
• The field output named S in the last frame of the step named Crush in the output database odb is assigned to the variable stress.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.8
The Abaqus Output Database • Given a FieldOutput object, stress, it is easy to extract results for stressValue in stress.values: print stressValue.mises
• More specific results for a region of the model can be obtained using the getSubset method, which returns another FieldOutput object. • Arguments to getSubset() include position, sectionPoint, region, location, and localCoordSystem. • Possible values for the position argument to the getSubset command are INTEGRATION_POINT, NODAL, ELEMENT_NODAL, CENTROID. • Note: The .odb may contain a FieldOutput object that has values that are associated with more than one position. For example, stress may be saved at the integration points, centroids, and at the nodes.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.9
The Abaqus Output Database • Mathematical operations are supported for FieldOutput objects. • Performed on tensors and vectors. • Examples: stress1 + stress2 2.*stress
• Invariants are calculated after the operation. • All operands must be compatible, for example: • This will not work: stress + disp; an exception will be thrown. • INTEGRATION_POINT data cannot be combined with ELEMENT_NODAL data. • Operations are performed in the coordinate system that was used to save the data. • Operators include the following: +, -, *, /, abs(), acos(), asin(), atan(), cos(), degreeToRadian(), exp(), exp10(), log(), log10(), power(), radianToDegree(), sin(), sqrt(), tan()
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.10
The Abaqus Output Database • HistoryRegion object • The output from all history requests for a single point or for values calculated for a portion of the model as a whole (such as energy) is collected in a HistoryRegion object. • Depending on the type of output expected, the history region corresponds to one of the following: • A node • An integration point • A region • A material point
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.11
The Abaqus Output Database • HistoryRegion • A HistoryRegion refers to a specific point or region of the model • Accessing a history region endPoint = crushStep.historyRegions['end point']
• HistoryOutput object • A HistoryRegion object contains multiple HistoryOutput objects. A HistoryOutput object contains the output for the specific point or region for all time intervals in a step, for example ((t1, U21), (t2, U22), etc.). • Accessing history output u2Deflection = endPoint.historyOutputs['U2']
• Given a HistoryOutput object, u2Deflection, it is easy to extract results. for time, value in u2Deflection.data: print 'Time:', time, 'U2 deflection:', value Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.12
The Abaqus Output Database • Mathematical operations are supported for HistoryOutput objects. • Analogous to operations on FieldOutput objects • Example (calculate the magnitude of a vector quantity) mag = 0 componentLabels = ('U1', 'U2', 'U3') for label in componentLabels: mag = mag + power(endPoint.historyOutput[label], 2.) mag = sqrt(mag)
• Obviously, the operations apply to only the values, not the time.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.13
The Abaqus Output Database • A complete example (print displacement data for each node in a set) import odbAccess odb = session.openOdb('indentfoam_std_visco_2.odb') # Create a variable that refers to the last frame of the first step. lastFrame = odb.steps['Step-1'].frames[-1] # Create a variable that refers to the displacement 'U' in the last frame of the first step. displacement = lastFrame.fieldOutputs['U'] # Create a variable that refers to the node set 'PUNCH' located at the center of the # hemispherical punch. The set is associated with the part instance 'PART-1-1'. center = odb.rootAssembly.instances['PART-1-1'].nodeSets['PUNCH'] # Create a variable that refers to the displacement of the node set in the last frame of the # first step. centerDisplacement = displacement.getSubset(region=center)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.14
The Abaqus Output Database # Finally, print some field output data from each node in the node set # (a single node in this example). for v in centerDisplacement.values: print print print print print print
'Position = ', v.position 'Type = ', v.type 'Node label = ', v.nodeLabel 'X displacement = ', v.data[0] 'Y displacement = ', v.data[1] 'Displacement magnitude =', v.magnitude
odb.close()
Position = NODAL Type = VECTOR Node label = 1000 X displacement = -8.05730572321e-034 Y displacement = -76.4923706055 Displacement magnitude = 76.4923706055
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.15
The Abaqus Output Database • Output database pitfalls • Data cannot be deleted from the output database. • Workaround: Create a new .odb file, and write data that is copied from an existing .odb file. • Only one write-access client is permitted at a time. • The file is locked to prevent corruption. • Reading data from an output database is backward compatible. • Later versions of Abaqus will be able to read from earlier versions of the output database. • Writing data to an output database is not backward compatible. • Later versions of Abaqus will not be able to write to earlier versions of the output database.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Automating Postprocessing Tasks
Copyright 2007 Dassault Systèmes
L3.17
Automating Postprocessing Tasks • Automating postprocessing tasks involves writing scripts that access both the output database and the Abaqus Visualization module (in either Abaqus/CAE and Abaqus/Viewer). • To access the output database, use the odbAccess module. • To access visualization functionality, use the Visualization module.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.18
Automating Postprocessing Tasks • Visualization commands • Displaying an output database in a viewport: odb = session.openOdb('viewer_tutorial.odb') vp = session.viewports['Viewport: 1'] vp.setValues(displayedObject=odb)
• Plotting contours of PEEQ: od = vp.odbDisplay od.setPrimaryVariable(variableLabel='PEEQ', outputPosition=INTEGRATION_POINT) od.display.setValues(plotState=(CONTOURS_ON_DEF,))
• The OdbDisplay object vp.odbDisplay has the settings for how the output database is displayed in a viewport. • Opening output datbases using session.openOdb rather than just odbAccess.openOdb allows Abaqus/CAE to keep track of the open output databases.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.19
Automating Postprocessing Tasks • Annotation commands • Annotate the current plot. vp.plotAnnotation( mdb.Text(name='test run', offset=(70, 110), text= 'Test Run #146'))
• Print commands • Print the current viewport and annotation to a .png file. session.pngOptions.setValues(imageSize=(750, 400)) session.printOptions.setValues(rendition=COLOR, vpDecorations=OFF, vpBackground=OFF) session.printToFile(fileName='stress', format=PNG, canvasObjects=(vp,))
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.20
Automating Postprocessing Tasks • Putting it all together # A script to plot contours of the equivalent plastic strain on the deformed shape of the final # frame in an output database and save the image to a .png file:
import odbAccess from abaqus import * from abaqusConstants import * import visualization # Assign a variable to the ODB in the current viewport.
vp = session.viewports[session.currentViewportName] odb = vp.displayedObject # Change background color to white.
session.graphicsOptions.setValues(backgroundColor='#FFFFFF') # Make the last step and frame the current step and frame.
lastStepIndex = len(odb.steps)-1 lastFrameIndex = len(odb.steps.values()[-1].frames)-1 vp.odbDisplay.setFrame(step=lastStepIndex, frame=lastFrameIndex) Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.21
Automating Postprocessing Tasks # Plot contours of the equivalent plastic strain on the deformed shape.
vp.odbDisplay.setDeformedVariable('U') vp.odbDisplay.setPrimaryVariable(variableLabel='PEEQ', outputPosition=INTEGRATION_POINT) vp.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF,)) vp.view.fitView() # Replace the state block with a custom annotation.
vp.viewportAnnotationOptions.setValues(state=OFF) vp.plotAnnotation( mdb.Text(name='Text: 1', offset=(30, 8), text='Equivalent plastic strain at the final\ configuration')) # Print the current viewport and annotation to a .png file.
session.printOptions.setValues(rendition=COLOR, vpDecorations=OFF, vpBackground=OFF) session.printToFile(fileName='finalConfig', format=PNG, canvasObjects=(vp,))
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.22
Automating Postprocessing Tasks
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Postprocessing External Data
Copyright 2007 Dassault Systèmes
L3.24
Postprocessing External Data • External Data is data that is prepared outside Abaqus. • The example will show how to create and view an Odb object using the ASI Python commands. The Odb is saved to an ODB file. • Approach • Read external data from ASCII or binary file. • Write the data to an output database. • You can also read X–Y data directly and plot it without having to write it to an output database. • Creating an output database odb = Odb(name='myData', analysisTitle='derived data', description='test problem', path='testWrite.odb')
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.25
Postprocessing External Data • Creating parts myPart = odb.Part(name='My Part', embeddedSpace=THREE_D, type=DEFORMABLE_BODY)
• Adding nodes and elements to a part nodeData = (
(1, 1, 0, 0), (2, 2, 0, 0), (3, 2, 1, 0.1), (4, 1, 1, 0.1), (5, 2,-1,-0.1), (6, 1,-1,-0.1), )
myPart.addNodes(nodeData=nodeData, nodeSetName='nset-1') elementData = ((1, 1,2,3,4), (2, 6,5,2,1),) myPart.addElements(elementData=elementData, type='S4', elementSetName='eset-1')
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.26
Postprocessing External Data • Instance the part in the root assembly myInstance = odb.rootAssembly.Instance(name='My Instance', object=myPart)
• Creating a step myStep = odb.Step(name='My Step', description='', domain=TIME, timePeriod=1.0)
• Creating a frame myFrame = myStep.Frame(frameId=1, frameValue=0.1, description='')
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.27
Postprocessing External Data • Creating field output uField = myFrame.FieldOutput(name='U', description='Displacements', type=VECTOR)
• Adding result data to field output nodeLabels = (1, 2, 3, 4, 5, 6) nodeDisplacements = ( (1.0,2.0,3.0), (4.0,5.0,6.0), (7.0,8.0,9.0), (10.0,11.0,12.0), (13.0,14.0,15.0), (16.0,17.0,18.0) ) uField.addData(position=NODAL, instance=myInstance, labels=nodeLabels, data=nodeDisplacements)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Examples
Copyright 2007 Dassault Systèmes
L3.29
Example 3-1: Plotting External X–Y Data Data file and corresponding plot
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.30
Example 3-1: Plotting External X–Y Data
from visualization import XYData, USER_DEFINED def plotExternalData(fileName): # Extract the data from the file file = open(fileName) lines = file.readlines() pxy = lines[0].split(',') pxy = [x.strip() for x in pxy] plotName, xAxisTitle, yAxisTitle = pxy data = [] for line in lines[1:]: data.append(eval(line))
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.31
Example 3-1: Plotting External X–Y Data
# Create an XY Plot of the data xyData = session.XYData(plotName, data, fileName) curve = session.Curve(xyData) xyPlot = session.XYPlot(plotName) chart = xyPlot.charts.values()[0] chart.setValues(curvesToPlot=(plotName, )) chart.axes1[0].axisData.setValues(useSystemTitle=False, title=xAxisTitle) chart.axes2[0].axisData.setValues(useSystemTitle=False, title=yAxisTitle) # Display the XY Plot in the current viewport vp = session.viewports[session.currentViewportName] vp.setValues(displayedObject=xyPlot)
if __name__ == '__main__': plotExternalData('scr_xyplot.dat')
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.32
Example 3-2: Multiple Frames in One Plot
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.33
Example 3-2: Multiple Frames in One Plot
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.34
Example 3-3: Extreme Value Odb Query • Find the extreme value of some element field output Tasks: Search all frames of all steps for the extreme value of Mises stress. Print the location with respect to time and space to the message area. Identify the extreme element with a plot.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.35
Example 3-3: Extreme Value Odb Query from abaqus import * from abaqusConstants import * import visualization import displayGroupOdbToolset as dgo # Use the output database displayed in the current viewport vp = session.viewports[session.currentViewportName] odb = vp.displayedObject if type(odb) != visualization.OdbType: raise 'An odb must be displayed in the current viewport.' # Find the maximum von Mises stress maxValue = None stressOutputExists = FALSE for step in odb.steps.values(): print 'Processing step:', step.name for frame in step.frames: try: stress = frame.fieldOutputs['S'] stressOutputExists = TRUE except KeyError: # Skip frames with no stress output continue Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.36
Example 3-3: Extreme Value Odb Query for stressValue in stress.values: if (not maxValue or stressValue.mises > maxValue.mises): maxValue = stressValue maxStep, maxFrame = step, frame # Raise an error if there was no relevant output in the Odb if not stressOutputExists: raise 'This odb does not have stress output.' # Print the details of the max von Mises stress print 'Found maximum von Mises stress of %E in' % maxValue.mises print ' Step: ', maxStep.name print ' Frame: ', maxFrame.frameId print ' Instance: ', maxValue.instance.name print ' Element: ', maxValue.elementLabel print ' Section point: ', maxValue.sectionPoint print ' Integration point:', maxValue.integrationPoint
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.37
Example 3-3: Extreme Value Odb Query
#Color the element Red where the max von Mises stress occurs leaf = dgo.Leaf(ALL_SURFACES) vp.odbDisplay.displayGroup.remove(leaf) leaf = dgo.LeafFromElementLabels( partInstanceName=maxValue.instance.name, elementLabels=(maxValue.elementLabel,) ) vp.setColor(leaf=leaf, fillColor='Red') vp.odbDisplay.commonOptions.setValues( renderStyle=FILLED, elementShrink=ON, elementShrinkFactor=0.15) vp.odbDisplay.display.setValues(plotState=(UNDEFORMED,))
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.38
Example 3-4: Tube Deflection
• This optimization example: • Runs an Standard analysis on a cantilever beam with a tube section. • Reads the output from the analysis to find the deflection at the tip. • If the deflection is too much, the wall thickness is increased, and the beam analyzed again.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.39
Example 3-4: Tube Deflection from abaqus import * from abaqusConstants import * from scr_tubeFunctions import createBeam, initializeVp, showDeflection import odbAccess import visualization # only for display purposes thickness = 0.004 # m maxAllowableDeflection = 0.025 # m while 1: # loop until deflection is OK # Parameterized function that creates the tube part, # creates the assembly, applies boundary conditions, # and applies the loads createBeam(thickness) jobName = "Tube%03d"%(thickness*1000) mdb.Job(name=jobName, model='Model-1') mdb.jobs[jobName].submit() mdb.jobs[jobName].waitForCompletion() # wait for analysis to complete Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L3.40
Example 3-4: Tube Deflection # get the end deflection from the Output Batabase odb = visualization.openOdb(path=jobName+'.odb') endNode = odb.rootAssembly.instances['PART-1-1'].nodeSets['END NODE'] u = odb.steps['Step-1'].frames[-1].fieldOutputs['U'] u1 = u.getSubset(region=endNode) deflection = u1.values[0].data[1] odb.close() del odb # display the beam in the viewport and the CLI showDeflection(jobName, thickness, deflection) print 'deflection: %7.3f mm'%(deflection*1000) if abs(deflection) >> odb = openOdb('cantilever.odb') >>> odb.__members__ ['analysisTitle', 'closed', 'description', 'diagnosticData', 'isReadOnly', 'jobData', 'name', 'parts', 'path', 'rootAssembly', 'sectionCategories', 'sectorDefinition', 'steps', 'userData'] >>> odb.__methods__ ['Part', 'SectionCategory', 'Step', 'UserXYData', 'close', 'getFrame', 'save', 'update']
Use the print statement. The state of Abaqus objects can be printed using the print statement. For example: >>> print odb ({'analysisTitle': Cantilever beam model', 'closed': FALSE, 'description': 'DDB object', 'diagnosticData': 'OdbDiagnosticData object', 'isReadOnly': FALSE, 'jobData': 'JobData object', 'name': 'cantilever.odb', 'parts': 'Repository object', 'path': 'd:\temp\cantilever.odb', 'rootAssembly': 'OdbAssembly object', 'sectionCategories': 'Repository object', 'sectorDefinition': None, 'steps': 'Repository object', 'userData': 'UserData object'})
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.5
Exploring Your Data • prettyPrint function >>> from textRepr import * >>> prettyPrint(odb) ({'analysisTitle': 'Cantilever beam model', 'closed': FALSE, 'description': 'DDB object', 'diagnosticData': 'OdbDiagnosticData object', 'isReadOnly': FALSE, 'jobData': 'JobData object', 'name': 'cantilever.odb', 'parts': 'Repository object', 'path': 'd:\temp\cantilever.odb ', 'rootAssembly': 'OdbAssembly object', 'sectionCategories': 'Repository object', 'sectorDefinition': None, 'steps': 'Repository object', 'userData': 'UserData object'})
• By default, prints only one level deep; 2nd argument is depth. >>> prettyPrint(odb, maxRecursionDepth=2)
• Set default depth - affects textRepr functions and printing Abaqus objects. >>> session.textReprOptions.setValues(maxRecursionDepth=3)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.6
Exploring Your Data • More textRepr functions • Functions in the textRepr module: getIndentedRepr, getPaths, getTypes, prettyPrint, prettyPrintToFile, prettyPrintToFileName, prettyPrintToTerm, printPaths, printPathsToFile, printPathsToFileName, printPathsToTerm, printTypes
• Function signatures: prettyPrint(object ) printPaths(object ) printTypes(object ) printPathsToFileName(fileName, object )
• Note: optional arguments are shown within • Use __doc__ to check arguments Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.7
Exploring Your Data • printPaths >>> from odbAccess import * >>> from textRepr import * >>> odb = openOdb('cantilever.odb') >>> printPaths(odb, pathRoot='odb') odb.analysisTitle odb.closed odb.description odb.diagnosticData odb.isReadOnly odb.jobData odb.name odb.parts odb.path odb.rootAssembly odb.sectionCategories odb.sectorDefinition odb.steps odb.userData
• Show more data by increasing the depth >>> printPaths(odb, 2, pathRoot='odb')
. . . or selecting one of the members >>> printPaths(odb.steps['Step-1'], 2, pathRoot='step')
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.8
Exploring Your Data • getPaths • Returns a string that can be used for further processing >>> x = getPaths(odb.steps['Step-1'].frames[87].fieldOutputs, pathRoot='fieldOutputs') >>> print x fieldOutputs['S'] fieldOutputs['PE'] fieldOutputs['RF'] fieldOutputs['PEEQ'] fieldOutputs['LE'] fieldOutputs['PEMAG'] fieldOutputs['AC YIELD'] fieldOutputs['CF'] fieldOutputs['U'] >>> y = x.splitlines() >>> print y[3] fieldOutputs['PEEQ']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.9
Exploring Your Data • printTypes • Returns the type of each member >>> stress = odb.steps['Step-1'].frames[87].fieldOutputs['S'] >>> printTypes(stress, pathRoot='stress') tuple stress.componentLabels string stress.description FieldLocationArray stress.locations string stress.name SymbolicConstant stress.type tuple stress.validInvariants FieldValueArray stress.values
• Print the value of each member using getPaths() and eval(path) for path in getPaths(obj).splitlines(): print '%-20s %s' % (eval(path), path)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Abaqus Architecture
Copyright 2007 Dassault Systèmes
L4.11
Abaqus Architecture • Abaqus has three processes: kernel, GUI, and analysis.
Abaqus/CAE Abaqus/CAE kernel kernel
Input file
Python Python interpreter interpreter
WIP messages ODB files
Abaqus Abaqus analysis analysis
Replay Replay file file
Commands
Update messages
Kernel Kernel script script
Abaqus Abaqus GUI GUI Command Command line line interpreter interpreter Python Python interpreter interpreter
GUI GUI script script
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.12
Abaqus Architecture • Kernel commands • The GUI and Command Line Interpreter execute commands in different namespaces of the kernel interpreter. This avoids a user overwriting a variable required by the application. • A kernel script uses the same namespace as the Command Line Interpreter. • Abaqus analysis messages • Messages from the Abaqus analysis are processed using the Job Monitoring API. • GUI script • The Abaqus GUI uses an internal Python interpreter. This is not exposed to the user but can be used for GUI customization.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Job Monitoring
Copyright 2007 Dassault Systèmes
L4.14
Job Monitoring • What is job monitoring? • Receiving messages from the analysis process while it is executing. • Responding to messages from jobs • In some cases you may want to process messages from the analysis while it is running; for example, to terminate it when a criterion is reached or to plot results as the analysis progresses. • This is accomplished by writing a callback function and registering it with the monitorManager object.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.15
Job Monitoring • Example • The following code will print all the messages from the analysis: from abaqus import * from jobMessage import ANY_JOB, ANY_MESSAGE_TYPE # define a callback function
def printMessages(jobName, mType, data, userData): print 'Job name: %s, Message type: %s'%(jobName, mType) print 'data members:' members = dir(data) format = ' %-18s %s' print format%('member', 'value') for member in members: memberValue = getattr(data, member) print format%(member, memberValue) # call the function for all jobs, and all message types
monitorManager.addMessageCallback(ANY_JOB, ANY_MESSAGE_TYPE, printMessages, None) Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.16
Job Monitoring • Waiting for jobs to complete • The easiest way to write scripts that perform some action (i.e., change the model, visualize results) based on the results of the analysis is to have the script wait for the analysis to complete. • In the following example, the script submits myJob1 and waits for it to complete before submitting myJob2. myJob1 = mdb.Job(name='Job-1', model='Model-1') myJob2 = mdb.Job(name='Job-2', model='Model-2') myJob1.submit() myJob1.waitForCompletion() myJob2.submit() myJob2.waitForCompletion()
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Custom Data
Copyright 2007 Dassault Systèmes
L4.18
CAE Custom Data • mdb.customData • User specified data, using Python objects or user specified classes • Persistent (saved to .cae file) • Lazy evaluation, on import customKernel i.e. >>> mdb.customData AttributeError: 'Mdb' object has no attribute 'customData' >>> import customKernel >>> mdb.customData mdb.customData
• Adding data is simple, i.e. >>> mdb.customData.myDict = {}
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.19
CAE Custom Data • mdb.customData (continued) • Data can be managed like Abaqus data by using the Repository method to map constructor to repository. In this case: • New objects are put into the specified repository • Objects have ASI style paths in the object model • Managed repositories are read only • Example: >>> from myModule import Axle >>> mdb.customData.Repository(name='axles', constructor=Axle) >>> mdb.customData.Axle(name='Axle-1', ... ) mdb.customData.axles['Axle-1']
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.20
CAE Custom Data • mdb.customData (continued) • Custom Data is saved using the Python module pickle • Side effect is that you can only save objects that Python can pickle (i.e. not Abaqus objects) • If special classes are used to create data, these classes can be pickled, but the modules containing the class definitions must be available when unpickling the data.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Abaqus/CAE Plug-ins
Copyright 2007 Dassault Systèmes
L4.22
Abaqus/CAE Plug-ins • A Plug-in is a simple way of customizing the Abaqus/CAE GUI • Two kinds of Plug-ins • Kernel plug-in • GUI plug-in (we will not discuss GUI plug-ins) • A plug-in registration file must have a name ending in _plugins.py • Abaqus/CAE searches for plug-in registration files in • abaqus/abaqus_plugins, where abaqus is the Abaqus parent directory. • home/abaqus_plugins, where home is your home directory. • current/abaqus_plugins, where current is the current directory. • You can also use the plugin_central_dir variable in abaqus_v6.env plugin_central_dir = r'\\fileServer\sharedDirectory'
• A plug-in must register itself to appear in the Abaqus/CAE Plug-ins menu • A kernel plug-in executes a function in a module that you specify.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.23
Abaqus/CAE Plug-ins • Example • myUtils.py def printTime(): import time t = time.localtime() print 'The time is: %d:%d' %d/%d/%d' % \ (t[3], t[4], t[1], t[2], t[0])
• time_plugin.py from abaqusGui import getAFXApp toolset = getAFXApp().getAFXMainWindow().getPluginToolset() toolset.registerKernelMenuButton(moduleName='myUtils', functionName='printTime()', buttonText='Print Time')
• The above files are placed in a directory named abaqus_plugins
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.24
Abaqus/CAE Plug-ins • Example (continued) • The previous example results in adding a button to the top-level Plug-ins menu. • myUtils.py must exist and contain a function named printTime and
both must be in a directory tree starting at abaqus_plugins located as described above.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Debugging Scripts
Copyright 2007 Dassault Systèmes
L4.26
Debugging Scripts • Debugging methods • Tracebacks • Exceptions and asserts • Print statements • PyChecker • Python Debugger • Write a test function • Replay File Utility • Use an IDE
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.27
Debugging Scripts • Tracebacks • Python tracebacks are a good debugging tool. • Example: File "testTraceback.py", line 3, in ? a() File ".\aTest.py", line 4, in a b() File ".\bTest.py", line 2, in b 1/0 ZeroDivisionError: integer division or modulo by zero
• The traceback clearly describes the location in the code (file, line number, and function name) and the type of error. • Exceptions • Raise an exception to indicate some type of error. if not myDict.has_key(key): raise KeyError, 'myDict does not have key: %s' % key
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.28
Debugging Scripts • Print statements • Use print statements to examine the state of objects at strategic points in your script. def myFunc(a, b): print 'arg a:', a, 'arg b:', b ...
• Abaqus Objects display their state when printed. print session.viewport['Viewport: 1'] ... 'border': ON, 'titleBar': ON, 'name': 'Viewport: 1' ...
• PyChecker • The PyChecker module does a static check on Python code. >>> from pychecker import checker >>> import myUtilities
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.29
Debugging Scripts • The Python Debugger • Python provides a debugger, the pdb module. >>> import pdb >>> import mymodule >>> pdb.run('mymodule.test()') > (0)?() (Pdb) continue > (1)?() (Pdb) continue NameError: 'spam' > (1)?() (Pdb)
• Can move up and down the stack, inspect variables, etc. (Pdb) ? EOF break cont enable list quit tbreak whatis
a c continue h n r u where
alias cl d help next return unalias
args clear disable ignore p s up
b condition down l q step w
• The pdb module is documented in the Python Library Reference.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.30
Debugging Scripts • Test function • Determine how your code is meant to work, and write a test function to test it. • PyUnit provides a testing framework for writing and running unit tests: pyunit.sourceforge.net
• Defines a TestCase class that will setup the test problem, run it, and report errors. You derive your own class from TestCase to test your problem. • Can be used to run large test suites.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.31
Debugging Scripts • Integrated Development Environment (IDE) • Testing an algorithm in a separate Integrated Development Environment, such as PythonWin, WingIDE, IDLE, or Komodo, can make the debugging easier. • A typical IDE provides a text editor (syntax coloring, block folding, method tips), debugger, project manager, keyboard shortcuts, toolbars, regular expression debugger, etc. • When the code works correctly, try it in Abaqus/CAE. • Note: No IDEs are delivered with Abaqus, but they are available on the Internet. Some are free, some allow a trial period.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.32
Debugging Scripts • IDE examples IDLE
Komodo Pythonwin
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Object-Oriented Programming
Copyright 2007 Dassault Systèmes
L4.34
Object-Oriented Programming • Object-Oriented Programming (OOP) • In a nutshell, OOP is a programming methodology that facilitates writing modular, reusable code. • In Python object-oriented programming is supported but not imposed. • As you get more experienced programming Abaqus, learning the objectoriented features of Python can help you write better code.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.35
Object-Oriented Programming • Definitions Object
A run-time entity that packages both data and the procedures that operate on that data. • In Python the data and procedures are called members and methods, respectively. • members and methods are both attributes of the object.
An object is an instance of a class or type. (A Python class is implemented in Python, a Python type is implemented in C.) Class
A class defines the data and procedures that operate on that data.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.36
Object-Oriented Programming • Definitions Encapsulation
The result of hiding a representation and implementation in an object. The representation is not visible and cannot be accessed directly from outside the object. Operations are the only way to access and modify an object's representation. (Note: Python does not hide the data of a class instance.)
All definitions taken from Design Patterns: Elements of Reusable Object-Oriented Software, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison-Wesley, 1995
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.37
Object-Oriented Programming •Class example • The Square class draws a square of a specific size and color. class Square: def __init__(self, size): self.size = size self.color = 'Red' # Set the default color to 'Red' def setColor(self, color): self.color = color def draw(self): s = self.size * 0.5 drawLine(-s, -s, s, -s) drawLine( s, -s, s, s) drawLine( s, s, -s, s) drawLine(-s, s, -s, -s) >>> sq = Square(5) >>> sq.size 5.0 >>> sq.color 'Red' >>> sq.setColor('Blue') >>> sq.draw()
Note: The code that imports the drawline function from another module is not shown here for brevity.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.38
Object-Oriented Programming Inheritance
A relationship that defines one entity in terms of another. Class inheritance defines a new class in terms of one or more parent classes. The new class inherits its interface and implementation from its parents. The new class is called a subclass or a derived class.
Generalized class
Animal
Example of an animal class hierarchy intended to demonstrate class inheritance
Mammal Cat
Dog
Specialized class
Abaqus user A Cat IsA Mammal IsA Animal
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Primate
L4.39
Object-Oriented Programming Interface
The set of all signatures defined by an object's operations. The interface describes the set of requests to which an object can respond. The members, methods and their arguments, and operators defined in the Abaqus Scripting Manual for each Abaqus object are the object's interface. A base class may define an interface that can be implemented differently in each derived class. A collection of objects of the same base type can then be used as if they are the same. This is called polymorphism. An abstract base class is one whose interface is not fully implemented in the class. Such a class should not be instantiated, and the interface must be implemented in each derived class.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.40
Object-Oriented Programming Polymorphism
The ability to substitute objects of matching interface for one another at run time.
def refreshCanvas():
Drawing primitive Triangle
Circle
for dp in drawingPrimitives: dp.draw()
Square
In the example the DrawingPrimitive class has an interface method draw that is implemented differently in each derived class. In the following code DrawingPrimitive objects have a default color 'Red', which can be changed using a base class method.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.41
Object-Oriented Programming • Polymorphism example class DrawingPrimitive: def __init__(self): self.color = 'Red' # Set the default color to 'Red' def setColor(self, color): self.color = color # color is set using base class method def draw(self): # abstract base class - cannot draw raise RuntimeError, 'draw method not implemented' class Square(DrawingPrimitive): def __init__(self, size): DrawingPrimitive.__init__(self) # init base class self.size = float(size) def draw(self): # override base class draw method s = self.size * 0.5 drawLine(-s, -s, s, -s) drawLine( s, -s, s, s) drawLine( s, s, -s, s) drawLine(-s, s, -s, -s)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.42
Object-Oriented Programming • Test a square >>> sq = Square(5) >>> sq.size 5.0 >>> sq.color 'Red' >>> sq.setColor('Blue') >>> sq.color 'Blue' >>> sq.draw()
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Python Classes
Copyright 2007 Dassault Systèmes
L4.44
Python Classes • Simple class • Use the class keyword to define a new class. >>> class Plain: # define a class ... pass ...
• Calling the class name as a function creates an instance of the class. >>> a = Plain()
# create an instance of class Plain
• Members can be added dynamically. >>> a.x = 1.0 # add members to the instance >>> a.y = 2.0 >>> a.description = 'First Point'
• Print it—more on this later. >>> print a # print the string value of the instance
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.45
Python Classes • Magic methods • . . . are defined by Python, and have double underscore at each end >>> class Simple: ... def __init__(self, arg): ... self.arg = arg # preferred way of adding members ... def __str__(self): # called by print or str(x) ... return self.arg ...
– __init__ is called when the instance is created >>> b = Simple('Point X')
– __str__ is called by Python print or str(b) >>> print b Point X
• Other magic methods are used by Python to compare instances, operate on instances using +, -, /, *, or to make the object indexable, or callable.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.46
Python Classes • Get details of square instance – Get the attributes of the instance. >>> dir(sq) # list the attributes of sq (incl class attrs) ['__doc__', '__init__', '__module__', 'color', 'draw', 'setColor', 'size'] >>> sq.__dict__ # attribute values are stored in __dict__ {'size': 5.0, 'color': 'Blue'}
– Get the attributes of the class. Usually methods. >>> dir(sq.__class__) ['__doc__', '__init__', '__module__', 'draw', 'setColor']
• Get the type. >>> type(sq) # all instances have type 'instance'
• To find the class, need the __class__ attribute. >>> sq.__class__ # __class__ contains the class object >>> sq.__class__.__name__ # get the class name 'Square'
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.47
Python Classes • More magic methods –The __repr__ and
__setattr__ methods
>>> class Spam(Simple): ... locked = 0 ... def __init__(self, arg): ... self.description = arg ... self.locked = 1 ... def __repr__(self): # used to re-create the object ... s = "Spam('%s')"%self.description ... return s ... def __setattr__(self, arg, value): ... if self.locked: ... raise TypeError, 'object is read-only' ... self.__dict__[arg] = value ... >>> c = Spam('Point 1') >>> c Spam('Point 1') >>> c.x = 2.1 Traceback (most recent call last): File "", line 1, in ? File "spam.py", line 11, in __setattr__ raise TypeError, 'object is read-only' TypeError: object is read-only Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.48
Python Classes • ... and more __getattr__ __setattr__ __getitem__ __setitem__ __len__ __nonzero__ __cmp__ __call__ __add__ __sub__ __mul__ __div__ (__iadd__ etc) __lt__ __le__ __eq__ __ne__ __ge__ __gt__
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.49
Python Classes • Guidelines for Abaqus work: • Add members in __init __ only. • Read the style guide. • Abaqus Answer 2483
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Example
Copyright 2007 Dassault Systèmes
L4.51
Example • Extrusion example from part import THREE_D, DEFORMABLE_BODY class Extrusion: """abstract base class Extrusion. Objects are centered at origin""" def __init__(self, model, name, depth): if self.__class__.__name__ == 'Extrusion': raise TypeError, "Extrusion is abstract base class" self.model = model self.name = name self.depth = depth self.sketch = self.model.ConstrainedSketch(name=name, sheetSize=200.0) def createPartUsingSketch(self): self.part = self.model.Part(name=self.name, dimensionality=THREE_D, type=DEFORMABLE_BODY) self.part.BaseSolidExtrude(sketch=self.sketch, depth=self.depth) session.viewports[session.currentViewportName].\ setValues(displayedObject=self.part) def getVolume(self): raise TypeError, "getVolume not implemented" def printSummary(self): raise TypeError, "printSummary not implemented"
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.52
Example
class Block(Extrusion): """Block(model, name, width, height, depth)""" def __init__(self, model, name, width, height, depth): Extrusion.__init__(self, model, name, depth) self.width = width self.height = height self.sketch.rectangle(point1=(-width/2,-height/2), point2=(width/2,height/2)) self.createPartUsingSketch() def getVolume(self): return self.width * self.height * self.depth def printSummary(self): print 'Block object:' print 'width=%d, height=%d, depth=%d'%\ (self.width, self.height, self.depth)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.53
Example
class Cylinder(Extrusion): """Cylinder(model, name, radius, depth)""" def __init__(self, model, name, radius, depth): Extrusion.__init__(self, model, name, depth) self.radius = radius self.sketch.CircleByCenterPerimeter(center=(0.0, 0.0), point1=(0.0, radius)) self.createPartUsingSketch() def getVolume(self): import math return math.pi * self.radius ** 2 * self.depth def printSummary(self): print 'Cylinder object:' print 'radius=%d'%(self.radius)
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
L4.54
Example • Running the script >>> execfile('extrusionDemo.py') Part module loaded >>> m = mdb.models['Model-1'] >>> b = Block(m, 20, 30, 100) #* exceptions.TypeError: not enough arguments; expected 6, got 5 >>> Block.__doc__ 'Block(model, name, width, height, depth)' >>> b = Block(m, 'BLK', 20, 30, 100) >>> c = Cylinder(m, 'CYL', 30, 100) >>> c.printSummary() Cylinder object: radius=30 >>> b.printSummary() Block object: width=20, height=30, depth=100 >>> b.getVolume() 60000 >>> c.getVolume() 282743.338823
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Workshop
Copyright 2007 Dassault Systèmes
L4.56
Workshop 4.1: Job monitoring • The input file rubberDome.inp includes a request to monitor the vertical (U2) displacement at node 52 at the top of the part. •
Write a script that creates and runs the rubberDome job and prints the time and value of the data sent by the MONITOR_DATA message.
•
Modify the monitorDataValue callback function to stop the analysis when the U2 displacement at node 52 reaches −2.0.
Introduction to Python and Scripting in Abaqus Copyright 2007 Dassault Systèmes
Workshop Preliminaries Setting up the workshop directories and files If you are taking a public seminar, the steps in the following section have already been done for you: skip to Basic Operating System Commands, (p. WP.2). If everyone in your group is familiar with the operating system, skip directly to the workshops. The workshop files are included on the Abaqus release CD. If you have problems finding the files or setting up the directories, ask your systems manager for help. Note for systems managers: If you are setting up these directories and files for someone else, please make sure that there are appropriate privileges on the directories and files so that the user can write to the files and create new files in the directories. Workshop file setup (Note: UNIX is case-sensitive. Therefore, lowercase and uppercase letters must be typed as they are shown or listed.) 1. Find out where the Abaqus release is installed by typing UNIX and Windows NT: abqxxx whereami where abqxxx is the name of the Abaqus execution procedure on your system. It can be defined to have a different name. For example, the command for the 6.7–1 version might be aliased to abq671. This command will give the full path to the directory where Abaqus is installed, referred to here as abaqus_dir. 2. Extract all the workshop files from the course tar file by typing UNIX: abqxxx perl abaqus_dir/samples/course_setup.pl Windows NT: abqxxx perl abaqus_dir\samples\course_setup.pl Note that if you have Perl and the compilers already installed on your machine, you may simply type: UNIX: abaqus_dir/samples/course_setup.pl Windows NT: abaqus_dir\samples\course_setup.pl 3. The script will install the files into the current working directory. You will be asked to verify this and to choose which files you wish to install. Choose “y” for the appropriate lecture series when prompted. Once you have selected the lecture series, type “q” to skip the remaining lectures and to proceed with the installation of the chosen workshops.
Copyright 2007 Dassault Systèmes
Preliminaries for Abaqus Workshops
WP.2
Basic operating system commands (You can skip this section and go directly to the workshops if everyone in your group is familiar with the operating system.) Note: The following commands are limited to those necessary for doing the workshop exercises. Working with directories 1. Start in the current working directory. List the directory contents by typing UNIX: ls Windows NT:
dir
Both subdirectories and files will be listed. On some systems the file type (directory, executable, etc.) will be indicated by a symbol. 2. Change directories to a workshop subdirectory by typing Both UNIX and Windows NT: cd dir_name 3. To list with a long format showing sizes, dates, and file, type UNIX: ls -l Windows NT:
dir
4. Return to your home directory: UNIX: cd Windows NT: cd home-dir List the directory contents to verify that you are back in your home directory. 5. Change to the workshop subdirectory again. 6. The * is a wildcard character and can be used to do a partial listing. For example, list only Abaqus input files by typing UNIX: ls *.inp Windows NT: dir *.inp Working with files Use one of these files, filename.inp, to perform the following tasks: 1. Copy filename.inp to a file with the name newcopy.inp by typing UNIX:
cp filename.inp newcopy.inp
Windows NT: copy filename.inp newcopy.inp 2. Rename (or move) this new file to newname.inp by typing UNIX: mv newcopy.inp newname.inp Windows NT: rename newcopy.inp newname.inp (Be careful when using cp and mv since UNIX will overwrite existing files without warning.)
Copyright 2007 Dassault Systèmes
Preliminaries for Abaqus Workshops
WP.3
3. Delete this file by typing UNIX: rm newname.inp Windows NT: erase newname.inp 4. View the contents of the files filename.inp by typing UNIX: Windows NT:
more filename.inp type filename.inp | more
This step will scroll through the file one page at a time. Now you are ready to start the workshops.
Copyright 2007 Dassault Systèmes
Preliminaries for Abaqus Workshops
Workshop 1.1 Output the Fibonacci Series Goals When you complete this workshop, you will be able to: • Use a loop, test operators. • Create a Python function.
Task 1 Print the Fibonacci series up to 10,000.
Task 2 Create a function that prints the Fibonacci series between any two (possibly large) numbers.
Other information •
The Fibonacci series is formed by starting with 0 and 1 and then adding the last two numbers to get the next one: 0, 1, 1, 2, 3, 5, 8, 13, … For example, 0 1 (the series starts like this) 0 + 1 = 1 So the series is now 0 1 1 1 + 1 = 2 The series continues... 0 1 1 2 and the next term is 1 + 2 = 3 So we now have 0 1 1 2 3 and it continues... Mathematically, the series is defined as kn = kn-1 + kn-2
Copyright 2007 Dassault Systèmes
with k0=0 and k1=1
Introduction to Python and Scripting in Abaqus
Workshop Answers 1.1 Output the Fibonacci Series Task 1 Print the Fibonacci series up to 10,000.
Answers In the interpreter, type the following: def fib(toNum=10000): a, b = 0, 1 print a, b, while 1: c = a + b if c >= toNum: break print c, a, b = b, c ... ... 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Task 2 Create a function that prints the Fibonacci series between any two (possibly large) numbers.
Answers The following code can be entered into the interpreter or into a text file: def fib(fromNum, toNum): a, b = 0, 1 c = a + b if c > fromNum: print a, b, while 1: c = a + b if c >= toNum: break if c > fromNum: print c, a, b = b, c
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop 1.2 Circle Module Goals When you complete this workshop, you will be able to: • Import a module. • Write a Python script. • Use the string formatting operations.
Task 1 Write a module named circle containing two functions: one that returns the circumference of a circle, given the radius, and one that returns the area of a circle, given the radius.
Task 2 Write a script that imports the circle module and uses it to print the circumference and area of circles with the following radii: (5, 6, 7, 8, and 9). The results should be formatted into a table as follows: radius
circumference
area
5.00
31.416
78.5398
6.00
37.699
113.0973
7.00
43.982
153.9380
8.00
50.265
201.0619
9.00
56.549
254.4690
Other information Use the math module for PI. The formatting can be done using the print statement and the string formatting operators (%s etc.).
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop Answers 1.2 Circle Module Task 1 Write a module named circle containing two functions: one that returns the circumference of a circle, given the radius, and one that returns the area of a circle, given the radius.
Answers import math def circumf(radius): return 2 * math.pi * radius def area(radius): return math.pi * radius ** 2
Task 2 Write a script that imports the circle module and uses it to print the circumference and area of circles with the following radii: (5, 6, 7, 8, and 9). The results should be formatted into a table as follows: radius
circumference
area
5.00
31.416
78.5398
6.00
37.699
113.0973
7.00
43.982
153.9380
8.00
50.265
201.0619
9.00
56.549
254.4690
Answers import circle r
= (5, 6, 7, 8, 9)
print " %-6s %-12s %-12s"%(’radius’, ’circumference’, ’area’) for radius in r: print "%6.2f %12.3f %12.4f"%(radius, circle.circumf(radius), circle.area(radius))
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop 2.1 Session Commands Goals When you complete this workshop, you will be able to: • Navigate the Abaqus Scripting Manual • Manipulate an object in the viewport using a script.
Task Examine the documentation for the canvas commands, then write a script to create a function that takes an output database name as an argument and creates a layout of four viewports with the following views of the output database: 'Top', 'Left', 'Front', and 'Iso'. You will use the following commands in your script: session.openOdb(...) session.Viewport(...) session.Viewport.setValues(...) session.Viewport.view.setValues(...)
Other information The following code is an example of applying a predefined ISO view to an existing viewport: isoView = session.views['Iso'] vp = session.viewports['Viewport: 1'] vp.view.setValues(isoView)
The following code is an example of how to open and display an output database in a viewport: odb = session.openOdb('beam3d.odb') vp = session.viewports['Viewport: 1'] vp.setValues(displayedObject=odb)
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop Answers 2.1 Session Commands Task Examine the documentation for the session commands, then write a script to create a function that takes an ODB name as an argument and creates a layout of four viewports with the following views: 'Top', 'Left', 'Front', and 'Iso'.
Answers from abaqus import * from abaqusConstants import * import visualization def cannedLayout(odbPath): width, height, margin = 90, 60, 2 data = ( (margin, margin*20, (margin*2+width, margin*20, (margin, margin*22+height, (margin*2+width, margin*22+height, ) odb = session.openOdb(odbPath)
'Front'), 'Top'), 'Left'), 'Iso'),
for x, y, view in data: vp = session.Viewport(name=view, origin=(x, y), width=width, height=height) vp.setValues(displayedObject=odb) vp.view.setValues(session.views[view])
Example of command used to call the above: cannedLayout('beam3d.odb')
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop 2.2 A Macro to Create a Library of Materials Goals When you complete this workshop, you will be able to: • Use the getInput function. • Understand the abaqusMacros.py file.
Task Create a macro that prompts the user for the name of the model and adds three materials, in SI units, to the model.
Other information 1. Start Abaqus/CAE. 2. Open the Macro Manager (File→Macro Manager). 3. Create a macro named add_SI_Materials. 4. Switch to the Property module, and use the Material Manager to create three materials with the following properties: Steel. Young's Modulus Poisson's ratio Density Yield Stress, Plastic Strain
200 E 9 0.3 7800 400 E 6, 0.00 420 E 6, 0.02 500 E 6, 0.20 600 E 6, 0.50
Young's Modulus Poisson's ratio Density Yield Stress, Plastic Strain
110 E 9 0.3 8970 314 E 6, 0.00
Copper
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
W2.2–2
Aluminum Young's Modulus Poisson's ratio Density Yield Stress, Plastic Strain, Temp
70 E 9 0.35 2700 270 E 6, 0, 0 300 E 6, 1, 0 243 E 6, 0, 300 270 E 6, 1, 300
5. Stop recording. 6. Exit Abaqus/CAE (do not save changes). 7. In an editor, open the file abaqusMacros.py. 8. At the start of the function named add_SI_Materials, add a line to get the model name from the user using getInput. The getInput function should prompt with the name of the last model in the model repository. Hint: Use mdb.models.keys()[-1] to get the name of the last model. 9. Replace instances of 'Model-1' with the name obtained from the user. 10. Save the file, and exit the editor. 11. Start Abaqus/CAE. Create a new model, and run the revised macro. Use the name of the new model. Confirm that the materials have been added to the new model and not to Model-1.
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop Answers 2.2 A Macro to Create a Library of Materials Task Create a macro that prompts the user for the name of the model and adds three materials, in SI units, to the model.
Answers from abaqus import * from abaqusConstants import * def add_SI_Materials(): """ Add Steel, Copper, Aluminum in SI units """ import material name = getInput('Enter model name', mdb.models.keys()[-1]) if not name in mdb.models.keys(): raise ValueError, 'mdb.models[%s] not found'%repr(name) m = mdb.models[name].Material('Steel') m.Elastic(table=((200.0E9, 0.3), )) m.Plastic(table=((400.E6, 0.0), (420.E6, 0.02), (500.E6, 0.2), (600.E6, 0.5))) m.Density(table=((7800.0, ), )) m = mdb.models[name].Material('Aluminum') m.Elastic(table=((70.0E9, 0.35), )) m.Plastic(temperatureDependency=ON, table=((270e6,0,0), (300e6,1.0,0),(243e6,0,300),(270e6,1.0,300))) m.Density(table=((2700,), )) m = mdb.models[name].Material('Copper') m.Elastic(table=((110e9,.3),)) m.Plastic(table=((314e6,0),)) m.Density(table=((8970,),))
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop 3.1 Linear Superposition of Results Goals When you complete this workshop, you will be able to: • Combine results from 2 separate fields on the ODB to create a new temporary field. • Display the new field in Abaqus/Viewer.
Task An ODB file is provided, named beam3d.odb, which contains the displacements of a cantilever beam. In the step named Down a vertical load was applied, and in the step named Sideways a horizontal load was applied. Add the displacements and stresses from the last frame of step Down to the last frame of step Sideways, and display the result in Abaqus/Viewer.
Other information Write a script that does the following: 1. Open the ODB file beam3d.odb. Use the command session.openOdb. 2. Assign the Odb object to the variable odb. 3. Assign the fields from the last frame of each step as follows: • • • • • •
Assign the variable disp1 to the displacement field of the last frame of the step named Down. Assign the variable disp2 to the displacement field of the last frame of the step named Sideways. Assign the variable stress1 to the stress field of the last frame of the step named Down. Assign the variable stress2 to the stress field of the last frame of the step named Sideways. Add the two displacement fields to get disp3. Add the two stress fields to get stress3. (Note that displacements have the key U, and stresses have the key S.)
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
W3.1–2
4. Plot the contours of the result, using the following commands (where vp refers to the current viewport) vp.setValues(displayedObject=odb) vp.odbDisplay.setPrimaryVariable(field=stress3, outputPosition=INTEGRATION_POINT, refinement=(INVARIANT, 'Mises')) vp.odbDisplay.setDeformedVariable(disp3) vp.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF,))
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop Answers 3.1 Linear Superposition of Results Task An ODB file is provided, named beam3d.odb, which contains the displacements of a cantilever beam. In the step named Down a vertical load was applied, and in the step named Sideways a horizontal load was applied. Add the displacements and stresses from the last frame of step Down to the last frame of step Sideways, and display the result in Abaqus/Viewer.
Answers from abaqus import * from abaqusConstants import * import visualization # Open the odb # odb = visualization.openOdb('beam3d.odb') # Fetch existing results from the last frame of each step # frame1 = odb.steps['Down'].frames[-1] disp1 = frame1.fieldOutputs['U'] stress1 = frame1.fieldOutputs['S'] frame2 = odb.steps['Sideways'].frames[-1] disp2 = frame2.fieldOutputs['U'] stress2 = frame2.fieldOutputs['S'] # Add the two fields together disp3 = disp1 + disp2 stress3 = stress1 + stress2 # Plot contours of the result vp = session.viewports['Viewport: 1'] vp.setValues(displayedObject=odb) vp.odbDisplay.setPrimaryVariable(field=stress3, outputPosition=INTEGRATION_POINT, refinement=(INVARIANT, 'Mises')) vp.odbDisplay.setDeformedVariable(disp3) vp.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF,))
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop 3.2 Create an ODB from a Text File Goals When you complete this workshop, you will be able to: • Create an Abaqus Output Database using the odbAccess API. • Display results in Abaqus/Viewer from the new ODB.
Task A text file is provided that contains data required to create a discrete part (nodes and elements) and nodal displacement results from an analysis. Read the text file, and create an ODB object from the data. Save the ODB object and close it. Open Abaqus/Viewer, and display a contour plot of the ODB. Animate the frames of the ODB.
Other information Use the function readOdbInfo in the module scr_parseodbinfo to parse the external file, and follow the instructions to create an ODB using the odbAccess API. The function readOdbInfo returns a tuple of three lists, nodeData, elementData, and frameData, that contain the data necessary to create the ODB. The data structures are as follows: nodeData A list of tuples containing node data, each of which is (nodeLabel, nodeX,
nodeY, nodeZ) elementData A list of tuples containing element data, each of which is
(elementLabel, connectivity1, connectivity2, connectivity3, connectivity4) frameData A list of data objects containing displacement data for each frame. Access
the data as follows: frameData[i].nodeDisplacementLabelData is a list of node labels frameData[i].nodeDisplacementData is a list of tuples, each of which is
(displacementX, displacementY, displacementZ) Use the following statements to read the data into your script: from scr_parseodbinfo import readOdbInfo nodeData, elementData, frameData = \ readOdbInfo('scr_readodbfromtext.txt')
In the instructions below the argument list is shown as (...). Use the online documentation to find the appropriate arguments for each of the functions and methods.
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
W3.2–2
Import all names from the odbAccess module. Create a new ODB (output database) object. Use the name odbFromText. This will also be used for the path. odb = Odb(...)
Create a Part object. part = odb.Part(...)
Use the method addNodes to define the part's nodes, using the node data. part.addNodes(...)
Use the method addElements to define the part's elements, using the element data. Use the element type 'CAX4RH'. part.addElements(...)
Create an instance of the part. instance = odb.rootAssembly.Instance(...)
Create a step. Use the domain TIME. step = odb.Step(...)
For each frame in the frame data: Create a frame. frame = step.Frame(...)
Create a nodal displacement field (use the key 'U'). fieldOutput = frame.FieldOutput(...)
Use the following to define values for the nodal displacements, using the frame data from the file. fieldOutput.addData(...)
Make this the default deformed field for visualization. step.setDefaultDeformedField(...)
Save and close the ODB so that it can be reopened by Abaqus/Viewer. odb.save() odb.close()
Open the ODB in Abaqus/Viewer and view the contour plot, then animate the plot.
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop Answers 3.2 Create an ODB from a Text File Task A text file is provided that contains data required to create a discrete part (nodes and elements) and nodal displacement results from an analysis. Read the text file, and create an Odb object from the data. Save the Odb object and close it. Open Abaqus/Viewer, and display a contour plot of the Odb. Animate the frames of the Odb.
Answers """ readOdbFromText.py """ from scr_parseodbinfo import readOdbInfo nodeData, elementData, frameData = \ readOdbInfo('scr_readodbFromtext.txt')
# The data has been read. Now create the Odb from odbAccess import * # remove any former version of the odb import os, osutils if os.path.exists('odbFromText.odb'): osutils.remove('odbFromText.odb') odb = Odb('OdbFromText', analysisTitle='', description='', path='odbFromText.odb') part1 = odb.Part(name='part-1', embeddedSpace=THREE_D, type=DEFORMABLE_BODY) part1.addNodes(nodeData=nodeData, nodeSetName='nset-1') del nodeData part1.addElements(elementData=elementData, type='CAX4RH', elementSetName='eset-1') del elementData
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
WA3.2–2 # Instance the part. instance1 = odb.rootAssembly.Instance(name='part-1-1', object=part1) # Field data: # Create a step and a frame. step1 = odb.Step(name='step-1', description='', domain=TIME, timePeriod=1.0) for i in range(len(frameData)): frame = step1.Frame(frameId=i, frameValue=0.1*i, description=frameData[i].description) # Add nodal displacements to Odb. uField = frame.FieldOutput(name='U', description='Displacements', type=VECTOR) uField.addData(position=NODAL, instance=instance1, labels=frameData[i].nodeDisplacementLabelData, data=frameData[i].nodeDisplacementData) del frameData # Make this the default deformed field for visualization. step1.setDefaultDeformedField(uField) # Save the Odb in order to re-open it in Abaqus/Viewer odb.save() odb.close()
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop 4.1 Job Monitoring Goals When you complete this workshop, you will be able to: • Write callback functions to respond to messages sent by analysis jobs.
Task 1 The file rubberDome.inp includes a request to monitor the vertical (U2) displacement at node 52 at the top of the part. Write a script that creates and runs the rubberDome job and prints the time and value of the data sent by the MONITOR_DATA message.
Other information 1. Open the file scr_datamonitor.py. You will find that it contains the code used for the simple monitor example from the class. 2. Write a callback function named monitorDataValue. The arguments are the same as the printMessages function. The function should print the data.time and data.value. 3. Edit the call to addMessageCallback as follows: a. Change the job argument from ANY_JOB to rubberDome b. Change the message type ANY_MESSAGE_TYPE to MONITOR_DATA c. Change the name of the callback function from printMessages to monitorDataValue. 4. Add code to the script to create and run the rubberDome job. Your script must create a Job object using the input file. Use the commands job = mdb.JobFromInputFile(name='rubberDome', inputFileName='rubberDome.inp') job.submit()
5. Run the script in Abaqus/CAE, either using either the -start option or the Run Script option within Abaqus/CAE.
Task 2 Modify the monitorDataValue callback function to stop the analysis when the U2 displacement at node 52 (data.value) reaches -2.0. The job is accessible using job = mdb.jobs[jobName]. Use the method job.kill() to stop the analysis.
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus
Workshop Answers 4.1 Job Monitoring Task 1 The file rubberDome.inp includes a request to monitor the vertical (U2) displacement at node 52 at the top of the part. Write a script that creates and runs the rubberDome job and prints the time and value of the data sent by the MONITOR_DATA message.
Task 2 Modify the monitorDataValue callback function to stop the analysis when the U2 displacement at node 52 (data.value) reaches −2.0.
Answers (Task 1 and Task 2) from abaqus import * from abaqusConstants import * import job from jobMessage import * def monitorDataValue(jobName, messageType, data, userData): print "%-8s
%s"%(data.time, data.value)
if data.value < -2.0: mdb.jobs[jobName].kill() monitorManager.addMessageCallback('rubberDome', MONITOR_DATA, monitorDataValue, None) job = mdb.JobFromInputFile('rubberDome', 'rubberDome.inp') job.submit()
Copyright 2007 Dassault Systèmes
Introduction to Python and Scripting in Abaqus