当前位置:文档之家› Abaqus二次开发高级专题

Abaqus二次开发高级专题

Advanced Topics

Lecture 4

L4.2 Overview

?Exploring Your Data

?Abaqus Architecture

?Job Monitoring

?Custom Data

?Plug-ins

?Debugging Scripts

?Abaqus PDE

?Object-Oriented Programming

?Python Classes

?Example

?Workshops

Introduction to Python and Scripting in Abaqus

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

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

Introduction to Python and Scripting in Abaqus

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

odb.closed

odb.description

odb.diagnosticData

odb.isReadOnly

odb.jobData

https://www.doczj.com/doc/631412858.html,

odb.parts

odb.path

odb.rootAssembly

odb.sectionCategories

odb.sectorDefinition

odb.steps

https://www.doczj.com/doc/631412858.html,erData

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

fieldOutputs['S']

fieldOutputs['PE']

fieldOutputs['RF']

fieldOutputs['PEEQ']

fieldOutputs['LE']

fieldOutputs['PEMAG']

fieldOutputs['AC YIELD']

fieldOutputs['CF']

fieldOutputs['U']

>>> y = x.splitlines()

>>> print y[3]

fieldOutputs['PEEQ']

Exploring Your Data

?printTypes

?Returns the type of each member

>>> stress = odb.steps['Step-1'].frames[87].fieldOutputs['S']

>>> printTypes(stress, pathRoot='stress')

tuple https://www.doczj.com/doc/631412858.html,ponentLabels

string stress.description

FieldLocationArray stress.locations

string https://www.doczj.com/doc/631412858.html,

SymbolicConstant stress.type

tuple stress.validInvariants

FieldValueArray stress.values

?Print the value of each member using getPaths()and eval(path) for path in getPaths(obj).splitlines():

print '%-20s %s' % (eval(path), path)

Introduction to Python and Scripting in Abaqus

Abaqus Architecture

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 messages ODB files

Python interpreter Python interpreter Abaqus GUI Abaqus GUI Command line interpreter

Command line interpreter Python interpreter Python interpreter Replay file Replay file Update messages

Kernel script Kernel script GUI script

GUI script C o m m a n d 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.

Job Monitoring

L4.14 Job Monitoring

?What is job monitoring?

?Receiving messages from the analysis process while it is executing.?Responding to messages from jobs

?In some cases you may want to process messages from the analysis

while it is running; for example, to terminate it when a criterion is

reached or to plot results as the analysis progresses.

?This is accomplished by writing a callback function and registering it with the monitorManager object.

Introduction to Python and Scripting in Abaqus

L4.15 Job Monitoring

?Example

?The following code will print all the messages from the analysis: from abaqus import *

from jobMessage import ANY_JOB, ANY_MESSAGE_TYPE

# define a callback function

def printMessages(jobName, mType, data, userData):

print 'Job name: %s, Message type: %s'%(jobName, mType)

print 'data members:'

members = dir(data)

format = ' %-18s %s'

print format%('member', 'value')

for member in members:

memberValue = getattr(data, member)

print format%(member, memberValue)

# call the function for all jobs, and all message types

monitorManager.addMessageCallback(ANY_JOB,

ANY_MESSAGE_TYPE, printMessages, None)

Introduction to Python and Scripting in Abaqus

L4.16 Job Monitoring

?Waiting for jobs to complete

?The easiest way to write scripts that perform some action (i.e.,change

the model, visualize results) based on the results of the analysis is to

have the script wait for the analysis to complete.

?In the following example, the script submits myJob1and waits for it to

complete before submitting myJob2.

myJob1 = mdb.Job(name='Job-1', model='Model-1')

myJob2 = mdb.Job(name='Job-2', model='Model-2')

myJob1.submit()

myJob1.waitForCompletion()

myJob2.submit()

myJob2.waitForCompletion()

Introduction to Python and Scripting in Abaqus

Custom Data

L4.18 Custom Data

?mdb.customData

?User specified data, using Python objects or user specified classes

?Persistent (saved to .cae file)

?Lazy evaluation, on import customKernel i.e.

>>> mdb.customData

AttributeError: 'Mdb' object has no attribute 'customData'

>>> import customKernel

>>> mdb.customData

mdb.customData

?Adding data is simple, i.e.

>>> mdb.customData.myDict = {}

Introduction to Python and Scripting in Abaqus

L4.19 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']

Introduction to Python and Scripting in Abaqus

L4.20 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 be

pickled, but the modules containing the class definitions must be

available when unpickling the data.

Introduction to Python and Scripting in Abaqus

Plug-ins

L4.22 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.

Introduction to Python and Scripting in Abaqus

Plug-ins

?Kernel Plug-in Example

?myUtils.py

def printTime():

import time

t = time.localtime()

print 'The time is: %d:%d' %d/%d/%d' % \

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

?time_plugin.py

from abaqusGui import getAFXApp

toolset = getAFXApp().getAFXMainWindow().getPluginToolset()

toolset.registerKernelMenuButton(moduleName='myUtils', functionName='printTime()',

buttonText='Print Time')

?The above files are placed in a directory named abaqus_plugins

Introduction to Python and Scripting in Abaqus

L4.24 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.

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

Introduction to Python and Scripting in Abaqus

Debugging Scripts

Debugging Scripts

?Debugging methods

?Tracebacks

?Exceptions and asserts

?Print statements

?PyChecker

?Python Debugger

?Write a test function

?Replay File Utility

?Use an IDE

Introduction to Python and Scripting in Abaqus

L4.28 Debugging Scripts

?Tracebacks

?Python tracebacks are a good debugging tool.

?Example:

File "testTraceback.py", line 3, in ?

a()

File ".\aTest.py", line 4, in a

b()

File ".\bTest.py", line 2, in b

1/0

ZeroDivisionError: integer division or modulo by zero ?The traceback clearly describes the location in the code (file, line number, and function name) and the type of error.

?Exceptions

?Raise an exception to indicate some type of error.

if not myDict.has_key(key):

raise KeyError, 'myDict does not have key: %s' % key

Introduction to Python and Scripting in Abaqus

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

> (0)?()

(Pdb) continue

> (1)?()

(Pdb) continue

NameError: 'spam'

> (1)?()

(Pdb)

?Can move up and down the stack, inspect variables, etc.

(Pdb) ?

EOF a alias args b

break c cl clear condition

cont continue d disable down

enable h help ignore l

list n next p q

quit r return s step

tbreak u unalias up w

whatis where

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

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: https://www.doczj.com/doc/631412858.html,

?Defines a TestCase class that will setup the test problem, run it, and

report errors. You derive your own class from TestCase to test your

problem.

?Can be used to run large test suites.

Introduction to Python and Scripting in Abaqus

L4.32 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.

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

import sys, win32ui

import pywin.framework.intpyapp

# Remove this script from argv, or pythonwin will edit it

del sys.argv[0]

# And bootstrap the app.

app = win32ui.GetApp()

app.InitInstance()

app.Run()

> abaqus python start_pythonwin.py

Introduction to Python and Scripting in Abaqus

Abaqus PDE

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.

Introduction to Python and Scripting in Abaqus

L4.36 Abaqus PDE

?Starting Abaqus PDE

?Standalone

?Abaqus/CAE and PDE

?From within Abaqus/CAE

Introduction to Python and Scripting in Abaqus

Abaqus PDE

?Abaqus PDE interface

Introduction to Python and Scripting in Abaqus

L4.38 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.

Select process

to run in GUI

GUI CLI

Introduction to Python and Scripting in Abaqus

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

相关主题
文本预览
相关文档 最新文档