Introduction to Python and Scripting in...

133
Introduction to Python and Scripting in Abaqus Introduction to Python and Scripting in Abaqus 2 Copyright 2007 Dassault Systèmes Agenda Overview Python Scripting in Abaqus Specialized Postprocessing Advanced Topics

Transcript of Introduction to Python and Scripting in...

Page 1: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

Introduction to Python and Scripting in Abaqus

2

Copyright 2007 Dassault Systèmes

Agenda

• Overview• Python• Scripting in Abaqus• Specialized Postprocessing• Advanced Topics

Page 2: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Overview

Introduction to Python and Scripting in Abaqus

4

Copyright 2007 Dassault Systèmes

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.

Page 3: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

5

Copyright 2007 Dassault Systèmes

Overview

• Motivation: Why customize Abaqus? • Automate repetitive tasks

• Model building• Job submission and monitoring• Postprocessing• Prescribe default

behavior

• Extend functionality

• Enhance the interface• Graphical• Nongraphical

Provides automated environment for

experienced analysts

Provides advanced analysis

functionality to non-FE users

Cus

tom

ized

appl

icat

ionCustomized versions

of Abaqus provide an effective analysis tool for a wide range of user expertise …

Introduction to Python and Scripting in Abaqus

6

Copyright 2007 Dassault Systèmes

Overview

• Abaqus/CAE customization• The ASI allows you to customize much of the behavior of Abaqus pre-

and 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.

Abaqus Scripting predominantly affects Abaqus/CAE customization

Page 4: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

7

Copyright 2007 Dassault Systèmes

Overview

• Two manuals* are presently available for scripting

* these two manuals are available in electronic format only.

Introduction to Python and Scripting in Abaqus

8

Copyright 2007 Dassault Systèmes

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.

Page 5: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

9

Copyright 2007 Dassault Systèmes

Revision Status

Updated for V6.75/07Workshop 3.1

Updated for V6.75/07Workshop 2.1

Updated for V6.75/07Workshop 1.1

Updated for V6.75/07Lecture 4

Updated for V6.75/07Workshop 1.2

Updated for V6.75/07Workshop 2.2

Updated for V6.75/07Workshop 3.2

Updated for V6.75/07Workshop 4.1

Updated for V6.75/07Lecture 3

Updated for V6.75/07Lecture 2

Updated for V6.75/07Lecture 1

Page 6: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Python

Lecture 1

Introduction to Python and Scripting in Abaqus

L1.2

Copyright 2007 Dassault Systèmes

Overview

• Basics• Types• Programming Constructs• Namespaces• Modules• Exceptions• Examples• Workshops

Page 7: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Basics

Introduction to Python and Scripting in Abaqus

L1.4

Copyright 2007 Dassault Systèmes

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 Class model supports encapsulation, polymorphism, andoriented: multiple inheritance

Page 8: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.5

Copyright 2007 Dassault Systèmes

Basics

• Python references• Official Python web site: www.python.org

• Online tutorialwww.python.org/doc/current/tut/tut.html

• News groupscomp.lang.python

comp.lang.python.announce

• Many books are available.www.rmi.net/~lutz/pybooks.html

Introduction to Python and Scripting in Abaqus

L1.6

Copyright 2007 Dassault Systèmes

Basics

• How to run Python• Interactive

$ abaqus python>>> print 5**4625>>> 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.py625

a = 5; b = 4c = a ** bprint c

Page 9: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.7

Copyright 2007 Dassault Systèmes

Basics

• How to run Python (cont.)• Unix-style script file

$ mytest.py625

• Embedded in another system

• E.g., Abaqus/CAE

#!/prog/pythona = 5; b = 4c = a ** bprint c

Run in interactive modeRun as top level

script

Introduction to Python and Scripting in Abaqus

L1.8

Copyright 2007 Dassault Systèmes

Basics

• How to run Python (cont.)• Windows-style script file

D:\ mytest625

• The interactive mode will echo data by default. Running from files will not.

a = 5; b = 4c = a ** bprint c

Page 10: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.9

Copyright 2007 Dassault Systèmes

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

L1.10

Copyright 2007 Dassault Systèmes

Basics

• Example using common syntax rules:

# simple examplemax = 5; i = 0x, y, z = 1, 2, 3

while i <= max:square = i**2 + x*ycube = i**3 - zprint i, square, cubei = i + 1 # increment index

for j in ['ASN',1,2]:pass

print 'The example is completed\now print a long message'

Semicolon for two statements

blank lines ignored

Comments start with # and continue to the end of the line

Backslash for line continuation

Indentation delimits blocks (such as loops)

The amount of indentation is arbitrary but must be consistent for a block

An empty block is denoted with the pass statement

The syntax forces the user to write readable code and enables productivity

Page 11: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.11

Copyright 2007 Dassault Systèmes

Basics

• Assignment: Binding a variable name to an object>>> 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 deletedautomatically.

Introduction to Python and Scripting in Abaqus

L1.12

Copyright 2007 Dassault Systèmes

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.• Example: file object

>>> f = open('tmp.txt')

>>> f.close()

>>> f.closed

True

• The members and methods of an object can be queried.>>> mdb.__members__['acis', 'adaptivityProcesses', 'annotations', …]

>>> mdb.__methods__['AdaptivityProcess', 'Annotation', 'Arrow', …]

method

member

The attributes called __members__ and __methods__ are discontinued in Python v2.2 but will be maintained in Abaqus Python.

Page 12: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.13

Copyright 2007 Dassault Systèmes

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= pinkarg2= 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

L1.14

Copyright 2007 Dassault Systèmes

Basics

• Keyword arguments• You can specify arguments in any order by using keywords.

