Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced...

33
Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview Exploring Your Data Abaqus Architecture Job Monitoring Custom Data Plug-ins Debugging Scripts Abaqus PDE Object-Oriented Programming Python Classes Example Workshops

Transcript of Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced...

Page 1: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Advanced TopicsLecture 4

L4.2

Introduction to Python and Scripting in Abaqus

Overview

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

Page 2: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Exploring Your Data

L4.4

Introduction to Python and Scripting in Abaqus

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': 'Repositoryobject', 'path': 'd:\temp\cantilever.odb', 'rootAssembly': 'OdbAssembly object', 'sectionCategories': 'Repository object', 'sectorDefinition': None, 'steps': 'Repository object', 'userData': 'UserData object'})

Page 3: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.5

Introduction to Python and Scripting in Abaqus

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)

L4.6

Introduction to Python and Scripting in Abaqus

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 4: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.7

Introduction to Python and Scripting in Abaqus

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

L4.8

Introduction to Python and Scripting in Abaqus

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 5: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.9

Introduction to Python and Scripting in Abaqus

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)

Abaqus Architecture

Page 6: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.11

Introduction to Python and Scripting in Abaqus

Abaqus Architecture

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

Abaqus/CAE kernel

Abaqus/CAE kernel

Abaqus analysis

Abaqus analysis

Input file

WIP messagesODB files

Python interpreterPython

interpreter

Abaqus GUI

Abaqus GUI

Commandline

interpreter

Commandline

interpreter

Python interpreterPython

interpreterReplay

fileReplay

file

Update messages

Kernelscript

Kernelscript

GUIscriptGUI

scriptC

omm

and s

L4.12

Introduction to Python and Scripting in Abaqus

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 7: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Job Monitoring

L4.14

Introduction to Python and Scripting in Abaqus

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 8: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.15

Introduction to Python and Scripting in Abaqus

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)

L4.16

Introduction to Python and Scripting in Abaqus

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 9: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Custom Data

L4.18

Introduction to Python and Scripting in Abaqus

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 10: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.19

Introduction to Python and Scripting in Abaqus

Custom Data

• mdb.customData (cont’d)• 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']

L4.20

Introduction to Python and Scripting in Abaqus

Custom Data

• mdb.customData (cont’d)• 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 11: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Plug-ins

L4.22

Introduction to Python and Scripting in Abaqus

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 briefly 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 12: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.23

Introduction to Python and Scripting in Abaqus

Plug-ins

• Kernel Plug-in 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

L4.24

Introduction to Python and Scripting in Abaqus

Plug-ins

• Kernel Plug-in Example (cont’d)• 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 13: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.25

Introduction to Python and Scripting in Abaqus

Plug-ins

• GUI Plug-in• GUI plug-ins execute Abaqus GUI Toolkit commands (details are not

addressed in this seminar).

• An alternative to using the Abaqus GUI Toolkit commands is the RSG(Really Simple GUI) Dialog Builder.

• RSG:

• Provides access to a subset of the commands in the Abaqus GUI Toolkit

• Requires no GUI programming experience

• Dialog boxes created become stand-alone plug-ins

• Workshop 4.2 shows how to create a plug-in using RSG

Debugging Scripts

Page 14: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.27

Introduction to Python and Scripting in Abaqus

Debugging Scripts

• Debugging methods• Tracebacks

• Exceptions and asserts

• Print statements

• PyChecker

• Python Debugger

• Write a test function

• Replay File Utility

• Use an IDE

L4.28

Introduction to Python and Scripting in Abaqus

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

Page 15: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.29

Introduction to Python and Scripting in Abaqus

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

L4.30

Introduction to Python and Scripting in Abaqus

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.

Page 16: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.31

Introduction to Python and Scripting in Abaqus

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.

L4.32

Introduction to Python and Scripting in Abaqus

Debugging Scripts

• Integrated Development Environment (IDE)• Testing an algorithm in an Integrated Development Environment, such

as PythonWin, WingIDE, IDLE, or Komodo, can make the debugging easier.

• When the code works correctly, try it with Abaqus Python.

• You cannot access Abaqus modules directly from these IDEs.

• Note: These IDEs are not delivered with Abaqus, but they are available on the Internet. Idle and PythonWin are free; the others have a free trial period.

• An alternative and built-in Python IDE (Abaqus PDE) is discussed shortly.

Page 17: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.33

Introduction to Python and Scripting in Abaqus

Debugging Scripts

• Integrated Development Environment (IDE)• Need to start the IDE with abaqus python

• Example: start PythonWin in abaqus python

• start_pythonwin.pyimport sys, win32uiimport pywin.framework.intpyapp# Remove this script from argv, or pythonwin will edit itdel sys.argv[0]# And bootstrap the app.app = win32ui.GetApp()app.InitInstance()app.Run()

> abaqus python start_pythonwin.py

Abaqus PDE

Page 18: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.35

Introduction to Python and Scripting in Abaqus

Abaqus PDE

• Using the Abaqus PDE, you can:• Edit Python files.

• Record GUI actions to create a guiLog script.

• Run a Python script in the kernel, or GUI (a guiLog), or outside Abaqus/CAE.