>>> test(arg2='bicycle', arg1='blue')arg1= bluearg2= 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

Page 13: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.15

Copyright 2007 Dassault Systèmes

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! = 1n! = 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)17112245242814131137246833888127283909227054489352036939364800923257279754140647424000000000000000L

Introduction to Python and Scripting in Abaqus

L1.16

Copyright 2007 Dassault Systèmes

Basics

• OperatorsMathematical: +, -, *, **, /, %

>>> (5 + 3)/2

4

Logical: and, or, not

>>> 1 or 0

1

Comparison: <, <=, ==, >, >=, != (!= same as <>)>>> 5 != 6

1

Bitwise: |, ^, &, <<, >>>>> 1 << 2

4

Page 14: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.17

Copyright 2007 Dassault Systèmes

Basics

• Coding style• Using a few rules and applying them consistently for coding will make

your code easier for others to read and maintain.

• Abaqus generally uses the style proposed by Guido van Rossum, the inventor of Python. His style guide is available at the following site:http://www.python.org/doc/essays/styleguide.html

Introduction to Python and Scripting in Abaqus

L1.18

Copyright 2007 Dassault Systèmes

Basics

• Common errors for new users • Do not override built-in

functions• It is easy for beginners

to override built-in functions inadvertently. For example:

• It is easy to recover from built-in overrides by the using the delstatement. For example:

Page 15: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.19

Copyright 2007 Dassault Systèmes

Basics

• Indent consistently.

• Mixing tabs with spaces for indentation can cause unpredictable behavior. We recommend using spaces exclusively.

• Do not always expect a function to return a result. • Functions that have no result to return, return the NoneType object;

for example, the following is an in-place change operation:

>>> list1 = [1,2,3]>>> list1[1, 2, 3]>>> list2 = list1.append(4)>>> list2>>> list1[1, 2, 3, 4]>>> type(list2)<type 'NoneType'>

Copyright 2007 Dassault Systèmes

Types

Page 16: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.21

Copyright 2007 Dassault Systèmes

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

L1.22

Copyright 2007 Dassault Systèmes

Types

• Number types• Integer (decimal, octal, hexadecimal)*

Example: 1234, 0644, 0x100fea8

• LongExample:

>>> 17643L**11111

463783748290623436091218...

• FloatExamples: 3.1415, .0314e2, .0314e+2, .0314e-2

• Complex Examples: z = 2 + 3j, 12.34j

z.real, z.imag* To specify octal or hexadecimal, precede the value with 0 or 0x respectively.

Integers

Numbers

Complex

Long Integer

Integer

Float

Page 17: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.23

Copyright 2007 Dassault Systèmes

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.010.0

• Operations between integers resulting in fractions do not create a float.>>> 3/2

1>>> 2/30

Introduction to Python and Scripting in Abaqus

L1.24

Copyright 2007 Dassault Systèmes

Types

• Sequence types • There are three built-in sequence types in Python and an array type

implemented in a separate module.

• 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.

array((2.3,5.6))YesYesYesarray

'wxyz'YesYesNostring

('a',45,)NoNoNotuple

[9.0,'b']YesNoYeslist

SyntaxMethodsHomogeneousMutableType

Page 18: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.25

Copyright 2007 Dassault Systèmes

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

L1.26

Copyright 2007 Dassault Systèmes

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'

Page 19: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.27

Copyright 2007 Dassault Systèmes

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

L1.28

Copyright 2007 Dassault Systèmes

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']

Page 20: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.29

Copyright 2007 Dassault Systèmes

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 "<stdin>", 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

L1.30

Copyright 2007 Dassault Systèmes

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"""

Page 21: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.31

Copyright 2007 Dassault Systèmes

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)))>>> a4. 5.2. 3.

• Array methods: astype() byteswapped() iscontiguous() itemsize() tolist() tostring() typecode()

Introduction to Python and Scripting in Abaqus

L1.32

Copyright 2007 Dassault Systèmes

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)<type 'dict'>>>> myDict{'eric': 'Eric Idle', 2001: 'Beginning of the century', 'PI': 3.14159265359}>>> myDict['PI']3.14159265359

Page 22: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.33

Copyright 2007 Dassault Systèmes

Types

• Dictionary data types have a number of different methods: has_key() keys() values() items()

clear() copy() 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

L1.34

Copyright 2007 Dassault Systèmes

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'

Page 23: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.35

Copyright 2007 Dassault Systèmes

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

Copyright 2007 Dassault Systèmes

Programming Constructs

Page 24: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.37

Copyright 2007 Dassault Systèmes

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

L1.38

Copyright 2007 Dassault Systèmes

Programming Constructs

• Loopingwhile—similar to C, will continue while expression is true.

while expression:do something

for—iterates through a sequence.>>> for i in range(2, 6):... print i, ... 2 3 4 5>>> myList = ['a', 'b', 'c']>>> for letter in myList:... print letter...abC

•The range function is convenient for generating a list to iterate through.

Page 25: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.39

Copyright 2007 Dassault Systèmes

Programming Constructs

break—break out of the loop.i, max = 0, 50while 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

L1.40

Copyright 2007 Dassault Systèmes

Programming Constructs

• Example: Print a graph in the terminal windowfor 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'

Page 26: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Namespaces

Introduction to Python and Scripting in Abaqus

L1.42

Copyright 2007 Dassault Systèmes

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.

Page 27: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.43

Copyright 2007 Dassault Systèmes

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 <built-in function len>?• 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

Copyright 2007 Dassault Systèmes

Modules

Page 28: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.45

Copyright 2007 Dassault Systèmes

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

L1.46

Copyright 2007 Dassault Systèmes

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 hworldprint 'importing hworld'hw = 'Hello World'c = 76

def pr(x):print x

$ abaqus python>>> import hworldimporting hworld>>> print hworld.hwHello World>>> print hworld.c76>>> hworld.pr(58)58

Page 29: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.47

Copyright 2007 Dassault Systèmes

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

L1.48

Copyright 2007 Dassault Systèmes

Modules

• Ways of changing the Python module search path for site specificmodules:

• Modify sys.path directly.

• Example: import syssys.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. Ifbackslashes 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']

Page 30: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.49

Copyright 2007 Dassault Systèmes

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, itsstatements are executed in the __main__ module.

< exported objects >

def test():< test my exports >

if __name__ == '__main__': test()

Example module format incorporating a self-test using __main__

Introduction to Python and Scripting in Abaqus

L1.50

Copyright 2007 Dassault Systèmes

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.

Page 31: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Exceptions

Introduction to Python and Scripting in Abaqus

L1.52

Copyright 2007 Dassault Systèmes

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.

Page 32: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.53

Copyright 2007 Dassault Systèmes

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 "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero

def inverse(x):try:

print 1/xexcept ZeroDivisionError:

print x, 'has no inverse'

Copyright 2007 Dassault Systèmes

Examples

Page 33: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.55

Copyright 2007 Dassault Systèmes

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 0else:

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

L1.56

Copyright 2007 Dassault Systèmes

Example 1-2: File Manipulation

# open a file for reading, and print it outf = 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 ittext.reverse()f = open('temp.txt', 'w')f.write('Reversed file\n')for line in text:

f.write(line)f.close()

# now print the new fileprint open('temp.txt').read()

Page 34: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Workshops

Introduction to Python and Scripting in Abaqus

L1.58

Copyright 2007 Dassault Systèmes

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:

Page 35: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L1.59

Copyright 2007 Dassault Systèmes

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 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

Page 36: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Scripting in Abaqus

Lecture 2

Introduction to Python and Scripting in Abaqus

L2.2

Copyright 2007 Dassault Systèmes

Overview

• The Abaqus Scripting Interface• Abaqus Object Model• Abaqus Types• Abaqus Modules• Setting Abaqus Defaults• Getting Interactive Input• Examples• Workshops

Page 37: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

The Abaqus Scripting Interface

Introduction to Python and Scripting in Abaqus

L2.4

Copyright 2007 Dassault Systèmes

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

Page 38: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.5

Copyright 2007 Dassault Systèmes

The Abaqus Scripting Interface

• Executing Scripting Interface commands

• Commands are issued by the GUI, via the command line interface, and from scripts.

• Commands go to the kernel that creates an internal representation of your model.

command line

interface (CLI)

Abaqus/CAE

Abaqus/CAEkernel

Abaqus/StandardAbaqus/ExplicitAbaqus/Design

output database file

input file

Python interpreter

replay files

scriptGUI

commands

1 2 3

Introduction to Python and Scripting in Abaqus

L2.6

Copyright 2007 Dassault Systèmes

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

The CLI is currently displayed

Page 39: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.7

Copyright 2007 Dassault Systèmes

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

L2.8

Copyright 2007 Dassault Systèmes

• 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.

(2) You may not bypass the Abaqus/CAE kernel like this:

The Abaqus Scripting Interface

abaqus python myscript.pyabaqus script myscript.py

abaqus cae startup = myscript.pyabaqus cae script = myscript.pyabaqus viewer startup = myscript.py

Page 40: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.9

Copyright 2007 Dassault Systèmes

The Abaqus Scripting Interface

•Two simple ways of building new scripts1. You can use the Macro Manager to record a sequence of the generated Abaqus commands in a macro file.

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.

The filename is abaqusMacros.py.The file always gets appended.

You may specify a location for the macro file when creating a macro.

Introduction to Python and Scripting in Abaqus

L2.10

Copyright 2007 Dassault Systèmes

The Abaqus Scripting Interface

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:

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)

session.viewports['Viewport:1'].view.rotate(xAngle=10,yAngle=0,zAngle=0,mode=MODEL)

Save the script as rotate.py.

Example: Creating a script that rotates the model in current display

Page 41: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.11

Copyright 2007 Dassault Systèmes

3) Run the script in Abaqus/CAE by selecting

File→Run Script

The Abaqus Scripting Interface

Introduction to Python and Scripting in Abaqus

L2.12

Copyright 2007 Dassault Systèmes

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.

Page 42: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

The Abaqus Object Model

Introduction to Python and Scripting in Abaqus

L2.14

Copyright 2007 Dassault Systèmes

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.

Taken from the Abaqus Scripting User's Manual (available online only)

There are three roots in the Abaqus object model: the Session, the Mdb, and the Odb objects.

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.

Page 43: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.15

Copyright 2007 Dassault Systèmes

The Abaqus Object Model

• Basics• The object model describes the relationships between objects.

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.

A Part owns features, datums, etc.

A Model owns parts

Introduction to Python and Scripting in Abaqus

L2.16

Copyright 2007 Dassault Systèmes

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.

Page 44: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.17

Copyright 2007 Dassault Systèmes

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]

• 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.

cell with index 4

part named crankcase

Model database mdb

Variable cell4

model named block

Introduction to Python and Scripting in Abaqus

L2.18

Copyright 2007 Dassault Systèmes

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.

Page 45: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.19

Copyright 2007 Dassault Systèmes

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

L2.20

Copyright 2007 Dassault Systèmes

•Constructor examplep = 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']

The Abaqus Object Model

Page 46: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.21

Copyright 2007 Dassault Systèmes

•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 printOptionsobject (values of other members are not changed):

session.printOptions.setValues(rendition=GREYSCALE)

The Abaqus Object Model

Introduction to Python and Scripting in Abaqus

L2.22

Copyright 2007 Dassault Systèmes

The Abaqus Object Model

• The Session object model

Page 47: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.23

Copyright 2007 Dassault Systèmes

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

L2.24

Copyright 2007 Dassault Systèmes

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

Page 48: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.25

Copyright 2007 Dassault Systèmes

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

L2.26

Copyright 2007 Dassault Systèmes

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)<type 'Viewport'>>>> vp.__members__['activeColorModes', 'animationConnect', 'animationPlayer', … ]>>> vp.__methods__['Layer', 'bringToFront', 'disableMultipleColors', … ]

Page 49: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.27

Copyright 2007 Dassault Systèmes

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 odbAccessshockLoadOdb = odbAccess.openOdb(path='myOdb.odb')>>>

• Tab completion is available at the interactive prompt in Abaqus Python (not available in standard Python).

Copyright 2007 Dassault Systèmes

Abaqus Types

Page 50: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.29

Copyright 2007 Dassault Systèmes

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

L2.30

Copyright 2007 Dassault Systèmes

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_BODYa.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.

Page 51: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.31

Copyright 2007 Dassault Systèmes

Abaqus Types

• Other Abaqus types• Currently there are about 280 different types.

• Examples: Material, HomogeneousSolidSectiontype(mdb.models['Model-1'].materials['Steel'])

<type 'Material'>

• 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

L2.32

Copyright 2007 Dassault Systèmes

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 namespacedel vp

• To delete the viewport named Viewport: 1del session.viewports['Viewport: 1']

Page 52: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.33

Copyright 2007 Dassault Systèmes

Abaqus Types

• Example: The section object>>> s = mdb.models['Model-1'].sections['sec-1']>>> type(s)<type 'HomogeneousSolidSection'>>>> s.__members__['material', 'name', 'thickness']>>> s.__methods__['setValues']>>> for member in s.__members__:... print 's.%s = %s' % (member, getattr(s, member))s.material = mat-1s.name = sec-1s.thickness = 1.0>>> del mdb.models['Model-1'].sections['sec-1']

Copyright 2007 Dassault Systèmes

Abaqus Modules

Page 53: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.35

Copyright 2007 Dassault Systèmes

Abaqus Modules

Creating and modifying sketchessketchAccessing the output database fileodbAccessVisualizing resultsvisualizationCreating, submitting, and monitoring jobsjobMeshing part instancesmeshCreating and modifying loads and boundary conditionsloadCreating and modifying interactionsinteractionCreating and modifying stepsstepCreating and modifying assembliesassemblyCreating and modifying sectionssectionCreating and modifying materialsmaterialCreating and modifying partspart

FunctionalityKernel Module

Introduction to Python and Scripting in Abaqus

L2.36

Copyright 2007 Dassault Systèmes

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.

Page 54: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Setting Abaqus Defaults

Introduction to Python and Scripting in Abaqus

L2.38

Copyright 2007 Dassault Systèmes

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.

Page 55: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.39

Copyright 2007 Dassault Systèmes

Setting Abaqus Defaults

• Abaqus environment file: abaqus_v6.env

def onCaeStartup():# Compatibility issuesbackwardCompatibility.setValues(includeDeprecated=OFF)

# Graphics preferencessession.graphicsOptions.setValues(displayLists=ON, dragMode=AS_IS)

# Print preferencessession.printOptions.setValues(vpDecorations=OFF, vpBackground=OFF,

rendition=COLOR, printCommand='lpr')

# Visualization preferencesdef setVisPreferences(module, userData):

from visualization import SHADED, EXTERIOR, CONTINUOUSsession.defaultOdbDisplay.commonOptions.setValues(

renderStyle=SHADED, visibleEdges=EXTERIOR)session.defaultOdbDisplay.contourOptions.setValues(

contourStyle=CONTINUOUS)addImportCallback('visualization', setVisPreferences)

# Material properties - read them from a fileexecfile('my_material_library.py')

Introduction to Python and Scripting in Abaqus

L2.40

Copyright 2007 Dassault Systèmes

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 osextensions = ('res','stt','mdl','prt','abq','pac')restartDir = savedir + id + '_restart' + os.sepif (not os.path.exists(restartDir)):

os.mkdir(restartDir)for extension in extensions:

fileName = id + '.' + extensionif (os.path.exists(savedir + fileName)):

os.rename(savedir + fileName, restartDir + fileName)

def onJobStartup():import os, osutilsrestartDir = savedir + id + '_restart'if (os.path.exists(restartDir)):

osutils.removeTree(restartDir)

Page 56: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.41

Copyright 2007 Dassault Systèmes

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 linesfrom 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)

Copyright 2007 Dassault Systèmes

Getting Interactive Input

Page 57: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.43

Copyright 2007 Dassault Systèmes

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

L2.44

Copyright 2007 Dassault Systèmes

Getting Interactive Input

• ExampleThe getInput function allows the user to enter a value:from abaqus import *from math import sqrtinput = 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:

Page 58: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Examples

Introduction to Python and Scripting in Abaqus

L2.46

Copyright 2007 Dassault Systèmes

Example 2-1: Multiple Viewport Create and Tile

• Create an array of viewports.

The scr_viewport_tiler.pyscript 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).

Viewport widths and heights are automatically calculated by the script to fit inside the drawing area.

Page 59: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.47

Copyright 2007 Dassault Systèmes

Example 2-2: “A” Shaped Part

• Create a part in the form of the letter A.Import modules and create the mdb object.

from abaqus import *from abaqusConstants import *from caeModules import *

Mdb()

1

This constructor creates the mdb object

Introduction to Python and Scripting in Abaqus

L2.48

Copyright 2007 Dassault Systèmes

Example 2-2: “A” Shaped Part

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])

2

Page 60: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.49

Copyright 2007 Dassault Systèmes

Example 2-2: “A” Shaped Part

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)

Instance the part in the root assembly.

myAssembly = mdb.models['Model A'].rootAssembly

myInstance = myAssembly.Instance(name='Part A-1', part=myPart, dependent=OFF)

3

4

Introduction to Python and Scripting in Abaqus

L2.50

Copyright 2007 Dassault Systèmes

Mesh the instance.partInstances = (myInstance,)

myAssembly.seedPartInstance(regions=partInstances, size=5.0)

myAssembly.generateMesh(regions=partInstances)

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)

Example 2-2: “A” Shaped Part

5

6

Page 61: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.51

Copyright 2007 Dassault Systèmes

Example 2-3: Parameter Study Example

• Implementation of Abaqus Benchmark Problem 2.3.4: Skew sensitivity of shell elements

Copyright 2007 Dassault Systèmes

Workshops

Page 62: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L2.53

Copyright 2007 Dassault Systèmes

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

L2.54

Copyright 2007 Dassault Systèmes

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.

Page 63: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Specialized Postprocessing

Lecture 3

Introduction to Python and Scripting in Abaqus

L3.2

Copyright 2007 Dassault Systèmes

Overview

• The Abaqus Output Database• Automating Postprocessing Tasks• Postprocessing External Data• Examples• Workshop

Page 64: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

The Abaqus Output Database

Introduction to Python and Scripting in Abaqus

L3.4

Copyright 2007 Dassault Systèmes

The Abaqus Output Database

• A portion of the Output Database object model: Model and result data

Field Data

History Data

Page 65: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.5

Copyright 2007 Dassault Systèmes

The Abaqus Output Database

• Opening an output databasefrom 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 stepcrushStep = 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

L3.6

Copyright 2007 Dassault Systèmes

The Abaqus Output Database

• Accessing the last frame of crushStepcrushFrame = 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.

Page 66: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.7

Copyright 2007 Dassault Systèmes

• Accessing field output (stress)stress = crushFrame.fieldOutputs['S']

• One statement access to the stress resultsstress = odb.steps['Crush'].frames[-1].fieldOutputs['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.

The Abaqus Output Database

Variable stress

Output database odb

Step named Crush

The last frame

Field output named S

Introduction to Python and Scripting in Abaqus

L3.8

Copyright 2007 Dassault Systèmes

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 getSubsetcommand 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.

Page 67: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.9

Copyright 2007 Dassault Systèmes

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

L3.10

Copyright 2007 Dassault Systèmes

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

Page 68: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.11

Copyright 2007 Dassault Systèmes

The Abaqus Output Database

• HistoryRegion• A HistoryRegion refers to a specific point or region of the model

• Accessing a history regionendPoint = 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 outputu2Deflection = 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

L3.12

Copyright 2007 Dassault Systèmes

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.

Page 69: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.13

Copyright 2007 Dassault Systèmes

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

L3.14

Copyright 2007 Dassault Systèmes

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 'Position = ', v.positionprint 'Type = ', v.typeprint 'Node label = ', v.nodeLabelprint 'X displacement = ', v.data[0]print 'Y displacement = ', v.data[1]print 'Displacement magnitude =', v.magnitude

odb.close()

Position = NODAL Type = VECTORNode label = 1000X displacement = -8.05730572321e-034Y displacement = -76.4923706055Displacement magnitude = 76.4923706055

Page 70: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.15

Copyright 2007 Dassault Systèmes

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.

Copyright 2007 Dassault Systèmes

Automating Postprocessing Tasks

Page 71: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.17

Copyright 2007 Dassault Systèmes

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

L3.18

Copyright 2007 Dassault Systèmes

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.odbDisplayod.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.

Page 72: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.19

Copyright 2007 Dassault Systèmes

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

L3.20

Copyright 2007 Dassault Systèmes

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)

Page 73: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.21

Copyright 2007 Dassault Systèmes

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

L3.22

Copyright 2007 Dassault Systèmes

Automating Postprocessing Tasks

Page 74: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Postprocessing External Data

Introduction to Python and Scripting in Abaqus

L3.24

Copyright 2007 Dassault Systèmes

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 databaseodb = Odb(name='myData', analysisTitle='derived data',

description='test problem', path='testWrite.odb')

Page 75: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.25

Copyright 2007 Dassault Systèmes

Postprocessing External Data

• Creating partsmyPart = odb.Part(name='My Part',

embeddedSpace=THREE_D, type=DEFORMABLE_BODY)

• Adding nodes and elements to a partnodeData = ( (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

L3.26

Copyright 2007 Dassault Systèmes

Postprocessing External Data

• Instance the part in the root assemblymyInstance = odb.rootAssembly.Instance(name='My Instance',

object=myPart)

• Creating a stepmyStep = odb.Step(name='My Step', description='',

domain=TIME, timePeriod=1.0)

• Creating a framemyFrame = myStep.Frame(frameId=1, frameValue=0.1,

description='')

Page 76: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.27

Copyright 2007 Dassault Systèmes

Postprocessing External Data

• Creating field outputuField = myFrame.FieldOutput(name='U',

description='Displacements', type=VECTOR)

• Adding result data to field outputnodeLabels = (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)

Copyright 2007 Dassault Systèmes

Examples

Page 77: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.29

Copyright 2007 Dassault Systèmes

Example 3-1: Plotting External X–Y Data

Data file and corresponding plot

Introduction to Python and Scripting in Abaqus

L3.30

Copyright 2007 Dassault Systèmes

Example 3-1: Plotting External X–Y Data

from visualization import XYData, USER_DEFINED

def plotExternalData(fileName):# Extract the data from the filefile = 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))

Page 78: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.31

Copyright 2007 Dassault Systèmes

Example 3-1: Plotting External X–Y Data

# Create an XY Plot of the dataxyData = 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 viewportvp = session.viewports[session.currentViewportName]vp.setValues(displayedObject=xyPlot)

if __name__ == '__main__':plotExternalData('scr_xyplot.dat')

Introduction to Python and Scripting in Abaqus

L3.32

Copyright 2007 Dassault Systèmes

Example 3-2: Multiple Frames in One Plot

Page 79: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.33

Copyright 2007 Dassault Systèmes

Example 3-2: Multiple Frames in One Plot

Introduction to Python and Scripting in Abaqus

L3.34

Copyright 2007 Dassault Systèmes

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.

Page 80: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.35

Copyright 2007 Dassault Systèmes

Example 3-3: Extreme Value Odb Query

from abaqus import *from abaqusConstants import *

import visualizationimport displayGroupOdbToolset as dgo

# Use the output database displayed in the current viewport

vp = session.viewports[session.currentViewportName]odb = vp.displayedObjectif type(odb) != visualization.OdbType:

raise 'An odb must be displayed in the current viewport.'

# Find the maximum von Mises stress

maxValue = NonestressOutputExists = FALSEfor step in odb.steps.values():

print 'Processing step:', step.namefor frame in step.frames:

try: stress = frame.fieldOutputs['S']stressOutputExists = TRUE

except KeyError: # Skip frames with no stress outputcontinue

Introduction to Python and Scripting in Abaqus

L3.36

Copyright 2007 Dassault Systèmes

Example 3-3: Extreme Value Odb Query

for stressValue in stress.values:if (not maxValue or

stressValue.mises > maxValue.mises):maxValue = stressValuemaxStep, maxFrame = step, frame

# Raise an error if there was no relevant output in the Odbif not stressOutputExists:

raise 'This odb does not have stress output.'

# Print the details of the max von Mises stressprint 'Found maximum von Mises stress of %E in' % maxValue.misesprint ' Step: ', maxStep.nameprint ' Frame: ', maxFrame.frameIdprint ' Instance: ', maxValue.instance.nameprint ' Element: ', maxValue.elementLabelprint ' Section point: ', maxValue.sectionPointprint ' Integration point:', maxValue.integrationPoint

Page 81: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.37

Copyright 2007 Dassault Systèmes

Example 3-3: Extreme Value Odb Query

#Color the element Red where the max von Mises stress occursleaf = 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

L3.38

Copyright 2007 Dassault Systèmes

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.

Page 82: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.39

Copyright 2007 Dassault Systèmes

Example 3-4: Tube Deflection

from abaqus import *from abaqusConstants import *

from scr_tubeFunctions import createBeam, initializeVp, showDeflection

import odbAccessimport visualization # only for display purposes

thickness = 0.004 # mmaxAllowableDeflection = 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 loadscreateBeam(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

L3.40

Copyright 2007 Dassault Systèmes

Example 3-4: Tube Deflection

# get the end deflection from the Output Batabaseodb = 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 CLIshowDeflection(jobName, thickness, deflection)print 'deflection: %7.3f mm'%(deflection*1000)

if abs(deflection) <= maxAllowableDeflection:break

# increase thickness by 1 mm for next loopthickness = thickness + 0.001

print 'Result obtained for deflection less than %5.2f mm:'%\(maxAllowableDeflection*1000)

print 'Thickness: %4.1f mm, Deflection: %7.3f mm'%\(thickness*1000, deflection*1000)

Page 83: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Workshops

Introduction to Python and Scripting in Abaqus

L3.42

Copyright 2007 Dassault Systèmes

Workshop 3-1: Linear Superposition

• This workshop shows how you can use the Abaqus Scripting Interface (ASI) to combine results from two or more result frames.

• An ODB file is provided that contains the analysis 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 from the two load cases, and display the result in Abaqus/Viewer.

Down Sideways Down + Sideways

Page 84: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L3.43

Copyright 2007 Dassault Systèmes

Workshop 3-2: Creating an Output Database

• This workshop shows how you can use the Abaqus Scripting Interface (ASI) to postprocess data from sources other than Abaqus.

• A text file is provided that contains data required to create a discrete part (nodes and elements), as well as nodal displacement results from an analysis. Read the text file, and create an ODB object from the data.

Page 85: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Advanced Topics

Lecture 4

Introduction to Python and Scripting in Abaqus

L4.2

Copyright 2007 Dassault Systèmes

Overview

• Exploring Your Data• Abaqus Architecture• Job Monitoring• Custom Data• Plug-ins• Debugging Scripts• Object-Oriented Programming• Python Classes• Example• Workshop

Page 86: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Exploring Your Data

Introduction to Python and Scripting in Abaqus

L4.4

Copyright 2007 Dassault Systèmes

Exploring Your Data

• Interrogate Object attributes

Use special attributes. For example:>>> 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'})

Page 87: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.5

Copyright 2007 Dassault Systèmes

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

L4.6

Copyright 2007 Dassault Systèmes

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 <, maxRecursionDepth, maxElementsInSequence,

significantDigits, _internalMembersMethods>)printPaths(object <, maxRecursionDepth, maxElementsInSequence,

pathRoot, _internalMembersMethods>)printTypes(object <, maxRecursionDepth, maxElementsInSequence,

pathRoot, _internalMembersMethods>)printPathsToFileName(fileName, object <, maxRecursionDepth,

maxElementsInSequence, pathRoot, _internalMembersMethods>)

• Note: optional arguments are shown within <...>• Use __doc__ to check arguments

Page 88: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.7

Copyright 2007 Dassault Systèmes

Exploring Your Data

• printPaths>>> from odbAccess import *>>> from textRepr import *>>> odb = openOdb('cantilever.odb')>>> printPaths(odb, pathRoot='odb')odb.analysisTitleodb.closedodb.descriptionodb.diagnosticDataodb.isReadOnlyodb.jobDataodb.nameodb.partsodb.pathodb.rootAssemblyodb.sectionCategoriesodb.sectorDefinitionodb.stepsodb.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

L4.8

Copyright 2007 Dassault Systèmes

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 xfieldOutputs['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']

Page 89: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.9

Copyright 2007 Dassault Systèmes

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.componentLabelsstring stress.descriptionFieldLocationArray stress.locationsstring stress.nameSymbolicConstant stress.typetuple stress.validInvariantsFieldValueArray 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)

Copyright 2007 Dassault Systèmes

Abaqus Architecture

Page 90: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.11

Copyright 2007 Dassault Systèmes

Abaqus Architecture

Abaqus/CAEkernel

Abaqus/CAEkernel

Abaqusanalysis

Abaqusanalysis

Input file

WIP messagesODB files

Python interpreterPython

interpreter

AbaqusGUI

AbaqusGUI

Commandline

interpreter

Commandline

interpreter

Python interpreterPython

interpreterReplay

fileReplay

file

Update messages

• Abaqus has three processes: kernel, GUI, and analysis.

Kernelscript

Kernelscript

GUIscriptGUI

scriptC

omm

and s

Introduction to Python and Scripting in Abaqus

L4.12

Copyright 2007 Dassault Systèmes

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.

Page 91: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Job Monitoring

Introduction to Python and Scripting in Abaqus

L4.14

Copyright 2007 Dassault Systèmes

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.

Page 92: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.15

Copyright 2007 Dassault Systèmes

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 typesmonitorManager.addMessageCallback(ANY_JOB,

ANY_MESSAGE_TYPE, printMessages, None)

Introduction to Python and Scripting in Abaqus

L4.16

Copyright 2007 Dassault Systèmes

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()

Page 93: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Custom Data

Introduction to Python and Scripting in Abaqus

L4.18

Copyright 2007 Dassault Systèmes

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.customDataAttributeError: 'Mdb' object has no attribute 'customData'>>> import customKernel>>> mdb.customDatamdb.customData

• Adding data is simple, i.e.>>> mdb.customData.myDict = {}

Page 94: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.19

Copyright 2007 Dassault Systèmes

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

L4.20

Copyright 2007 Dassault Systèmes

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 bepickled, but the modules containing the class definitions must be available when unpickling the data.

Page 95: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Abaqus/CAE Plug-ins

Introduction to Python and Scripting in Abaqus

L4.22

Copyright 2007 Dassault Systèmes

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.

Page 96: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.23

Copyright 2007 Dassault Systèmes

Abaqus/CAE Plug-ins

• Example• myUtils.py

def printTime():import timet = time.localtime()print 'The time is: %d:%d' %d/%d/%d' % \

(t[3], t[4], t[1], t[2], t[0])

• time_plugin.pyfrom abaqusGui import getAFXApptoolset = 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

L4.24

Copyright 2007 Dassault Systèmes

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.

Page 97: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Debugging Scripts

Introduction to Python and Scripting in Abaqus

L4.26

Copyright 2007 Dassault Systèmes

Debugging Scripts

• Debugging methods• Tracebacks

• Exceptions and asserts

• Print statements

• PyChecker

• Python Debugger

• Write a test function

• Replay File Utility

• Use an IDE

Page 98: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.27

Copyright 2007 Dassault Systèmes

Debugging Scripts

• Tracebacks• Python tracebacks are a good debugging tool.• Example:

File "testTraceback.py", line 3, in ?a()

File ".\aTest.py", line 4, in ab()

File ".\bTest.py", line 2, in b1/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

L4.28

Copyright 2007 Dassault Systèmes

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

Page 99: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.29

Copyright 2007 Dassault Systèmes

Debugging Scripts

• The Python Debugger• Python provides a debugger, the pdb module.

>>> import pdb>>> import mymodule>>> pdb.run('mymodule.test()')> <string>(0)?()(Pdb) continue> <string>(1)?()(Pdb) continueNameError: 'spam'> <string>(1)?()(Pdb)

• Can move up and down the stack, inspect variables, etc.(Pdb) ?EOF a alias args bbreak c cl clear conditioncont continue d disable downenable h help ignore llist n next p qquit r return s steptbreak u unalias up wwhatis where

• The pdb module is documented in the Python Library Reference.

Introduction to Python and Scripting in Abaqus

L4.30

Copyright 2007 Dassault Systèmes

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.

Page 100: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.31

Copyright 2007 Dassault Systèmes

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

L4.32

Copyright 2007 Dassault Systèmes

Debugging Scripts

• IDE examples

Komodo

IDLE

Pythonwin

Page 101: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Object-Oriented Programming

Introduction to Python and Scripting in Abaqus

L4.34

Copyright 2007 Dassault Systèmes

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 object-oriented features of Python can help you write better code.

Page 102: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.35

Copyright 2007 Dassault Systèmes

Object-Oriented Programming

• DefinitionsObject 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

L4.36

Copyright 2007 Dassault Systèmes

Object-Oriented Programming

• DefinitionsEncapsulation 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

Page 103: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.37

Copyright 2007 Dassault Systèmes

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 = sizeself.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.size5.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

L4.38

Copyright 2007 Dassault Systèmes

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.

Animal

Cat Dog

Abaqus user

Mammal

Primate

Example of an animal class hierarchy intended to demonstrate class inheritance

Generalized class

Specialized class

A Cat IsA Mammal IsA Animal

Page 104: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.39

Copyright 2007 Dassault Systèmes

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 Abaqusobject 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

L4.40

Copyright 2007 Dassault Systèmes

Object-Oriented Programming

Polymorphism The ability to substitute objects of matching interface for one another at run time.

Circle

Drawingprimitive

Triangle Square

def refreshCanvas():

for dp in drawingPrimitives:dp.draw()

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.

Page 105: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.41

Copyright 2007 Dassault Systèmes

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 methoddef 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 classself.size = float(size)

def draw(self): # override base class draw methods = 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

L4.42

Copyright 2007 Dassault Systèmes

Object-Oriented Programming

• Test a square

>>> sq = Square(5)>>> sq.size5.0>>> sq.color'Red'>>> sq.setColor('Blue')>>> sq.color'Blue'>>> sq.draw()

Page 106: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Python Classes

Introduction to Python and Scripting in Abaqus

L4.44

Copyright 2007 Dassault Systèmes

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<__main__.Plain instance at 00896A7C>

Page 107: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.45

Copyright 2007 Dassault Systèmes

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 bPoint 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

L4.46

Copyright 2007 Dassault Systèmes

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'<type 'instance'>

• To find the class, need the __class__ attribute.>>> sq.__class__ # __class__ contains the class object<class __main__.Square at 008C6534>>>> sq.__class__.__name__ # get the class name'Square'

Page 108: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.47

Copyright 2007 Dassault Systèmes

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')>>> cSpam('Point 1')>>> c.x = 2.1Traceback (most recent call last):File "<stdin>", 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

L4.48

Copyright 2007 Dassault Systèmes

Python Classes

• ... and more__getattr__ __setattr____getitem__ __setitem__ __len__ __nonzero__ __cmp__ __call____add__ __sub__ __mul__ __div__ (__iadd__ etc)__lt__ __le__ __eq__ __ne__ __ge__ __gt__

Page 109: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.49

Copyright 2007 Dassault Systèmes

Python Classes

• Guidelines for Abaqus work:

• Add members in __init __ only.

• Read the style guide.

• Abaqus Answer 2483

Copyright 2007 Dassault Systèmes

Example

Page 110: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.51

Copyright 2007 Dassault Systèmes

Example

• Extrusion examplefrom 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 = modelself.name = nameself.depth = depthself.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

L4.52

Copyright 2007 Dassault Systèmes

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 = widthself.height = heightself.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)

Page 111: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Introduction to Python and Scripting in Abaqus

L4.53

Copyright 2007 Dassault Systèmes

Example

class Cylinder(Extrusion):"""Cylinder(model, name, radius, depth)"""

def __init__(self, model, name, radius, depth):Extrusion.__init__(self, model, name, depth)self.radius = radiusself.sketch.CircleByCenterPerimeter(center=(0.0, 0.0),

point1=(0.0, radius))self.createPartUsingSketch()

def getVolume(self):import mathreturn 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

L4.54

Copyright 2007 Dassault Systèmes

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

Page 112: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes

Workshop

Introduction to Python and Scripting in Abaqus

L4.56

Copyright 2007 Dassault Systèmes

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.

Page 113: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Preliminaries

Copyright 2007 Dassault Systèmes Preliminaries for Abaqus Workshops

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.

Page 114: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

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.)

Page 115: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

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: more filename.inp Windows NT: type filename.inp | more This step will scroll through the file one page at a time.

Now you are ready to start the workshops.

Page 116: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 1.1

Output the Fibonacci Series

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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 with k0=0 and k1=1

Page 117: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 1.1

Output the Fibonacci Series

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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

Page 118: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 1.2

Circle Module

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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.).

Page 119: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 1.2

Circle Module

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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))

Page 120: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 2.1

Session Commands

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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)

Page 121: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 2.1

Session Commands

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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, 'Front'), (margin*2+width, margin*20, 'Top'), (margin, margin*22+height, 'Left'), (margin*2+width, margin*22+height, 'Iso'), ) odb = session.openOdb(odbPath) 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')

Page 122: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 2.2

A Macro to Create a Library of Materials

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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 200 E 9 Poisson's ratio 0.3 Density 7800 Yield Stress, Plastic Strain 400 E 6, 0.00 420 E 6, 0.02 500 E 6, 0.20 600 E 6, 0.50

Copper

Young's Modulus 110 E 9 Poisson's ratio 0.3 Density 8970 Yield Stress, Plastic Strain 314 E 6, 0.00

Page 123: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

W2.2–2

Aluminum

Young's Modulus 70 E 9 Poisson's ratio 0.35 Density 2700 Yield Stress, Plastic Strain, Temp 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.

Page 124: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 2.2

A Macro to Create a Library of Materials

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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,),))

Page 125: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 3.1

Linear Superposition of Results

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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.)

Page 126: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

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,))

Page 127: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 3.1

Linear Superposition of Results

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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,))

Page 128: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 3.2

Create an ODB from a Text File

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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.

Page 129: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

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.

Page 130: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 3.2

Create an ODB from a Text File

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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

Page 131: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

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()

Page 132: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop 4.1

Job Monitoring

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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.

Page 133: Introduction to Python and Scripting in Abaqusread.pudn.com/downloads648/ebook/2633377/Scripting... · ABAQUS, Inc., assumes no responsibility for any errors that may appear in this

Workshop Answers 4.1

Job Monitoring

Copyright 2007 Dassault Systèmes Introduction to Python and Scripting in Abaqus

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()