• Set a delay between Python commands.

• Set breakpoints in the Python code.

• Watch each line being executed.

• Step through the code line by line, step into a function, and examine variable values.

• Step through Python code of a plug-in.• See variable values in a Watch window.

• Access the Python interpreter in the GUI (similar to the kernel CLI).

• Reload any edited Python modules without restarting Abaqus/CAE.

• Step through custom startup module code.

L4.36

Introduction to Python and Scripting in Abaqus

Abaqus PDE

• Starting Abaqus PDE

• Standalone

• Abaqus/CAE and PDE

• From within Abaqus/CAE

Page 19: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.37

Introduction to Python and Scripting in Abaqus

Abaqus PDE

• Abaqus PDE interface

L4.38

Introduction to Python and Scripting in Abaqus

Abaqus PDE

• The GUI Command Line Interface (CLI)• Can be used to find Python variable values in the GUI process.

• Any GUI API can be called, for testing a dialog for example.

GUI CLI

Select process to run in GUI

Page 20: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.39

Introduction to Python and Scripting in Abaqus

Abaqus PDE

• The Kernel Command Line Interface (CLI) Kernel process

Breakpoint

Watch list on variable ‘p’

Step through kernel script

Syntax coloring

L4.40

Introduction to Python and Scripting in Abaqus

Abaqus PDE

• PDE outside Abaqus/CAE• Can be used to debug utility or odb API scripts

• Script can be selected by using Main File in PDE GUI, or by specifying the file on the command line abq pde –script local.py

Run in “Local” process

GUI CLI not available when outside Abaqus/CAE

Page 21: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Object-Oriented Programming

L4.42

Introduction to Python and Scripting in Abaqus

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 22: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.43

Introduction to Python and Scripting in Abaqus

Object-Oriented Programming

• Definitions• Object A run-time entity that packages both data and the

procedures that operate on that data.• In Python the data and procedures are called members and

methods, respectively.

• members and methods are both attributes of the object.

An object is an instance of a class or type.(A Python class is implemented in Python, a Python type is implemented in C.)

• Class A class defines the data and procedures that operate on that data.

L4.44

Introduction to Python and Scripting in Abaqus

Object-Oriented Programming

• Definitions (cont’d)• Encapsulation The result of hiding a representation and

implementation in an object. The representation is not visible and cannot be accessed directly from outside the object. Operations are the only way to access and modify an object's representation.

(Note: Python does not hide the data of a class instance.)

All definitions taken from Design Patterns: Elements of Reusable Object-Oriented Software, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison-Wesley, 1995

Page 23: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.45

Introduction to Python and Scripting in Abaqus

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.

L4.46

Introduction to Python and Scripting in Abaqus

Object-Oriented Programming

• Definitions (cont’d)• 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 classA Cat IsA Mammal IsA Animal

Page 24: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.47

Introduction to Python and Scripting in Abaqus

Object-Oriented Programming

• Definitions (cont’d)• Interface The set of all signatures defined by an object's

operations. The interface describes the set of requests to which an object can respond.

The members, methods and their arguments, and operators defined in the Abaqus Scripting Manual for each Abaqus object are the object's interface.

A base class may define an interface that can be implemented differently in each derived class.

A collection of objects of the same base type can then be used as if they are the same. This is called polymorphism.

An abstract base class is one whose interface is not fully implemented in the class. Such a class should not be instantiated, and the interface must be implemented in each derived class.

L4.48

Introduction to Python and Scripting in Abaqus

Object-Oriented Programming

• Definitions (cont’d)• 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 25: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.49

Introduction to Python and Scripting in Abaqus

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)

L4.50

Introduction to Python and Scripting in Abaqus

Object-Oriented Programming

• Test a square

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

Page 26: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Python Classes

L4.52

Introduction to Python and Scripting in Abaqus

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 27: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.53

Introduction to Python and Scripting in Abaqus

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.

L4.54

Introduction to Python and Scripting in Abaqus

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 28: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.55

Introduction to Python and Scripting in Abaqus

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

L4.56

Introduction to Python and Scripting in Abaqus

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 29: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.57

Introduction to Python and Scripting in Abaqus

Python Classes

• Guidelines for Abaqus work:

• Add members in __init __ only.

• Read the style guide.

• SIMULIA Answer 2483

Example

Page 30: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.59

Introduction to Python and Scripting in Abaqus

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"

L4.60

Introduction to Python and Scripting in Abaqus

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 31: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.61

Introduction to Python and Scripting in Abaqus

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)

L4.62

Introduction to Python and Scripting in Abaqus

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 32: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

Workshops

L4.64

Introduction to Python and Scripting in Abaqus

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 33: Advanced Topics - pudn.comread.pudn.com/downloads611/ebook/2491718/Abaqus_python.pdf · Advanced Topics Lecture 4 L4.2 Introduction to Python and Scripting in Abaqus Overview •

L4.65

Introduction to Python and Scripting in Abaqus

Workshop 4.2: Creating kernel and GUI scripts

• This workshop shows how to create a kernel script from a replay file and how to use RSG to build dialogs and connect to the kernel script.