Vous êtes sur la page 1sur 178

tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.

com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

DASSAULT SYSTÈMES SIMULIA CORP.


RISING SUN MILLS
166 VALLEY STREET
PROVIDENCE, RI 02909-2499
www.simulia.com

January 10, 2013

Release Authorization and Stipulations

Dassault Systemes Simulia Corp. (SIMULIA) retains the copyright to this document.
These training notes are available by special arrangement from the SIMULIA
Learning Community to the Authorized Party (company or individual) whose
details appear in the watermarked text.

Release of these training notes in PDF format is made with the following
stipulations:

1. The materials are for personal use by the Authorized Party only.

2. The Authorized Party may view and print these training files, but must not
otherwise attempt to modify their contents, or extract content from the files.

3. The training notes may not be distributed or otherwise retransmitted without


separate, express written approval from SIMULIA.

4. The training notes may not be sold.

Visit the SIMULIA Learning Community (www.simulia.com/learning) for additional


training materials, tutorials and technical commentary.

Dassault Systèmes | www.3ds.com


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Introduction to Abaqus Scripting


www.3ds.com | © Dassault Systèmes

R 6.12

About this Course

Course objectives
Help students to develop a high level understanding of the Abaqus scripting capabilities.
Organize and present the technical details of Python and the Abaqus Scripting Interface.
Expose the strengths and weaknesses of Abaqus scripting.
Encourage the student to use scripting in new ways.

Targeted audience
www.3ds.com | © Dassault Systèmes

Analysts.

Prerequisites
None.

2 days
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Day 1

Lecture 1 Overview of Scripting in Abaqus


Workshop 1 Creating a Basic Abaqus Script

Lecture 2 Why Python?


Workshop 2 Running Python

Lecture 3 Python Core Language Part 1


Workshop 3 Python Types, Operators, and Expressions
www.3ds.com | © Dassault Systèmes

Workshop 4 Investigating Python Objects

Lecture 4 Python Core Language Part 2


Workshop 5 Defining a Function for a Series Calculation
Workshop 6 Modules

Day 2

Lecture 5 More on Abaqus Scripting Basics


Workshop 7 Creating a Macro and Getting Input interactively

Lecture 6 Abaqus Object Model


Workshop 8 Working with the Session Object

Lecture 7 Postprocessing with Abaqus Scripting


Workshop 9 Working with the ODB Object
www.3ds.com | © Dassault Systèmes

Workshop 10 Linear Superposition

Lecture 8 Miscellaneous Topics


Workshop 11 Creating Kernel and GUI Scripts
Workshop 12 Setting Abaqus Defaults
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Legal Notices

The Abaqus Software described in this documentation is available only under license from Dassault
Systèmes and its subsidiary and may be used or reproduced only in accordance with the terms of such
license.
This documentation and the software described in this documentation are subject to change without
prior notice.
Dassault Systèmes and its subsidiaries shall not be responsible for the consequences of any errors or
omissions that may appear in this documentation.
www.3ds.com | © Dassault Systèmes

No part of this documentation may be reproduced or distributed in any form without prior written
permission of Dassault Systèmes or its subsidiary.
© Dassault Systèmes, 2012.
Printed in the United States of America
Abaqus, the 3DS logo, SIMULIA and CATIA are trademarks or registered trademarks of Dassault
Systèmes or its subsidiaries in the US and/or other countries.
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 6.12 Release Notes and the notices at:
http://www.3ds.com/products/simulia/portfolio/product-os-commercial-programs.

Revision Status

Lecture 1 8/12 Updated for 6.12


Lecture 2 8/12 Updated for 6.12
Lecture 3 8/12 Updated for 6.12
Lecture 4 8/12 Updated for 6.12
Lecture 5 8/12 Updated for 6.12
Lecture 6 8/12 Updated for 6.12
Lecture 7
www.3ds.com | © Dassault Systèmes

8/12 Updated for 6.12


Lecture 8 8/12 Updated for 6.12
Appendix 1 8/12 Updated for 6.12
Workshop 1 8/12 Updated for 6.12
Workshop 2 8/12 Updated for 6.12
Workshop 3 8/12 Updated for 6.12
Workshop 4 8/12 Updated for 6.12
Workshop 5 8/12 Updated for 6.12
Workshop 6 8/12 Updated for 6.12
Workshop 7 8/12 Updated for 6.12
Workshop 8 8/12 Updated for 6.12
Workshop 9 8/12 Updated for 6.12
Workshop 10 8/12 Updated for 6.12
Workshop 11 8/12 Updated for 6.12
Workshop 12 8/12 Updated for 6.12
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.1
Lesson 1: Overview of Scripting in Abaqus

Lesson content:

Overview
Terminology
Types and Languages for Customizing Abaqus
Examples
Abaqus Scripting Interface Basics
www.3ds.com | © Dassault Systèmes

Creating a Basic Abaqus Script


Workshop Preliminaries
Workshop 1: Creating a Basic Abaqus Script

75 minutes

L1.2
Overview (1/5)

Just the facts:

A 3rd-party programming language called Python is embedded within the Abaqus product line.

SIMULIA has extended the functionality of Python to provide an interface to Abaqus data.

These extensions are referred to as the Abaqus Scripting Interface (ASI).

What we think:
www.3ds.com | © Dassault Systèmes

The Python-based Abaqus Scripting Interface is an excellent framework for:

Automating modeling tasks

Augmenting the functionality of the interactive products

The productivity of every Abaqus analyst can benefit from scripting.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.3
Overview (2/5)

Motivation: why customize Abaqus?


Automate repetitive tasks Provides automated
environment for experienced
Model building analysts

Job submission and monitoring


www.3ds.com | © Dassault Systèmes

Postprocessing

Prescribe default behavior Customized versions

Customized
application
of Abaqus provide an
Extend functionality effective analysis tool
Enhance the interface for a wide range of
user expertise …
Graphical

Nongraphical

Provides
advanced analysis functionality
to non-FEA users

L1.4
Overview (3/5)

Process automation can deliver

Repeatability, productivity, and quality to proven workflows and methods throughout the design and
validation process

Automated FEA Processes Impact Here


Conceptual analyses Design Studies Late design changes
www.3ds.com | © Dassault Systèmes

Concept Design Validation Manufacture

Customized solutions for specific applications, via customer-preferred interface (web, familiar user
interface, PLM system)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.5
Overview (4/5)

Abaqus Scripting predominantly affects Abaqus/CAE


customization

Abaqus/CAE customization

The ASI allows you to customize much of the behavior of Abaqus pre- and postprocessing to suit your
specific requirements.
www.3ds.com | © Dassault Systèmes

Scripts that affect the Graphical User Interface are called GUI scripts. Those that do not are called
kernel scripts. GUI scripts are not discussed in this course.

Analysis customization

The Abaqus analysis products may be customized with user subroutines.

Site customization

Hardware, operating system, batch queuing, etc. may be tuned for Abaqus performance.

L1.6
Overview (5/5)

Resources: Two manuals* are presently available for scripting


www.3ds.com | © Dassault Systèmes

* These two manuals are available in electronic format only.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.7
Terminology (1/2)

Application Programming Interface (API)

A set of routines, protocols, and tools that makes it easier to develop a software application.

Abaqus Scripting Interface (ASI)

An API to the data used by Abaqus; an extension of the Python programming language.
www.3ds.com | © Dassault Systèmes

Abaqus/CAE kernel

The portion of Abaqus/CAE that interprets the Abaqus Scripting Interface commands to create an
internal representation of the model.

Graphical User Interface (GUI)

An interface between the user and Abaqus/CAE kernel. The interface allows the user to specify
geometry and select options from dialog boxes.

L1.8
Terminology (2/2)

Programming language

Designed mainly for building algorithms from scratch.

Programming languages are compiled and linked to create a .exe file.

Examples of programming languages are C, C++, Fortran, etc.


www.3ds.com | © Dassault Systèmes

Scripting language

Designed for effective integration with components written in other computer languages.

Scripting languages are interpreted so they do not create a .exe file.

Examples of scripting languages are Python, Tcl, Perl, etc.

Customization

Something that has been altered according to individual specifications. Here, we often are referring to a
collection of Abaqus scripts and/or user subroutines.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.9
Types and Languages for Customizing Abaqus (1/4)

Types of customization

Kernel customization

Kernel (nongraphical) scripts allow you to create new functions to perform modeling or
postprocessing tasks

I. Use existing Abaqus/CAE commands


» Edit replay files
www.3ds.com | © Dassault Systèmes

» Record macros

II. Create custom commands and objects using Python

Parametric scripts allow you to generate and execute the results of multiple analyses that differ
only in the values of some of the parameters used in place of input quantities

Environment files allow you to change various default settings

Simple dialog boxes

I. Use getInput or getInputs to prompt a user for input

L1.10
Types and Languages for Customizing Abaqus (2/4)

Types of customization (cont’d)

GUI customization

Dialogs

I. Collect inputs from the user using


a variety of widgets from the GUI
toolkit
www.3ds.com | © Dassault Systèmes

Modules and toolsets

I. Create custom modules or


toolsets to provide new
capabilities

Applications

I. Create specialized “vertical”


applications for specific needs

Note this seminar does not cover GUI


Customization. However, the RSG (Really
Simple GUI) technique to make GUI dialogs is
covered and is sufficient for most routine
requirements.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.11
Types and Languages for Customizing Abaqus (3/4)

Languages for customizing Abaqus

Abaqus (input file syntax, API, user subroutines)

Required (but not really a language).

Fortran, C
www.3ds.com | © Dassault Systèmes

Required for analysis product customization (Abaqus user subroutines)

Python, C++

Required for non-analysis product customization

Python is not a product developed by Abaqus

Python is distributed with the Abaqus software

GUI Toolkit (Based on Fox Toolkit)

Another extension of the Python language

Helpful for GUI customization

L1.12
Types and Languages for Customizing Abaqus (4/4)

Languages for customizing Abaqus (cont’d)

Python is integrated with Abaqus in several ways.

The environment file (abaqus_v6.env) uses Python statements.

The input file (.inp) accepts parameter definitions using Python statements in the data lines of
the *PARAMETER option.
www.3ds.com | © Dassault Systèmes

The parametric scripting file (scriptname.psf) uses Python to provide a basis for defining
parametric modeling studies.

The journal files ( .rpy, .jnl,.rec) record Python commands.

Tasks can be executed in Abaqus/CAE and Abaqus/Viewer using Python commands.

The Macro feature of Abaqus/CAE uses a Python script.

The output database file (.odb) can be accessed directly using a Python script.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.13
Example: Postprocessing through Abaqus Scripting Interface

One of the simplest ways to customize


Abaqus is to develop kernel scripts to
perform modeling or postprocessing tasks

In this example a kernel script has been


developed to interact with an output
database file through the Abaqus Scripting
www.3ds.com | © Dassault Systèmes

Interface

The script searches for the maximum


value of von Mises stress on a certain
model component.

L1.14
Example: *NMAP

Application

The *NMAP option is not supported through Abaqus/CAE

Perform *NMAP from within Abaqus/CAE on a flat plate with holes

Merge nodes on the common face


www.3ds.com | © Dassault Systèmes

Before *NMAP After *NMAP


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.15
Example: Plug-in to Automatically Generate Point-to-Point Springs, Dashpots, or MPC constraints

Plug-in to generate multiple spring and/or dashpot elements, or MPC constraints between proximal nodes of
neighboring parts.
www.3ds.com | © Dassault Systèmes

L1.16
Example: Customization through Parametric Studies

Parametric studies allow the user to generate,


execute, and gather the results of multiple analyses
that differ only in the values of some of the
parameters used in place of input quantities

In this example parametric studies were used to


study the influence of material coefficients on the
response of a two-layer viscoplasticity model
www.3ds.com | © Dassault Systèmes
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

Application
Abaqus/CAE
Problem description

post processing tasks in


bellows design and analysis

or facilitate model building and


Create a custom application for

develop specific tools to automate


GUI Customization can be used to

Example: Bellows Custom Application


Example: Bellows Custom Application

L1.18
L1.17
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.19
Example: Vertical Application for Roll Pass

Roll pass design system for use at Corus

Corus is the leading metals solutions


provider formed by the merger of British
Steel and Koninklijke Hoogovens

This system allows the mill design


engineers to validate their designs using simulation,
www.3ds.com | © Dassault Systèmes

to carry out sensitivity studies


on key rolling parameters, and to investigate the
effectiveness of novel rolling techniques

The use of simulation reduces the requirement to


build expensive and complex prototype rolls,
providing rapid results and, therefore, reducing the
lead time and cost for the development of new
sections

This extremely advanced structural mechanics


application is used by roll designers with no FE
experience

L1.20
Example: Vertical Application for Roll Pass

Corus launched its roll pass design system


in 1999. Since that time mill trials have
decreased significantly

“We now introduce 75 percent of our


products into the mill without a physical trial
at all. We also have success in improved
www.3ds.com | © Dassault Systèmes

mill yield and throughput per hour. And on


one of our rolling mills this year we've
eliminated 90 roll changes, simply by
rationalizing design and shortening the mill.”
– David Jennings, manager of Corus
product and process development
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.21
Example: Web Customization

Honeywell Federal Manufacturing and Technologies*

Manages and operates the National Nuclear Security Administration’s (NNSA) Kansas City Plant

Web advisor project

HTML user interface


www.3ds.com | © Dassault Systèmes

Standardized programming language,


Python

Uses Abaqus/CAE kernel for


geometry modifications and meshing

Delivers finite element tools to any


engineer’s desk

Use Abaqus power without training


investment

Cost savings and avoidance


* Presented by Aaron Seaholm
at the Abaqus Midwest Users’
Conference, 2003.

L1.22
Example: Web Customization
www.3ds.com | © Dassault Systèmes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.23
Example: Spreadsheet Interface to Abaqus

Based on Abaqus Scripting API


and Excel/VBA API.

The user does not need to


know VBA.
www.3ds.com | © Dassault Systèmes

Excel can be directly used as


the GUI to drive Abaqus.

L1.24
Example: Automated Report Generation

Application

Copy image from Abaqus/CAE and paste into


an MS Word document

Format the MS Word figure and add text

Additional Information
www.3ds.com | © Dassault Systèmes

Software integration technology called


the Component Object Model (COM)
was developed by Microsoft to provide
users with an easy-to-use interface for
sharing functionality between different
programs.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.25
Example: Consultant-developed System—Scanscot Brigade

Scanscot Technology

Focused on providing analysis software for


structural, civil, and bridge engineering

Brigade product family uses Abaqus


technology for finite element analysis solution
www.3ds.com | © Dassault Systèmes

User interface for bridge design “vertical


applications” based on Abaqus/CAE platform

User interface customization and workflow


automation via open GUI toolkit

L1.26
Example: Abaqus Extension—Adjustable Rigid Torus (ART)

The Adjustable Rigid


Torus (ART) is an Abaqus
extension that provides a
graphical user interface
(GUI) in Abaqus/CAE to
supply the necessary
parameters used by the
subroutine, RSURFU.
www.3ds.com | © Dassault Systèmes

It is used to model radial


expansion, contraction,
bending, and pulsatile
motion of deformable
tube-like structures such
as stents.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.27
Abaqus Scripting Interface Basics (1/8)

Executing Scripting Interface commands


Abaqus/CAE
Commands are issued via: 1 2 3
command
GUI line script
interface
1. The GUI (CLI)

commands
2. The command line interface (CLI)
www.3ds.com | © Dassault Systèmes

3. Scripts. Python replay


interpreter files
Commands are interpreted and sent to the
kernel to create an internal representation of
your model. Abaqus/CAE
kernel

input file

Abaqus/Standard
Abaqus/Explicit

output database file

L1.28
Abaqus Scripting Interface Basics (2/8)

What is 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:


www.3ds.com | © Dassault Systèmes

Customize your Abaqus environment via the 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.

Perform parameter studies.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.29
Abaqus Scripting Interface Basics (3/8)

Aside: Terminology

The command line


interface (CLI) is
hidden by default, but
it uses the same
space occupied by
the message area.
www.3ds.com | © Dassault Systèmes

L1.30
Abaqus Scripting Interface Basics (4/8)

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.


www.3ds.com | © Dassault Systèmes

In the examples below, it is accessed directly by typing in the CLI.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.31
Abaqus Scripting Interface Basics (5/8)

When accessing the functionality of any


Abaqus/CAE module:
The script must be interpreted by the
Abaqus/CAE kernel.
You may run the script from within
Abaqus/CAE:

From the File menu


www.3ds.com | © Dassault Systèmes

Using the Python execfile() at the


command line interface.
From the start-up screen.
From the system command line.

abaqus cae startup = myscript.py


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

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

abaqus python myscript.py


abaqus script myscript.py

L1.32
Abaqus Scripting Interface Basics (6/8)

Two simple ways of building new scripts

You can use the Macro Manager to record a sequence of the generated Abaqus commands in a macro
file.
You may specify a
location for the macro
file when creating a
macro.
www.3ds.com | © Dassault Systèmes

The filename is abaqusMacros.py.


The file always gets appended.

You can also use the Abaqus replay file as the basis for a new script.

The file name for the current session is abaqus.rpy. If multiple sessions of Abaqus/CAE exist,
the file name extension may be numbered, e.g., abaqus.rpy.1.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.33
Abaqus Scripting Interface Basics (7/8)

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

Steps:

1) In Abaqus/CAE rotate the model by a specifying an increment in the


dialog box. The Python command for this will be automatically written to
the replay file:

session.currentViewportName.view.rotate(xAngle=10,
www.3ds.com | © Dassault Systèmes

yAngle=0,zAngle=0,mode=MODEL)

Cut and paste this command into a new text file.

2) Add a Python statement to loop over the command:

for x in range(36):
session.currentViewportName.view.rotate(xAngle=10,
yAngle=0,zAngle=0, mode=MODEL)

3) Save the script as rotate.py.

L1.34
Abaqus Scripting Interface Basics (8/8)

4) Run the script in Abaqus/CAE by selecting File→Run Script.


www.3ds.com | © Dassault Systèmes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L1.35
Workshop Preliminaries (1/2)

1. Objectives
a. When you complete this exercise you will be able to extract all the files necessary to complete the
demonstrations and workshops associated with this course

2. Workshop file setup (option 1: installation via plug-in)


a. From the main menu bar, select
Plug-ins→Tools →Install Courses.
b. In the Install Courses dialog box:
www.3ds.com | © Dassault Systèmes

i. Specify the directory to which the files will be written.


ii. Chooses the course(s) for which the files will be
extracted.
iii. Click OK.

5 minutes

L1.36
Workshop Preliminaries (2/2)

3. Workshop file setup (option 2: manual installation)


a. Find out where the Abaqus release is installed by typing
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.12–1 release might be aliased to abq6121.
This command will give the full path to the directory where Abaqus is installed, referred to here as
abaqus_dir.
www.3ds.com | © Dassault Systèmes

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

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

5 minutes
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes

5.
4.
3.
2.
1.

60 minutes
Create a CAE model.

Edit a replay file to modify a model.


Use the replay file to recreate a model.
When you complete this workshop, you will be able to:
Workshop 1: Creating a basic Abaqus script

Understand the commands written to the replay file when creating a CAE model.
L1.37
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.1
Lesson 2: Why Python?

The following topics are covered in this lesson.

Lesson content:
High Level Description of the Language
Why Python?
Growing Python Universe
Running Python
www.3ds.com | © Dassault Systèmes

Lexical Convention and Syntax


Workshop 2: Running Python

2 hours

L2.2
High Level Description of the Language (1/4)

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
www.3ds.com | © Dassault Systèmes

Mixable: Can be used with components written in other languages

Easy: Simple easy-to-read syntax

Powerful: Incorporates dynamic typing, high-level built-in objects and tools, library
utilities, 3rd-party extensions, automatic memory management, modules,
classes, exceptions

Object oriented: Class model supports encapsulation, polymorphism, and multiple


inheritance
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.3
High Level Description of the Language (2/4)

Brief History

Created by Guido van Rossum in Amsterdam, 1990

USENET newsgroup started, 1994

First books appeared, 1996

First O’Reilly Python Conference, 1999


www.3ds.com | © Dassault Systèmes

Estimated user base of 3+ million, 2011

Used in – Google, NSA, Intel, NASA, SIMULIA

L2.4
High Level Description of the Language (3/4)

Python is designed for working well with multi-language systems

Python is optimized for speed of development

Appropriate applications for Python

Component integration

Rapid application development


www.3ds.com | © Dassault Systèmes

System utilities

Graphical user interfaces

Usage within specific domains

Internet scripting

Database programming

COM

Numeric programming

Graphics
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.5
High Level Description of the Language (4/4)

Python references

Official Python web site: www.python.org

Online tutorial
www.python.org/doc/current/tut/tut.html

News groups
www.3ds.com | © Dassault Systèmes

comp.lang.python
comp.lang.python.announce

Many books are available.


www.rmi.net/~lutz/pybooks.html
http://books.google.com/books?q=python

L2.6
Why Python? (1/2)

A comparison of different computer languages

Scripting Programming
Language Language
www.3ds.com | © Dassault Systèmes

High Level Low Level


(# Instr/Stmnt) (# Instr/Stmnt)

/Python Weakly Typed Strongly Typed

Rapid Rapid Run-Time


Development

Easy to Reuse Difficult to Reuse


Code Code

* This information is taken from


Scripting: Higher Level Programming
* Typing is the degree to which the meaning of for the 21st Century
information is specified in advance of its use. by Ousterhout J.K.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.7
Why Python? (2/2)

Why use a scripting language?

A scripting language is high-level language that executes more operations per language statement that
a language such as C++.

Scripting languages like Python can significantly boost programmer productivity.

A scripting language does not require compilation, leading to fast prototyping.


www.3ds.com | © Dassault Systèmes

“For the past 15 years a fundamental change has been occurring in the way that people write computer
programs. The change is a transition from system programming languages such as C or C++ to scripting
languages such as Perl or Tcl. Although many people are participating in the change, few people realize that it
is occurring and even fewer people know why it is happening.”
- John Ousterhout (inventor of the Tcl language), 1998

L2.8
Growing Python Universe (1/9)

The popularity of Python has grown significantly over several years

It is found in application domains as diverse as finance, scientific computing, data visualization, web
development, system administration, etc.

It is an extremely popular choice for building APIs around applications.


www.3ds.com | © Dassault Systèmes

Several top ranked universities like MIT are now introducing Python as a first language to their students.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.9
Growing Python Universe (2/9)

There are several reasons to explain Python’s popularity:

Extensive suite of third-party libraries built around Python built in virtually every domain (we will see some of
them).

Python is a general purpose programming language.

It is possible to do scientific computing, internet scripting, building applications using GUI toolkits, file
www.3ds.com | © Dassault Systèmes

handling and parsing all within a single language

Right mix of focus on modern language constructs like OOPS (Object oriented programming) and a design
focused on minimizing programmer overhead.

Flexibility of mixing languages with Python.

Languages as diverse as C, Java, Fortran can be seamlessly mixed with Python.

A Programming Paradigm which is gaining in popularity involves Python code in a flexible outer core mixed
with languages designed for specialized tasks.

L2.10
Growing Python Universe (3/9)

Python and scientific computing

To get a sense of the growing Python universe we take a look at some of the libraries available for
scientific computing.

Python and scientific computing may seem an odd combination: Python is interpreted and scientific
computing requires efficiency so how can the twain meet ?
www.3ds.com | © Dassault Systèmes

Remember Python is a mixing language.

Often only the outer shell is Python and internally you make calls to highly optimized libraries like BLAS,
LAPACK, etc..

The flexible outer shell minimizes the development time and calls to native languages provide efficiency.

If efficiency is required for a certain segment of code, compiled languages such as Fortran and C can be
mixed with Python.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.11
Growing Python Universe (4/9)

Python and scientific computing (cont’d) >>> A = matrix('1.0 2.0; 3.0 4.0')
>>> A [[ 1. 2.] [ 3. 4.]]
NumPy is a powerful package for scientific
computing with Python. >>> A.T # transpose
[[ 1. 3.] [ 2. 4.]]

It contains among other things: >>> X = matrix('5.0 7.0')


>>> Y = X.T
A powerful N-dimensional array object >>> Y [[5.] [7.]]
www.3ds.com | © Dassault Systèmes

# matrix multiplication
Tools for integrating C/C++ and Fortran code >>> print A*Y
[[19.] [43.]]
Useful linear algebra, Fourier transform, and
random number capabilities. # inverse
>>> print A.I
Symbolic capabilities lead to compact code [[-2. 1. ] [ 1.5 -0.5]]

# solving linear equation matrix


Shipped with Abaqus distribution of Python >>> solve(A, Y)
([[-3.], [ 4.]])

L2.12
Growing Python Universe (5/9)

Python and scientific computing (cont’d)

SciPy

SciPy is open-source software for mathematics, science, and engineering.

Depends on NumPy.

Extensive library for a number of engineering and scientific routines.


www.3ds.com | © Dassault Systèmes

Integration (scipy.integrate)
Optimization (optimize)
Interpolation (scipy.interpolate)
Fourier Transforms (scipy.fftpack)
Signal Processing (signal)
Linear Algebra
Statistics
Multi-dimensional image processing (ndimage)
File IO (scipy.io)

SciPy is not shipped with Abaqus but can be installed as per SIMULIA Answers 3993 and 3782
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.13
Growing Python Universe (6/9)

Python and scientific computing


(cont’d)

Matplotlib

Matplotlib is a Python 2D
plotting library
www.3ds.com | © Dassault Systèmes

Can generate plots,


histograms, power spectra,
bar charts, errorcharts,
scatterplots, etc, with just a
few lines of code.

Numpy + Scipy + Matplotlib


have emerged as an
alternative to the matlab
environment.

L2.14
Growing Python Universe (7/9)

Python and scientific computing (cont’d)

Other libraries:

Sympy – Library for symbolic manipulation.

openOpt, cvxOpt – Optimization library with Python.


www.3ds.com | © Dassault Systèmes

Sage – Collection of Python utilities for mathematical applicationswith the aim of becoming a viable
open source alternative to Matlab, Maple, Mathematica.

Cython, pyfort, f2py, Jython – Instant inlining or arbitrary mixing of C , Fortran code, java code.

Matplotlib, Mayavi2 – 2D, 3D plotting utilities.

Qt Designer – Rapid GUI/ application builder..something like Visual Basic.

Python(x,y) – Integrated IDE of many of the above libraries.

Many more…
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.15
Growing Python Universe (8/9)

Libraries for other domains

Similar libraries exist for almost every domain!

Web Programming
CGI, Zope, Django, TurboGears, XML

Databases
www.3ds.com | © Dassault Systèmes

ODBC, MySQL

GUI Development
wxPython, tkInter, PyGtk, PyQt

Education
pyBiblio, Software Carpentry Course

Networking
Sockets, Twisted

Software Development
Buildbot, Trac, Roundup, IDEs

L2.16
Growing Python Universe (9/9)

Libraries for other domains (cont’d)

Parsing
re, pyparse, ANTLR, PLY,KWparsing

Rapid Application Builders like visual Basic l


Qt Designer, Pyside etc.
www.3ds.com | © Dassault Systèmes

Game Development
PyGame, PyKyra, 3D Rendering

The utility of learning Python for scripting in Abaqus extends far beyond Abaqus !
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.17
Running Python (1/8)

Python program structure

Programs are typically comprised of a collection of files.

These files are typically referred to as modules.

One module is selected by the user as the main program.

The other modules are used as libraries outside of the main.


www.3ds.com | © Dassault Systèmes

Modules are files that contain statements and organize accessibility to data.

Statements create and process objects.

L2.18
Running Python (2/8)

Python Interpreter

Source file Compiled Python Virtual Machine


Byte-code
www.3ds.com | © Dassault Systèmes

.pyc Interpreter

The .pyc file is not machine code, but something that is a bit higher level
The result is a language that is not as fast as C++, but comparable to Java or Perl.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.19
Running Python (3/8)

How to run Python

Interactive
$ abaqus python
>>> print 5**4
625
>>>
To exit: Ctrl-D (on UNIX), Ctrl-Z & Return (on Windows)
www.3ds.com | © Dassault Systèmes

To exit on both: import sys; sys.exit()

Command line
$ abaqus python -c "print 5**4"
625

Top-level Script
a = 5; b = 4
$ abaqus python mytest.py c = a ** b
625 print c

L2.20
Running Python (4/8)

How to run Python (cont’d)

Unix-style script file


#!/prog/python
a = 5; b = 4
$ mytest.py c = a ** b
625 print c

Embedded in another system


www.3ds.com | © Dassault Systèmes

I. E.g., Abaqus/CAE

Run in interactive
Run as top level mode
script
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.21
Running Python (5/8)

How to run Python (cont’d)

Windows-style script file


a = 5; b = 4
D:\ mytest c = a ** b
625 print c
www.3ds.com | © Dassault Systèmes

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

L2.22
Running Python (6/8)

Integrated Development Environment (IDE)

An IDE provides an alternative to using a shell command line and text editor for developing and/or
running code

Most IDEs provide text editing (syntax coloring, block folding, method tips), debugger, project manager,
class browser, keyboard shortcuts, toolbars, regular expression debugger, etc.
www.3ds.com | © Dassault Systèmes

The IDE built into Abaqus is known as Abaqus Python Development Environment (PDE)

Separate application

Accessible from within Abaqus/CAE or independently

Step through a Python script running in the Abaqus/CAE kernel or GUI

Debug Python script or plug-in

Documentation available in Abaqus Scripting User’s Manual

Discussed further in Lecture 5


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.23
Running Python (7/8)

A simple Python IDE called IDLE comes embedded with Python.

There are several commercial IDEs

Popular free IDEs are Eclipse and Spyder

Eclipse is a very powerful IDE and is highly recommended for developing large projects
www.3ds.com | © Dassault Systèmes

Spyder is a popular Scientific Python Development Environment:

a powerful interactive development environment for the Python language with advanced editing,
interactive testing, debugging and introspection features

and a numerical computing environment and popular Python libraries such as NumPy (linear
algebra),SciPy (signal and image processing) or matplotlib (interactive 2D/3D plotting).

L2.24
Running Python (8/8)

Different versions of Python

The version of Python that comes with Abaqus might not be the latest version that is available from
other sources.

Abaqus 6.12 uses Python version 2.6.2

Use the sys.version parameter to query the version of Python that is being used. For example:
www.3ds.com | © Dassault Systèmes

>>> import sys


>>> sys.version
'2.6.2 (#0, Apr 07 2010, 16:24:34) [MSC v.1500 32 bit (Intel)]'
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.25
Lexical Conventions and Syntax (1/8)

Example using common syntax rules:

Comments start with # and continue


to the end of the line

# simple example
max = 5; i = 0 Semicolon for two statements
www.3ds.com | © Dassault Systèmes

x, y, z = 1, 2, 3
blank lines ignored

while i <= max:


Indentation square = i**2 + x*y The syntax forces the user to
delimits write readable code and
cube = i**3 - z
blocks (such enables productivity
print i, square, cube
as loops) i = i + 1 # increment index
for j in ['ASN',1,2]: An empty block is denoted with the
The amount pass statement
of pass
indentation print 'The example is completed\
is arbitrary now print a long message'
Backslash for line
but must be
continuation
consistent
for a block

L2.26
Lexical Conventions and Syntax (2/8)

Identifiers

An identifier is a name that is used to identify objects such as variables, functions, classes, or modules.

Legal identifier names:

[underscore or letter] + [any number of


www.3ds.com | © Dassault Systèmes

letters, numbers, or underscores]

Names are case-sensitive.

Some names are always reserved (Python will raise a syntax error if one is used as an identifier):

and, as, assert, break, class, continue,


def, del, elif, else, except, exec,
finally, for, from, global, if, import,
in, is, lambda, not, or, pass, print,
raise, return, try, while
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.27
Lexical Conventions and Syntax (3/8)

Identifiers

Identifiers that start or end with underscore(s) usually have special meanings:

Example Description Meaning


www.3ds.com | © Dassault Systèmes

_name Starts with underscore Not imported when using the


from statement

__name Starts with two underscores Private class member

__name__ Starts and ends with two Reserved for special Python
underscores methods

L2.28
Lexical Conventions and Syntax (4/8)

Special symbols

The following characters cannot be used in a program except in a string literal: @ $ ?

The following special symbols are used in accordance with the rules already
discussed: ' " # \
www.3ds.com | © Dassault Systèmes

Delimiters

The following symbols serve as delimiters for expressions, lists, dictionaries, and parts of statements:
( ) [ ] { } , : . ` = ;
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.29
Lexical Conventions and Syntax (5/8)

String literals

Single quote characters or double quote characters are acceptable. For example:
>>> s = 'text'
>>> s = "text"

The same quote character (single or double) must be used at the start and end of the string
www.3ds.com | © Dassault Systèmes

Many standard character escape codes are available. The backslash character is used to escape
special characters. For example, the following will sound the system bell, insert a tab, and print the
word “test”.
'\a\ttest'

Use raw strings to turn off backslash escape sequence. For example:
open(r'c:\dir1\dir2\filename')

L2.30
Lexical Conventions and Syntax (6/8)

Number literals

Integer: 123, 0644, 0x100fea8

Long: 123L, 1L

Float: .123, .123e4, .123E4, .123E+4, .123E-4


www.3ds.com | © Dassault Systèmes

Complex: 1.2j, 1.2J

New numeric type

Allows for accurate representation of floating point numbers

Decimal: decimal.Decimal(2008)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L2.31
Lexical Conventions and Syntax (7/8)

Documentation string

If specified as a string, the first statement of a module, class, or function definition becomes a
documentation string for that object

Documentation strings are accessible in the __doc__ attribute of an object. They may also be used in
code-browsing and documentation-generation tools.
www.3ds.com | © Dassault Systèmes

Example:

def test():
'this is a test documentation string'
print 'test'

>>> print test.__doc__


this is a test documentation string

L2.32
Lexical Conventions and Syntax (8/8)

Triple quoted string

Triple quoted strings can contain embedded new lines.

>>> doc = """ This program is designed


... to be all things to all men """
>>> doc
' This program is designed\nto be all things to all men '
www.3ds.com | © Dassault Systèmes

Double or single quote character may be used.

Triple quotes can be used to create a comment block, or comment out a block of code. Note that, unlike
a normal comment, the string is compiled into the .pyc file, although it is inaccessible.
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes

60 minutes
b. run Python by using scripts
Workshop 2: Running Python

1. When you complete this workshop, you will be able to:


a. run Python interactively; from the command line and from Abaqus/CAE
L2.33
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.1
Lesson 3: Python Core Language Part 1

Lesson content:

Data Types
Operators and Expressions
Workshop 3: Python Types, Operators, and Expressions
Objects
Workshop 4: Investigating Python Objects
www.3ds.com | © Dassault Systèmes

3 hours

L3.2
Data Types (1/17)

List of types
Number: int, long, float, complex, bool

Sequence: string, list, tuple, array

Map: dictionary

Other: file, module, function, class


www.3ds.com | © Dassault Systèmes

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


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.3
Data Types (2/17)

Number types

Numbers
Integer (decimal, octal, hexadecimal)*
Example: 1234, 0644, 0x100fea8
Integers Float

Long **
Example:
www.3ds.com | © Dassault Systèmes

Integer Complex
>>> 17643L**11111
463783748290623436091218...
Long
Float
Examples: 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.

** It is recommended to use int() since it will return a short or long


int depending on the argument value

L3.4
Data Types (3/17)

Type coercion

If number types differ in an operation, a coercion operation is automatically performed to convert one of
the types to the other (usually the more complex type)

Operations between an integer and a float create a float.


>>> 5*2.0
10.0
www.3ds.com | © Dassault Systèmes

Operations between integers resulting in fractions do not create a float.


This is similar to most classical languages and a common source of beginner errors.
>>> 3/2
1
>>> 2/3
0

Note: In Python 3.0 (Abaqus uses Python 2.6-2) the default has been changed and the answer to
the above will be 0.66666
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.5
Data Types (4/17)

Collection types

Collection
www.3ds.com | © Dassault Systèmes

Sequence Mapping

Immutable Mutable Dictionary

String List

Tuple

L3.6
Data Types (5/17)

Sequence types

There are three built-in sequence types in Python and an array type implemented in a separate module.

Type Mutable Homogeneous Methods Syntax


list Yes No Yes [9.0,'b']
www.3ds.com | © Dassault Systèmes

tuple No No No ('a',45,)
string No Yes Yes 'wxyz'
array Yes Yes Yes array((2.3,5.6))

Mutable: Elements may be added, changed, and removed.

Homogeneous: Elements must be of the same type.

Methods: The type has methods that can be used to manipulate the contents of the
array (e.g., sort(), reverse()).

Syntax: Syntax used to construct the object.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.7
Data Types (6/17)

Sequence types: string

String types have a number of different methods

>>> dir ('')


['capitalize', 'center', 'count', 'decode', 'encode',
www.3ds.com | © Dassault Systèmes

'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',


'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join',
'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']

* private and "magic" methods have not been included in this list, and will also be omitted from the dir() shown
in subsequent slides.

L3.8
Data Types (7/17)

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
www.3ds.com | © Dassault Systèmes

[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']
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.9
Data Types (8/17)

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'
www.3ds.com | © Dassault Systèmes

Traceback (innermost last):


File "<stdin>", line 1, in ?
TypeError: can't assign to this subscripted object

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.

L3.10
Data Types (9/17)

Sequence types: tuple (cont’d)

Tuple data types do not have built-in methods:

>>> dir(myTuple)
[ ]

Small syntactical point: one-element sized tuples require a comma after the element. For example:
www.3ds.com | © Dassault Systèmes

>>> myTuple = (x+y,)


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.11
Data Types (10/17)

Sequence types: array

An array is a mutable homogeneous sequence.

Module 'array' defines a multi-dimensional homogeneous array.

The first argument (optional) defines the type; otherwise, the type is based on the contents of the array.
>>> from array import array
www.3ds.com | © Dassault Systèmes

>>> a = array("d",(4.0,5.0,3.0))
>>> a
array('d',[4.0, 5.0, 3.0])

Array methods:
>>> dir(array)
['append', 'buffer_info', 'byteswap', 'count', 'extend', 'fromfile',
'fromlist', 'fromstring', 'fromunicode', 'index', 'insert', 'itemsize',
'pop', 'read', 'remove', 'reverse', 'tofile', 'tolist', 'tostring',
'tounicode', 'typecode', 'write‘]

L3.12
Data Types (11/17)

Mapping type: 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:


www.3ds.com | © Dassault Systèmes

>>> myDict = {} # create an empty dictionary


>>> myDict['eric'] = 'Eric Idle'
>>> myDict['PI'] = 3.14159265359
>>> myDict[2001] = 'Beginning of the century'
>>> type(myDict)
<type 'dictionary'>
>>> myDict
{'eric': 'Eric Idle', 2001: 'Beginning of the century',
'PI': 3.14159265359}
>>> myDict['PI']
3.14159265359
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.13
Data Types (12/17)

Mapping type: dictionary (cont’d)

Dictionary data types have a number of different methods:

'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems',


'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update',
'values'
www.3ds.com | © Dassault Systèmes

Here are a few methods at work:


>>> myDict.keys()
['eric', 2001, 'PI']
>>> myDict.has_key('Turnip')
False
>>> myDict.values()
['Eric Idle', 'Beginning of the century', 3.14159265359]
>>> myDict.items()
[('eric', 'Eric Idle'), (2001, 'Beginning of the century'),
('PI', 3.14159265359)]

L3.14
Data Types (13/17)

Mapping type: dictionary (cont’d)

Properties of dictionaries

Change in-place: like lists, size can change without making a copy

Flexible: can contain objects of any type


www.3ds.com | © Dassault Systèmes

Not a sequence type: sequence methods do not work

Fast retrieval: Python employs optimized hashing algorithms to find the keys.

Values stored in dictionaries are not implicitly ordered relative to one another.

The order of keys in a dictionary is not predictable


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.15
Data Types (14/17)

Callable, internal, and other types

Callable Internal Other Type


www.3ds.com | © Dassault Systèmes

Function Type Module

Class Code Instance

Method Frame File

Bound Unbound Traceback None

L3.16
Data Types (15/17)

Built-in data types

Python has dozens* of built-in data types for providing a variety of features

If it is true that any computer program could be written using only a few basic language features and
data types, then …
www.3ds.com | © Dassault Systèmes

Why use built-in Python data types?

Efficient: Optimized for performance

Easy to use: standard from site to site

Powerful: Extensions may be built on top of built-in types

* Abaqus extends Python with many additional types.


* For most programs, you will need less than a dozen object types:
int, float, string, tuple, list, dictionary, function, class, file, module
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.17
Data Types (16/17)

Python data types can be queried

>>> import types


>>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType',
'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType',
'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType',
www.3ds.com | © Dassault Systèmes

'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType',


'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType',
'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType',
'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType',
'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType',
'XRangeType', '__builtins__', '__doc__', '__file__', '__name__']

L3.18
Data Types (17/17)

Working with data types

To query the type of an object, use this built-in function: type(object).

The standard module called types contains the type objects for all of the built-in Python types.

The behavior of an operation depends on the type of object. Taking advantage of Python's run-time
binding can help you develop code that is very general.
www.3ds.com | © Dassault Systèmes

Examples:

L=[1,2,3]
import types
if type(L) == types.ListType:
<do some method>
If type(displayedObject)== OdbType:
do something
>>> type(1L)
If type(displayedObject)== PartType:
<type 'long'>
do something
>>> type((1,2,3))
<type 'tuple'>
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.19
Operators and Expressions (1/7)

Examples of some Python operators

Mathematical: +, -, *, **, /, %
>>> (5 + 3)/2
4

Logical: and, or, not


>>> 3 or 0
www.3ds.com | © Dassault Systèmes

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


>>> 5 != 6
True

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


>>> 1 << 2
4

L3.20
Operators and Expressions (2/7)

Number operations

Operation Description Function Description

x + y Addition abs(x) Absolute value


www.3ds.com | © Dassault Systèmes

x – y Subtraction divmod(x,y) Returns the following:


(int(x/y), x%y)
x * y Multiplication
round(x [,n]) Round to the nearest 10-n
x / y Division
pow(x,y Returns the following:
x ** y x raised to power y [,modulo]) (x**y) % modulo
x % y x modulo y

-x Unary minus

+y Unary plus
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.21
Operators and Expressions (3/7)

Sequence operations

Operation Description
s1 + s2 Concatenation

s * n Make n copies of s (n is integer) All of these operations are not


applicable to all sequence types
www.3ds.com | © Dassault Systèmes

s % d String formatting

s[i] Indexing

s[i:j] Slicing
x in s Membership testing
x not in s

for x in s: Iteration

len(s) Length

min(s) Minimum item from all items

max(s) Maximum item from all items

zip(s1, s2) Combines two lists (see docs)

L3.22
Operators and Expressions (4/7)

Sequence operation examples

Indexing

All sequence types can be indexed.

Indices are zero-based.


>>> a = ['a','b','c',('A','B','C')]
www.3ds.com | © Dassault Systèmes

>>> 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'
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.23
Operators and Expressions (5/7)

Sequence operation examples (cont’d)

Slicing

All sequence types can be sliced.

s[m:n]
www.3ds.com | © Dassault Systèmes

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:4] + welcome[5:-1]
'Hell Worl'

L3.24
Operators and Expressions (6/7)

Sequence operation examples (cont’d)

Repeat

>>> a = [0,1] * 3
>>> a
[0, 1, 0, 1, 0, 1]
www.3ds.com | © Dassault Systèmes

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'
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.25
Operators and Expressions (7/7)

Dictionary operations

Operation Description
www.3ds.com | © Dassault Systèmes

x = d[k] Accessing by key

d[k] = x Key assignment

del d[k] Delete an item by key

len(d) Return number of items in dictionary

a in d Membership test
d.has_key(a)

d.get(a) Access by key, with default value.

d.setdefault(a) Access by key, with default value placed into


the dictionary.

L3.26
Workshop 3: Python Types, Operators, and Expressions

1. When you complete this workshop, you should be comfortable using:


a. Basic Python types
b. Operators
c. Expressions
www.3ds.com | © Dassault Systèmes

60 minutes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.27
Objects (1/15)

Objects

All the data stored in a Python program is built around the concept of an object. Internally everything in
Python is an Object.

Each object has an identity, type, and value (discussed next).

An object can contain references to other objects or data (referred to as container).


www.3ds.com | © Dassault Systèmes

Example: A Part object contains faces, cells and edge objects .

We discuss objects in greater detail later.

L3.28
Objects (2/15)

Object Identifiers

Identifiers are user-defined names that provide references (pointers) to an object and the type of object
to which it is bound. You can think of Identifier as a variable name.

An assignment is a statement that binds an identifier to an object:

>>> x = 4 # variable name x refers to the integer 4


www.3ds.com | © Dassault Systèmes

>>> y = [6,5,7]

Here identifier x refers or points to object 4.

Here identifier y refers to array object [6,5,7].

The identity of x and y will contain the address of the objects in memory (More on identity later).

>>> id(x)
18975092
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.29
Objects (3/15)

Assignments

Type declarations are not required for assignment.

Assignments can be made to objects of any size.

Any number of identifiers can be bound to the same object:


www.3ds.com | © Dassault Systèmes

>>> a = b = 'test'
>>> print a, b
'test' 'test'

In Python you may not refer to an identifier that has not been assigned. You will get a name error. For
example:

>>> print x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined

L3.30
Objects (4/15)

Object Identity (this is different in Abaqus Python; more on this later)

The identity of an object is a Python-defined integer pointer to a location in memory

The built-in function id() returns the object identity

The is operator is used to compare the identity of two objects


www.3ds.com | © Dassault Systèmes

Object Type

The type of an object describes the internal representation of the object as well as the methods and
operations that it supports

The type of an object is itself an object, is uniquely defined, and is identical for all instances of an object

The standard module called types contains all of the built-in type objects

Object Value

If an object's value can be modified, the object is said to be mutable. If not, the object is said to be
immutable
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.31
Objects (5/15)

Identity, Equality, Truth

Identity testing operators:

Test to determine if two objects refer to the same memory location

x is y
x is not y
www.3ds.com | © Dassault Systèmes

Equality testing operator:

Test to determine if two objects are equal

x == y
x != y

For container types, all items are tested

Examples of objects that have a false Truth value:

'',"", '''''', """""", [], (), {}, 0, 0.0, None


>>> x = 0
>>> if x:
print 'True'

L3.32
Objects (6/15)

Example, Identity and Type

# code to compare two objects


import types
def compare(x, y):
print 'id for x and y =', (id(x), id(y))
www.3ds.com | © Dassault Systèmes

if x is y: print 'x and y are the same object'


if x == y: print 'x and y have the same value'
if type(x) is type(y): # in this case, same as using ==
print 'x and y have the same type'
if type(x) is types.IntType:
print 'x is an integer'
else:
print 'x is not an integer'
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.33
Objects (7/15)

Example, Identity and Type (cont’d)

>>> compare(1,2)
id for x and y = (11288312, 11288300)
x and y have the same type
x is an integer
www.3ds.com | © Dassault Systèmes

>>>
>>> x=[1,2,3]
>>> y=x
>>> compare.compare(x,y)
id for x and y = (2146243648, 2146243648)
x and y are the same object
x and y have the same value
x and y have the same type
x is not an integer

L3.34
Objects (8/15)

Object identity in Abaqus Python

The is operator cannot be used to compare the identity of two objects in Abaqus/CAE. This is because
each time an object is accessed, a new wrapper object is created. Each of these Python objects has a
different ID.

For example, in the CLI:


www.3ds.com | © Dassault Systèmes

>>> m = mdb.models['Model-1']
>>> id(m) > 149395192
>>> m1 = mdb.models['Model-1']
>>> id(m1) > 149339120
>>> m2 = mdb.models['Model-1']
>>> id(m2) > 149395272
>>> m1 is m2
0
>>> m1 == m2
1

DON'T use is in Abaqus/CAE.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.35
Objects (9/15)

Attributes and the attribute operator

In addition to holding a value, type and identity, some objects define data attributes or other objects.

The properties or variables or identifiers bound to an object are called members

The functions bound to an object are called methods


www.3ds.com | © Dassault Systèmes

The attribute or dot (.) operator is used to access attributes of an object as shown in the following
example:

>>> f = open('tmp.txt')
>>> f.close() method
>>> f.closed member
True

We will discuss this in greater detail when we discuss object oriented programming.

L3.36
Objects (10/15)

Attributes and the attribute operator (cont’d)

The members and methods of an object can be queried:

>>> mdb.__members__
['acis', 'adaptivityProcesses', 'annotations', …]
>>> mdb.__methods__
www.3ds.com | © Dassault Systèmes

['AdaptivityProcess', 'Annotation', 'Arrow', …]

The attributes called __members__ and __methods__ were


discontinued in Python v2.2 but are maintained in Abaqus Python.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.37
Objects (11/15)

Object references

Objects are assigned by reference. So if b = a, then b becomes a reference to the object that a refers
to, not to a itself.

Example of objects that change in-place


www.3ds.com | © Dassault Systèmes

>>> a = [1, 2, 3]; b = a


>>> a[2] = 4
>>> b The name b points to the
[1, 2, 4] modified list

Example of objects that do not change in-place.

>>> a = [1, 2, 3]; b = a


>>> a = [1, 2, 4]
>>> b The name b points to the original list object
[1, 2, 3]. a was reassigned to a different
[1, 2, 3]
object while b points to the original object.

L3.38
Objects (12/15)

Object references (cont’d)

Consider the following again:


Notes
>> a = [100,200,300]
>> b = a Object References
>> a[0] = 5
>> print b Only the address is shared between a and b.
www.3ds.com | © Dassault Systèmes

5, 200,300 The whole array is not copied !!


>> print a
5, 200, 300 Python does not have name aliasing.
>> a = [80,100,90]
>> print b With name aliasing, In the above example 'b'
would also change when a changes.
5, 200, 300
>> print b
80,100,90

What Python has is shared references like C


pointers.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.39
Objects (13/15)

References versus copies

Objects are never copied in Python unless requested.

Usually, the “shared references” that are inherent in Python provide exactly the behavior that you want.
If not, you can avoid sharing objects by explicitly creating copies.

Empty limit slice copy


www.3ds.com | © Dassault Systèmes

An empty limit slice operation makes a one-level deep (shallow) copy of the sequence. Shallow copy
example:

>>> a = b = [1,2,3]
This is an empty limit slice
>>> c = a[:]
operation that makes a top-level
>>> b.append(4)
copy of the object a.
>>> a
[1, 2, 3, 4]
>>> c
[1, 2, 3]

L3.40
Objects (14/15)

Repetition copy

An repetition operation also makes a one-level deep (shallow) copy of the sequence. Shallow copy
example:

>>> L0 = [1, 2, 3]
2
>>> L1 = L0 * 2
www.3ds.com | © Dassault Systèmes

>>> L2 = [L0] * 2
>>> L0[1] = 0
L1
>>> L1
???
>>> L2
???
1 0
>>> L2[0][1] = 2
>>> L2 3
???
L0

Same as
[L0] + [L0] L2
Same as
[1, 2, 3] + [1, 2, 3]
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L3.41
Objects (15/15)

Other explicit copy methods

A standard copy module is available for making shallow copies. It also allows the user to make deep
copies of objects.

Shallow copy: creates a new object but populates it with references to the items contained in the
original.
www.3ds.com | © Dassault Systèmes

Deep copy: creates a new object and recursively copies all of the objects that it contains.

>>> import copy


>>> a = [[1],[2],[3]]
>>> b = copy.deepcopy(a)
>>> c = copy.copy(a)
>>> a[0][0] = 0
>>> a, b
([[0], [2], [3]], [[1], [2], [3]])
>>> c
[[0], [2], [3]]

L3.42
Workshop 4: Investigating Python Objects

1. When you complete this workshop you will have a basic understanding of Python objects
www.3ds.com | © Dassault Systèmes

60 minutes
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

Modules
Functions

Exceptions

Conditionals
3 hours
Control Flow

Namespaces
Lesson content:

else:
Control Flow (1/8)
Workshop 6: Modules

statements
statements
statements
statements
if expression:

elif expression:
elif expression:
Common Issues for New Users

General format of if, elif, and else statements


Workshop 5: Defining a Function for a Series Calculation
Lesson 4: Python Core Language Part 2

L4.2
L4.1
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.3
Control Flow (2/8)

Looping

while – executes statements until expression is false.

while expression:
statements

for – iterates through a sequence.


www.3ds.com | © Dassault Systèmes

for i in sequence:
statements

If elements of the sequence are sequences of uniform size (in this case the size of each must be
three elements each), the following variations of the for loop may be used:

for i, j, k in sequence:
statements
for [i, j, k] in sequence:
statements

L4.4
Control Flow (3/8)

Flavors of for loop in Python

>>> arr = [10,20,30,40]


>>> for a in arr:
... print a
...
10
20
30
www.3ds.com | © Dassault Systèmes

40

Alternatively you can use the range functions:

>>> for i in range(len(arr)):


... print arr[i]
...
10
20
30
40
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.5
Control Flow (4/8)

for loops in Python

Range function returns an array on the fly from 0 to n-1 the specified integer.

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> for i in range(10):


... print i
www.3ds.com | © Dassault Systèmes

...
0
1
2
3
4
5
6
7
8
9

Use range when you want to loop n times

L4.6
Control Flow (5/8)

for loops in Python (cont‟d)

Enumerate function can be used to maintain an index variable.

>>> arr = [10,20,30,40]


>>> for index,i in enumerate(arr):
... print index, i
...
0 10
www.3ds.com | © Dassault Systèmes

1 20
2 30
3 40
>>>
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.7
Control Flow (6/8)

Looping (cont‟d)

break – break out of the loop.

i, max = 0, 50
while 1:
if i > max:
break
www.3ds.com | © Dassault Systèmes

else:
print i
i = i + 1

continue – skip the rest of the code in the loop and go to next iteration.

goto – Python does not provide a goto statement

break and continue statements apply to the inner most loop that is being executed. In order to break
out of a deeply nested loop, use an exception (discussed later).

L4.8
Control Flow (7/8)

Looping (cont‟d)

The else statement may be used to execute code only if the loop runs to completion (i.e. not
terminated early). Examples:

for i in [1, 2, 3]:


if i < 0:
break
else:
www.3ds.com | © Dassault Systèmes

print 'list is all positive (no break occurred)'

i=0
while i < 4:
i=i+1
else:
print 'Done'
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.9
Control Flow (8/8)

Example: Print a graph in the terminal window

for x in range(-21, +19):


if x == 0:
continue # skip the case of x = 0
# evaluate an expression
www.3ds.com | © Dassault Systèmes

y = 30 + 30/x
# print (x,y) followed by y spaces and a marker
print '(%03d,%03d):' % (x,y), ' '*y, 'o'

L4.10
Functions (1/8)

Basics

Most programs are organized into functions for modularity

Functions are defined with the def statement.


>>> def test(x, y):
... return x + y
www.3ds.com | © Dassault Systèmes

Functions are invoked with name followed by a tuple of arguments.


>>> test(1,1)
2

Normally, the order and number of arguments must match the definition
>>> test(1,1,1)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: test() takes exactly 2 arguments (3 given)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.11
Functions (2/8)

Flow of execution

Execution always begins at the first statement. Statements are executed one at a time, in order from
top to bottom

Statements inside a function are not executed until the function is called

Functions may be used to call other functions


www.3ds.com | © Dassault Systèmes

Parameters and arguments

Functions are defined with variables that are called parameters

Functions are called by passing values that are called arguments

L4.12
Functions (3/8)

Parameters and arguments (cont‟d)

Parameters and other function variables are local to the function.

For example:

def test(a):
b = a
www.3ds.com | © Dassault Systèmes

>>> test(1)
>>> b
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'b' is not defined
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.13
Functions (4/8)

Recursion

A function may be used to call itself.

This can cause infinite recursion. For example:

>>> def count(n):


www.3ds.com | © Dassault Systèmes

... count(n+1)
>>> count(1)
RuntimeError: maximum recursion depth exceeded

Python has a limit on the depth of recursive function calls. The default value is 1000.

sys.getrecursionlimit() returns the current max recursion depth


sys.setrecursionlimit() is used to set the max recursion depth

L4.14
Functions (5/8)

Recursion (cont‟d)

Example: factorial function

The definition is often written as:

0! = 1
n! = n * (n-1)!
www.3ds.com | © Dassault Systèmes

This may be replicated with a recursive function

def factorial(n):
if n == 0:
return 1
else:
n = long(n)
return n * factorial(n-1)
>>> factorial(69)
17112245242814131137246833888127283909227054489352036939364804092325
7279754140647424000000000000000L
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.15
Functions (6/8)

Defining a function with default argument values

Arguments may be assigned default values

>>> def test(x, y=1):


... return x+y

If a function has default arguments, you can omit arguments when calling the function.
www.3ds.com | © Dassault Systèmes

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

L4.16
Functions (7/8)

Calling functions using keyword arguments

You can specify arguments in any order by using keywords.

>>> def test(arg1, arg2):


... print 'arg1 = ',arg1
... print 'arg2 = ',arg2
www.3ds.com | © Dassault Systèmes

>>> test(arg2='bicycle', arg1='blue')


arg1= blue
arg2= bicycle

When calling a function with keyword arguments, the order of the parameters does not matter.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.17
Functions (8/8)

Fruitful functions

Functions may be used to return values. Values are returned using the return statement.

More than one return statement may be used. The function terminates at the first occurrence.

>>> def absoluteValue(x):


... if x < 0:
www.3ds.com | © Dassault Systèmes

... return -x
... if x > 0:
... return x

If a function does not execute a return statement, the None object is returned.

>>> print absoluteValue(0)


None

L4.18
Workshop 5: Defining a Function for a Series Calculation

1. When you complete this workshop, you will be able to:


a. Use a loop with test operators
b. Create a Python function
c. Work with large integers
www.3ds.com | © Dassault Systèmes

60 minutes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.19
Modules (1/6)

A module is a file containing code of related functions, classes, and variables that may be reused.

Modules are a way of organizing code and grouping functionality.

Modules can be used to help avoid name clashing.

Modules can be run from the command line


www.3ds.com | © Dassault Systèmes

abaqus python –m <Module name>

A module can be a text file with a .py suffix or a shared library.

The name of a module is derived from the name of the file.

L4.20
Modules (2/6)

Most of the functionality that is available to a Python user is implemented as a series of modules (e.g., the
Abaqus Scripting Interface)

Many Python modules are available for use with Abaqus.

Standard modules come with the Python distribution (e.g., httplib)

Other modules are also available (e.g., Numpy)


www.3ds.com | © Dassault Systèmes

A set of modules can be implemented as package. More on this later.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.21
Modules (3/6)

Using the import statement

To load some code as a module, use the import statement.

To import multiple modules, separate names with commas.

A new namespace is created for the module objects. For example:


www.3ds.com | © Dassault Systèmes

>>> import math, os


>>> x = math.sin(7)

Module code is executed during import. However, the code is executed only once, regardless of how
many times the import statement is used.

L4.22
Modules (4/6)

Using the from import statement

Names from the module can be copied into the importer‟s namespace.

>>> from math import sin


>>> x = sin(7)
www.3ds.com | © Dassault Systèmes

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 at the module level only, not inside of functions
and methods. Example:

>>> from math import *


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.23
Modules (5/6)

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.
www.3ds.com | © Dassault Systèmes

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

L4.24
Modules (6/6)

Three ways of changing the Python module search path:

Modify sys.path directly

Not generally recommended because hard coding the path may restrict behavior or require
constant maintenance.

The following lines will modify the search path directly:


www.3ds.com | © Dassault Systèmes

import sys, os The constant string used by


if os.curdir not in sys.path: the OS to refer to the current
sys.path.append(os.curdir) directory, e.g. '.'

Assign the environment variable value PYTHONPATH

Should not be overused because it may not apply to all users.

Add default search path using the path configuration file (packagename.pth)

Put this file in the site-packages directory

Helps to organize scripts for easy access and maintenance.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.25
Namespaces (1/6)

Python uses lexical scoping.

Lexical scoping is a convention used in a block-structured programming language: a variable can only
be referenced within the block in which it is defined and in blocks contained within that block.

The scope of a variable is completely determined at compile time.


www.3ds.com | © Dassault Systèmes

Built-in
Built-in
Global
Enclosing-defs
Local

L4.26
Namespaces (2/6)

Namespace

A name space can be thought of as a space where the variables or identifiers are stored.

When simple variables are assigned, Python changes or creates the name in the closest namespace.

The existence of different namespaces provides a means of avoiding name clashing.


www.3ds.com | © Dassault Systèmes

In Python speak a namespace is a program execution environment which corresponds to an object.

By default the variables are created in __main__ interpreter namespace.

>>> __name__
'__main__'
>>> x=4 ##identifier x is stored in the __main__ namespace
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.27
Namespaces (3/6)

Scope

Sometimes this term is used synonymously with namespace.

Used to refer to how the namespaces relate to each other and how the user can access each
namespace.

>>>newVariable = x.y.z
www.3ds.com | © Dassault Systèmes

In the example above z is in the scope of y and y is the scope of x. z and y are said to be qualified and
x is unqualified.

Let‟s consider another example:

>>> import math


>>> math.sin(78)
Here sin exists in the math namespace.

In the above the two cases both x and math are unqualified names. When the Python interpreter
encounters an unqualified name, it performs a search as discussed next.

L4.28
Namespaces (4/6)

Lexical scoping rules and namespaces

The Python interpreter will search namespaces to resolve unqualified names.

Local – functions define a temporary local namespace (may use globals)

Intermediate - read variables from nesting functions (if any)

Global – modules define a persistent global namespace


www.3ds.com | © Dassault Systèmes

Built-in – reserved names used by Python

Built-in (Python)

 Predefined names

Global (Module)
Nested (Functions) 1
 Names declared global
in a function
Nested (Functions)
 Names assigned at top
level of module Local (Functions)

 Names declared inside a


function statement (def)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.29
Namespaces (5/6)

Example

>>> len = 5
>>> def test():
>>> len = 6
>>> print len

Does this print 5, 6, or <built-in function len>?


www.3ds.com | © Dassault Systèmes

Note the global namespace in the preceding slide are the variables defined at the top level of the file, which
can be accessed using the dot notation.
# module test_mod.py
>>>import test_mod
x = 1
>>>test_mod.x
y = [2,2]
1

The only truly global variables in Python are the built-ins.

L4.30
Namespaces (6/6)

Summary

Python variables always exist in a namespace.

Namespace rules resolve ambiguities when there are multiple occurrences of a name.

Each object has its own namespace (strings, dictionaries, lists, etc.).
www.3ds.com | © Dassault Systèmes

Namespace paths are „qualified‟ using explicit dot notation. Example:

>>> myList = [1, 2, 3]


>>> myList.reverse()

Here the name myList is unqualified, and the name reverse is qualified.

The interactive interpreter executes in the namespace of a special module named __main__.

The namespace called “global” is a misnomer (better to call it “module”?)


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.31
Exceptions (1/2)

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.
www.3ds.com | © Dassault Systèmes

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.

L4.32
Exceptions (2/2)

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
www.3ds.com | © Dassault Systèmes

def inverse(x):
try:
print 1/x
except ZeroDivisionError:
print x, 'has no inverse'
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.33
Common Issues for New Users (1/3)

Coding style

Using a few rules and applying them consistently for coding will make your code easier for others to
read and maintain.

It is based on the style favored by Python


www.3ds.com | © Dassault Systèmes

http://www.python.org/dev/peps/pep-0008

http://www.python.org/dev/peps/pep-0257

The original style guide was written by Guido van Rossum, inventor of Python. It is available at the
following site:

http://www.python.org/doc/essays/styleguide.html

L4.34
Common Issues for New Users (2/3)

Indentation

Mixing tabs with spaces for indentation can cause unpredictable behavior. We recommend using spaces
exclusively, 4 spaces preferred.

Non-fruitful functions

Do not always expect a function to return a result. Some functions return the None object; for
www.3ds.com | © Dassault Systèmes

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 'None'>
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L4.35
Common Issues for New Users (3/3)

Overriding built-in functions

It is easy for beginners to override


built-in functions inadvertently. For
example:
www.3ds.com | © Dassault Systèmes

It is easy to recover from built-in


overrides by the using the del
statement. For example:

L4.36
Workshop 6: Modules

1. When you complete this workshop, you will be able to:


a. import a module using different techniques
b. observe some the inherent behavior different module import techniques
www.3ds.com | © Dassault Systèmes

60 minutes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L5.1
Lesson 5: More on Abaqus Scripting Basics

Lesson content:

Abaqus PDE
Abaqus Namespaces and Conventions
Resources
Getting Input Interactively
Workshop 7: Creating a Macro and Getting Input interactively
www.3ds.com | © Dassault Systèmes

1.5 hours

L5.2
Abaqus PDE (1/6)

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.


www.3ds.com | © Dassault Systèmes

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.


For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

Standalone
Starting Abaqus PDE

Abaqus PDE interface


Abaqus PDE (3/6)
Abaqus PDE (2/6)

Abaqus/CAE and PDE

From within Abaqus/CAE

L5.4
L5.3
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes


Abaqus PDE (4/6)

Abaqus PDE (5/6)


The GUI Command Line Interface (CLI)

GUI CLI

The Kernel Command Line Interface (CLI)


Any GUI API can be called, for testing a dialog for example.
Can be used to find Python variable values in the GUI process.

„p‟
Kernel process

script
in GUI

Breakpoint

Syntax coloring
Step through kernel

Watch list on variable


Select process to run

L5.6
L5.5
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L5.7
Abaqus PDE (6/6)

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
www.3ds.com | © Dassault Systèmes

Run in “Local” process

GUI CLI not available when


outside Abaqus/CAE

L5.8
Abaqus Namespaces and Conventions (1/3)

Abaqus Namespaces

Journaling namespace

A private namespace in which commands issued from the GUI are executed.

CLI namespace
www.3ds.com | © Dassault Systèmes

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.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L5.9
Abaqus Namespaces and Conventions (2/3)

Executing Macro Scripts

For the special case of executing a Python script that was created by the Macro Manager:

The general script limitation applies: if the script accesses the functionality of any Abaqus/CAE
module, the commands must be interpreted by the Abaqus/CAE kernel.

The scripts that are created by Abaqus Macro Manager are a collection of Python functions. To
www.3ds.com | © Dassault Systèmes

execute the script, either of the following techniques may be used:

1. Use the Macro Manager

2. Use File→Run Script and access each function at the command line interface (CLI). You
must know the function names (look at the file).

L5.10
Abaqus Namespaces and Conventions (3/3)

Abaqus Scripting Interface style

Abaqus provides a style guide to help maintain script consistency.

A consistent style:

Generally makes scripts easier to debug and maintain

Can establish conventions that parallel the object model


www.3ds.com | © Dassault Systèmes

The style guide is available from SIMULIA Answer 4430

Examples of Abaqus Scripting Interface convention:

Maximum line length is 79 characters.

Constructors begin with an uppercase character.

Methods begin with a lowercase character.

Use Keywords in function calls.

Use underscores only for private names.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L5.11
Resources (1/3)

Abaqus scripting references

Abaqus Scripting User‟s Manual

Included with each Abaqus release

Provides a description of methods.


www.3ds.com | © Dassault Systèmes

I. Describes how to access existing


objects via an Access section and
how to create new objects via a
Path section.

Contains an introduction to scripting and


numerous examples.

* These two manuals are


available in electronic format only.

L5.12
Resources (2/3)

SIMULIA Answer 3435 contains a list of SIMULIA supplied plug-ins.


www.3ds.com | © Dassault Systèmes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L5.13
Resources (3/3)

In addition, you can visit the SIMULIA Learning Community (www.3ds.com/simulia-learning) and
browse for more plug-ins.
www.3ds.com | © Dassault Systèmes

L5.14
Getting Input Interactively (1/2)

Overview

The getInput function displays a simple dialog box, along with a specified prompt, in which the user
enters the requested value or values.

The value is returned to the executing script as a string after the user presses the [Enter] key.

Optionally, you can specify a default value to be displayed in the data entry dialog box.
www.3ds.com | © Dassault Systèmes

The getInput function does not provide any error checking; it is the script author's responsibility to
verify the user input.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L5.15
Getting Input Interactively (2/2)

Example
The getInput function allows the user to enter a value:
from abaqus import *
from math import sqrt
input = getInput('Enter a number:', '9')
number = float(input)
print sqrt(number)

The float function converts the string returned by getInput into a floating point number.
www.3ds.com | © Dassault Systèmes

The getInputs function will get several values.

x = getInputs((('Enter first', '1'),


('Enter second', '2'),
('Enter third', '3')))
print x

A list is returned:

L5.16
Workshop 7: Creating a Macro and Getting Input Interactively

1. When you complete this workshop you will be able to create and use an Abaqus macro and request input
interactively using getInputs
www.3ds.com | © Dassault Systèmes

60 minutes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.1
Lesson 6: Abaqus Object Model

Lesson content:

Introduction to Object Oriented Programming


Abaqus Object Model Basics
The Session Object
The Mdb Object
Exploring Your Data
www.3ds.com | © Dassault Systèmes

Abaqus Data Types


Abaqus Modules
Workshop 8: Working with the Session Object

2 ½ hours

L6.2
Introduction to Object Oriented Programming (1/9)

Structured programming

Back in the "old days" structured programming was common:

Also known as modular programming.


A goal is accomplished by dividing tasks into several sub tasks.
The main function calls several functions which can call sub functions.
www.3ds.com | © Dassault Systèmes

Main

subFunc1 subFunc2 subFunc3

subFunc2-1 subFunc2-2 subFunc2-3


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.3
Introduction to Object Oriented Programming (2/9)

Structured programming (cont’d)

Data was separate from code.

Programmer is responsible for organizing everything into logical units of code/data.

No help from the compiler/language for enforcing modularity.


www.3ds.com | © Dassault Systèmes

For beginners structured programming or functional decomposition is more intuitive; however ,


scalability and reuse is more difficult with structured programming.

It was hard to build large systems (not impossible, just hard)


so there was a need for a different programming paradigm.

L6.4
Introduction to Object Oriented Programming (3/9)

Object Oriented Programming (OOP) to the rescue

Keep data near the relevant code

Provide a nice packaging mechanism for related code

Model the world as objects which have data or state and behavior or methods
www.3ds.com | © Dassault Systèmes

Objects can send "messages" to each other

Object 2
Object 1
Object 3

Object4 Object 5
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.5
Introduction to Object Oriented Programming (4/9)

So what is an Object ?

Collection of:

Fields also known as members (object state, instance variables, ..)

Methods (behaviors, …)
www.3ds.com | © Dassault Systèmes

Each object has its own memory for maintaining state (the members)

E.g., each Part Object in Abaqus/CAE has vertices, edges etc.

All objects of the same type share code.

You can also think of an object as customized or template types of which multiple copies can be created
at runtime.

Custom template types are created by a “Class definition”

We will see how to construct Objects with a class definition next.

L6.6
Introduction to Object Oriented Programming (5/9)

Classes: Class Syntax to define objects.

A class is defined with the class statement


class MyClass:
attr = 0 class variable or member

By convention, class names are capitalized


www.3ds.com | © Dassault Systèmes

Once defined, an object of the class type may be created by instantiation.


myInstance = MyClass() multiple objects can be created.

Attributes of an object may be created on the fly (dynamically)


myInstance.attr = 1 instance variable (not allowed for Abaqus objects)

Attributes may be initialized automatically by using __init__ constructor


class MyClass:
def __init__(self): init method is known as the constructor.
self.attr = 1 This constructor is executed automatically
every time an instance is created.

instance variable
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.7
Introduction to Object Oriented Programming (6/9)

Example: Class

The Square class draws a square of a specific size and color.


class Square:
def __init__(self, size):
self.size = size
self.color = 'Red' # Set the default color to 'Red'
def setColor(self, color): Class Functions or
self.color = color
www.3ds.com | © Dassault Systèmes

Methods
def draw(self):
s = self.size * 0.5

Create as many copies of the object Square at


>>> sq = Square(5) run time as desired. Each Square object will
>>> sq2 = Square(10.0) have a state (size and color) and a behavior
>>> sq.size (draw and setColor methods can be invoked).
5.0
>>>sq2.size
10.0 An example from Abaqus/CAE: You can think of
>>> sq.color “Part” as an object which has been defined with
'Red' a class definition. You can create as many
>>> sq.setColor('Blue')
copies of the part as you wish at run time.

L6.8
Introduction to Object Oriented Programming (7/9)

Example: Objects in Python

In Python, everything is an object. For example, consider a list object.

L = [1,2,3] In Python, this syntax is a special case of a constructor for a list

A list has a state which is represented by its contents (values)


www.3ds.com | © Dassault Systèmes

>>> L
[1, 2, 3]

A list has some behavior which is represented by its methods

>>> dir(L)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']

A list has an identity

>>> id(L)
17858620
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.9
Introduction to Object Oriented Programming (8/9)

Classes can be extended via Inheritance.

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.
www.3ds.com | © Dassault Systèmes

Generalized class Animal


Example of an animal class hierarchy
intended to demonstrate class
inheritance
Mammal

Cat Dog Primate

Specialized class Abaqus User

L6.10
Introduction to Object Oriented Programming (9/9)

Object Oriented Decomposition gives:

Reusability or modularity.

Ease of scalability or extensibility via inheritance.

Encapsulation or data protection.


www.3ds.com | © Dassault Systèmes

But any object oriented decomposition does not accomplish the above !!

Only a good Object oriented design will !!

In Python, object-oriented programming is an option that is supported but not imposed.

As you gain experience programming, learning the object-oriented features of Python can help you write better
code.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.11
Abaqus Object Model Basics (1/7)

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.
www.3ds.com | © Dassault Systèmes

There are three roots in the


Abaqus object model: the Session,
the Mdb, and the Odb objects.

Taken from the Abaqus Scripting User's Manual The complete Abaqus object
(available online only) model is too complex to easily
present in a single figure.

A container is either a sequence


or a repository of like objects.

L6.12
Abaqus Object Model Basics (2/7)

Basics

The object model describes the relationships between objects.

A Part owns features, datums,


www.3ds.com | © Dassault Systèmes

etc.

A Model
owns
parts

Ownership implies that if an object is copied, everything owned by that object is also copied. Similarly, if
an object is deleted, everything owned by the object is deleted. This concept is known as a parent-child
relationship in Abaqus/CAE.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.13
Abaqus Object Model Basics (3/7)

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.


www.3ds.com | © Dassault Systèmes

Any Python statement that accesses the Session, Mdb, or Odb is called a command.

L6.14
Abaqus Object Model Basics (4/7)

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))
www.3ds.com | © Dassault Systèmes

cell4 = mdb.models['block'].parts['crankcase'].cells[4]

Variable Model database model named part named cell with


cell4 mdb block crankcase index 4

The cell with an index of 4 in the part named crankcase in the model named block in the model
database mdb is assigned to the variable cell4.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.15
Abaqus Object Model Basics (5/7)

The Access and Path descriptions in the Abaqus Scripting Reference Manual describe the access to and
interface for each Abaqus object.
www.3ds.com | © Dassault Systèmes

L6.16
Abaqus Object Model Basics (6/7)

Constructor example

p = mdb.models['Model-1'].Part(name='Part-1',
dimensionality=THREE_D, type=DEFORMABLE_BODY)

The path to the constructor is


www.3ds.com | © Dassault Systèmes

mdb.models['Model-1'].Part

The new Part object is placed into the parts repository

mdb.models['Model-1'].parts['Part-1']
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.17
Abaqus Object Model Basics (7/7)

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).
www.3ds.com | © Dassault Systèmes

The following statement modifies the rendition member of the printOptions object (values of other
members are not changed):
session.printOptions.setValues(rendition=GREYSCALE)

L6.18
The Session Object (1/8)

The Session object model


www.3ds.com | © Dassault Systèmes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.19
The Session Object (2/8)

The Session object model (cont'd)

Session objects can be saved to the model database,


to an output database, or to a settings file in XML format
for use in subsequent sessions.

Session objects include things such as viewport definitions,


remote queues, and user-defined views.
www.3ds.com | © Dassault Systèmes

The Session objects are normally available only from inside


of Abaqus/Viewer or Abaqus/CAE.

Either of the following statements imports the Session object:

from abaqus import *


from abaqus import session

L6.20
The Session Object (3/8)

Visualization commands

Displaying an output database in a viewport

odb = session.openOdb(name='viewer_tutorial.odb')
vp = session.viewports['Viewport: 1']
vp.setValues(displayedObject=odb)
www.3ds.com | © Dassault Systèmes

Plotting contours of PEEQ

od = vp.odbDisplay
od.setPrimaryVariable(variableLabel='PEEQ',
outputPosition=INTEGRATION_POINT)
od.display.setValues(plotState=(CONTOURS_ON_DEF,))

The ODB Display object called vp.odbDisplay has the settings for how the output database is
displayed in a viewport.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.21
The Session Object (4/8)

Annotation commands

Annotate the current plot.

vp.plotAnnotation(
mdb.Text(name='test run', offset=(70, 110),
text= 'Test Run #146'))
www.3ds.com | © Dassault Systèmes

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

L6.22
The Session Object (5/8)

Example: Automating the display of output data


# 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.
www.3ds.com | © Dassault Systèmes

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.
lastStep = odb.steps.values()[-1] this can be an integer
lastFrame = lastStep.frames[-1] or a frame object
vp.odbDisplay.setFrame(frame=lastFrame)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.23
The Session Object (6/8)

Example (cont'd)

# 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()
www.3ds.com | © Dassault Systèmes

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

L6.24
The Session Object (7/8)

Example (cont'd)
www.3ds.com | © Dassault Systèmes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.25
The Session Object (8/8)

Example: Create an array of viewports.

The scr_viewport_tiler.py script


defines two functions:

createViewports()
www.3ds.com | © Dassault Systèmes

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.

L6.26
The Mdb Object (1/5)

The Mdb object model

Mdb objects are persistent.

The Mdb objects are normally


available only from inside Abaqus/Viewer
www.3ds.com | © Dassault Systèmes

or Abaqus/CAE.

Either of the following statements imports


the Mdb objects

from abaqus import *


from abaqus import mdb
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.27
The Mdb Object (2/5)

Example: Create a part in the form of the letter A.

1 Import modules and create the mdb object.

from abaqus import *


from abaqusConstants import *
from caeModules import *
www.3ds.com | © Dassault Systèmes

Mdb()

This constructor creates the mdb object

L6.28
The Mdb Object (3/5)

2 Draw a two-dimensional sketch.

myModel = mdb.Model(name='Model A')

mySketch = myModel.ConstrainedSketch(
name='Sketch A', sheetSize=200.0)

xyCoordsInner = ((-5 , 20), (5, 20), (15, 0),


(-15, 0), (-5, 20))
www.3ds.com | © Dassault Systèmes

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])
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.29
The Mdb Object (4/5)

3 Create a part and add a base feature using the sketch.

myPart = myModel.Part(name='Part A',


dimensionality=THREE_D, type=DEFORMABLE_BODY)
myPart.BaseSolidExtrude(sketch=mySketch,
depth=20.0)
www.3ds.com | © Dassault Systèmes

4 Instance the part in the root assembly.

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


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

L6.30
The Mdb Object (5/5)

5 Mesh the instance.

partInstances = (myInstance,)
myAssembly.seedPartInstance(
regions=partInstances, size=5.0)
myAssembly.generateMesh(regions=partInstances)
www.3ds.com | © Dassault Systèmes

6 Plot the meshed instance in a new viewport.

myViewport = session.Viewport(name='Viewport for Model A',


origin=(20, 20), width=150, height=100)
myViewport.assemblyDisplay.setValues(renderStyle=SHADED, mesh=ON)
myViewport.setValues(displayedObject=myAssembly)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.31
Exploring Your Data (1/3)

Interrogate Object attributes

Use special attributes. For example:

>>> odb = openOdb('cantilever.odb')


>>> odb.__members__
['analysisTitle', 'closed', 'customData', 'description',
'diagnosticData', 'isReadOnly', 'jobData', 'name', 'parts', 'path',
www.3ds.com | © Dassault Systèmes

'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,
‘customData’: python object wrapper, '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'})

L6.32
Exploring Your Data (2/3)

prettyPrint function
>>> from textRepr import *
>>> prettyPrint(odb)
({'analysisTitle': 'Cantilever beam model',
'closed': FALSE,
'customData': None,
'description': 'DDB object',
'diagnosticData': 'OdbDiagnosticData object',
'isReadOnly': FALSE,
www.3ds.com | © Dassault Systèmes

'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)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.33
Exploring Your Data (3/3)

More textRepr functions

Functions in the textRepr module:


getIndentedRepr, getPaths, getTypes, prettyPrint,
prettyPrintToFile, prettyPrintToFileName, prettyPrintToTerm,
printPaths, printPathsToFile, printPathsToFileName,
printPathsToTerm, printTypes
www.3ds.com | © Dassault Systèmes

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

I. Note: optional arguments are shown within <...>

II. Use __doc__ to check arguments

L6.34
Abaqus Data Types (1/4)

Abaqus extends Python with Abaqus-specific types

Currently there are about 280 different types. For example, MaterialType,
HomogeneousSolidSectionType, etc.

All the Python types are still available.

To test for a specific type, use the type function


www.3ds.com | © Dassault Systèmes

type(mdb.models['Noname'].materials['Steel'])
<type 'Material'>
import section
s = mdb.models['Noname'].sections['sec-1']
...
...
if type(s) == section.HomogeneousSolidSectionType:
print 'This object is of type HomogeneousSolidSection'

Type objects are found in Python modules. Use the qualified name.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.35
Abaqus Data Types (2/4)

Repository (a keyed container)

Mapping type, like a dictionary.

Objects in a repository are of a similar type and immutable.

Repositories are typically used for models, parts, materials, etc.


www.3ds.com | © Dassault Systèmes

Objects are added to a repository using a constructor.

mdb.models['engine'].Material('steel')
steel = mdb.models['engine'].materials['steel']

Abaqus Array (an indexed container)

Sequence type, like a tuple.

For example, nodes and elements in meshes are stored in Abaqus arrays.

L6.36
Abaqus Data Types (3/4)

SymbolicConstant

Used as an argument to Abaqus methods and as member value in Abaqus objects.

SymbolicConstant variables are ALL_CAPS.

Examples: QUAD, SAX2T, RB2D2, DEFORMABLE, D_2D,


DEFORMABLE_BODY
www.3ds.com | © Dassault Systèmes

a.setMeshControls(elemShape=QUAD)

Boolean

Similar to a SymbolicConstant but has a value that can be truth tested.

In Abaqus, the available symbolic constants are ON, OFF, TRUE, FALSE.

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"
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.37
Abaqus Data Types (4/4)

Keywords

Methods on Abaqus objects accept keyword arguments.

Example: Change model shape on which contours are plotted.

vp = session.viewports['Viewport: 1']
vp.odbDisplay.contourOptions.setValues(shape=UNDEFORMED)
www.3ds.com | © Dassault Systèmes

L6.38
Abaqus Modules (1/9)

Terminology

The functionality of Abaqus/CAE and Abaqus/Viewer is presented through modules that are accessible
from a pull-down menu (for example, Part, Property, etc).

These modules provide sensible packaging of a graphical user interface and are referred to as
the GUI modules.
www.3ds.com | © Dassault Systèmes

For kernel scripting, functionality is accessible from Python modules that must be imported by the user.

These modules are referred to as kernel modules and have names that are mostly similar to the
GUI module names.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.39
Abaqus Modules (2/9)

Importing an Abaqus module

Abaqus modules are imported using the import statement, the same as any other Python module.

Convention: Module imports should be done at the top of each script.

Importing an Abaqus module does not affect the GUI appearance (for example, which module the GUI is
switched to).
www.3ds.com | © Dassault Systèmes

On startup, Abaqus/CAE calls

from abaqus import *


from abaqusConstants import *
from caeModules import *

The caeModules module imports the kernel modules. It has the same effect as

import part, material, assembly, … etc

L6.40
Abaqus Modules (3/9)

The module called abaqus defines two root objects of the Abaqus object model:

session

mdb
www.3ds.com | © Dassault Systèmes

non-persistent objects persistent objects

On the previous slide, why do we import using from abaqus import *?


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.41
Abaqus Modules (4/9)

Abaqus modules that augment existing objects

Kernel Module Functionality

part Creating and modifying parts

material Creating and modifying materials


www.3ds.com | © Dassault Systèmes

section Creating and modifying sections

assembly Creating and modifying assemblies

step Creating and modifying steps

interaction Creating and modifying interactions

load Creating and modifying loads and boundary conditions

mesh Meshing part instances

job Creating, submitting, and monitoring jobs

visualization Visualizing results

sketch Creating and modifying sketches

L6.42
Abaqus Modules (5/9)

Abaqus modules that do not augment existing objects

Kernel Module Functionality

abaqus Abaqus object model root objects

abaqusConstants Abaqus symbolic constant objects


www.3ds.com | © Dassault Systèmes

odbAccess Tools for reading and writing ODB data

osutils UNIX-like shell utilities that are designed to behave the same on
different platforms

textRepr Print functions for exploring the object model


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.43
Abaqus Modules (6/9)

Useful Python modules that are delivered with Abaqus (these modules also do not augment existing objects)

Other Modules Functionality

Numpy Efficient manipulation of large arrays

shutil Provides high-level file operations


www.3ds.com | © Dassault Systèmes

shelve Provides support for persistent objects using a special shelf object

re Regular expression pattern matching and replacement

math, cmath Provides standard mathematical functions and constants

random Generates pseudo-random numbers

This is not a complete list of modules included with Abaqus

L6.44
Abaqus Modules (7/9)

Recommended methods for importing modules

1. 3.
import moduleName from moduleName import *

This is the recommended method for This method is not recommended.


www.3ds.com | © Dassault Systèmes

importing Python modules most of the


time. Exception: often used for three Abaqus modules:
Benefits: (1) abaqus
Avoids name clashing (2) odbAccess
Can be used in functions (3) abaqusConstants

Much effort has been made to design these


modules to avoid name clashing.

2. Should not do this inside a function.


from moduleName import name

This is OK if you prefer. It also avoids


name clashing by minimizing the number
of names.
Can also be used in functions.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L6.45
Abaqus Modules (8/9)

Recommended methods for importing modules (cont'd)

4.
import moduleName as pseudoName
www.3ds.com | © Dassault Systèmes

This is an alternate approach that is also recommended for importing Python modules.
Benefits:
Avoids name clashing
Avoids using long identifiers
Example:
import displayGroupOdbToolset as dgo
leaf = dgo.LeafFromElementSets(elementSets=('PART-1-1.E1', ))
session.viewports['Viewport:1'].odbDisplay.displayGroup.replace(
leaf=leaf)
vp.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF,))

L6.46
Abaqus Modules (9/9)
Tip: if you want to write scripts that work for non-
osutils Abaqus versions of Python, then do not get in the
habit of using the osutils module.

This is a collection of shell utilities such as move, copy, and removeTree. It is intended to provide
consistent behavior over different platforms.

osutils.chmod
www.3ds.com | © Dassault Systèmes

osutils.chmodRecursive Each function has a __doc__ string that describes its


osutils.compare usage.
osutils.compareTree
osutils.copy The functionality is intended to be slightly enhanced
osutils.copyTree over built-in modules such as os and sys
osutils.makeDir
osutils.move
osutils.remoteCopy
osutils.remoteMove
osutils.remoteShell
osutils.remoteShellCommand
osutils.remove
osutils.removeTree
osutils.rename
osutils.sameFile
osutils.touch
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes

60 minutes
a. Navigate the Abaqus Scripting Manual
1. When you complete this workshop, you will be able to:

b. Manipulate an object in the viewport using a script


Workshop 8: Working with the Session Object
L6.47
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.1
Lesson 7: Postprocessing with Abaqus Scripting

Lesson content:

The Odb Object


Writing to the Odb
Examples
Workshop 9: Working with the ODB Object
Workshop 10: Linear Superposition
www.3ds.com | © Dassault Systèmes

2 ¾ hours

L7.2
The Odb Object (1/18)

Output Database Object Model

Results data in the ODB are categorized as Field Data or History Data.

Odb objects are persistent.

The Odb object is normally available from inside or outside of Abaqus/Viewer or Abaqus/CAE.
www.3ds.com | © Dassault Systèmes

Field Data

History Data
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.3
The Odb Object (2/18)

Accessing ODB root objects

From within the interactive products:

import visualization
session.openOdb(<odb path>)
www.3ds.com | © Dassault Systèmes

This method allows Abaqus/CAE to keep track of the open output databases:

I. Opens an existing output database (.odb) file

II. Creates a new Odb object

III. Adds the new Odb object to the session.odbs repository.

L7.4
The Odb Object (3/18)

Access to odb object from outside of the interactive products:

from odbAccess import *


o = openOdb(<odb path>)

This will not use Abaqus tokens but Abaqus/CAE Session functionality will be unavailable. Odb
object model is same in either case.
www.3ds.com | © Dassault Systèmes

Useful for third party developers. Sometimes can be useful for batch mode on clusters.

Note if both batch mode of execution and Abaqus/CAE functionality is desired use
“abaqus cae –noGUI scriptname”

When you execute outside of Abaqus/CAE typically only one output database is open at a time.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.5
The Odb Object (4/18)

Examples: Accessing the odb root objects

Example from within the interactive products

import visualization
odb1 = session.openOdb('/home/job1.odb')
odb2 = session.openOdb('/home/job2.odb')
odb3 = session.openOdb('/home/job3.odb')
for odb in session.odbs.values():
www.3ds.com | © Dassault Systèmes

odb.close() The session.openOdb() method allows


Abaqus/CAE to keep track of the open output
databases
Example from outside of the interactive products

from odbAcess import *


odb1 = openOdb('/home/job1.odb')
odb2 = openOdb('/home/job2.odb')
odb3 = openOdb('/home/job3.odb')
odb1.close()
odb2.close()
odb3.close()

L7.6
The Odb Object (5/18)
Field Data
steps (type = Repository)

Background: each step in the analysis is associated with an analysis procedure.

The output data for an Abaqus analysis contains a repository of one or more step objects.

The key to the repository is the name of the step (user defined when building the model).
www.3ds.com | © Dassault Systèmes

Examples: accessing two steps by name and by pseudo-index

crushStep = odb.steps['Crush']
lastStep = odb.steps.values()[-1]
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.7
The Odb Object (6/18)
Field Data
frames (type = OdbFrameArray)

Background: Each increment of the analysis that writes output to the output database is called a frame.

The index to the frame sequence is not the frame number.

Examples: accessing two frames by index


www.3ds.com | © Dassault Systèmes

firstFrame = crushStep.frames[0]
Standard Python
lastFrame = lastStep.frames[-1] 0th-based indexing

Field Data

History Data

L7.8
The Odb Object (7/18)
Field Data
fieldOutputs (type = Repository)

Background: Different variables can be written to the output database at different frequencies. As a
result, not all frames will contain all of the field output variables.

Field output data objects are stored in the fieldOutputs repository under the Odb frames object.

The key to the repository is the name of the output variable. For example, here we are accessing the
www.3ds.com | © Dassault Systèmes

field output for stress:

stress = crushFrame.fieldOutputs['S']
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.9
The Odb Object (8/18)

Example: One statement access to the result

stress = odb.steps['Crush'].frames[-1].fieldOutputs['S']

Variable Output Step named The last Field output


stress database odb Crush Frame named S
www.3ds.com | © Dassault Systèmes

The field output named S in the last frame of the step named Crush in the output database object called
odb is assigned to the identifier stress.

This example does not use intermediate assignments.

The code using intermediate assignments:

odb = session.openOdb('/home/job1.odb')
steps = odb.steps
frames = steps[„Crush‟]
stress = frames[-1].fieldOutputs['S']

L7.10
The Odb Object (9/18)

FieldOuptut Object

By default the field output data is output for the full model.

So the FieldOutput object stress in the previous case will include stress values at all the elements in
the model for last frame of step Crush.

It contains a “cloud or array of field value objects” (e.g., stress tensors at each integration point for all
www.3ds.com | © Dassault Systèmes

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.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.11
The Odb Object (10/18)
Field Data
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.
www.3ds.com | © Dassault Systèmes

## Restrict the stress output to a prticular elementset


instance = odb.rootAssembly.instances[“PART-1-1”]
elSet1 = instance.elementSet[“elSet1”]
stress.getSubset(region=elSet1)

L7.12
The Odb Object (11/18)
Field Data
getSubset() method

The getSubset() method can be thought of as a filter to restrict the FieldOutput object to a certain
section of the model.

The method returns a fieldOutput object.

Arguments to getSubset() can include position, sectionPoint, region


www.3ds.com | © Dassault Systèmes

(node,elements,elementsets etc), location, and localCoordSystem.

Possible values for the position argument to the getSubset command are
INTEGRATION_POINT, NODAL, ELEMENT_NODAL, CENTROID.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.13
The Odb Object (12/18)
Field Data
Performance considerations for the getSubset() method

The use of the getSubset() method is optional.

The getSubset() method is used to facilitate efficient random access of the ODB.

As a general rule, the efficiency of the getSubset() method will break down when trying to access
www.3ds.com | © Dassault Systèmes

more than half of the model.

The performance of the getSubset() method should be evaluated on a case-by-case basis when
accessing data for large regions of a database.

See SIMULIA Answer 4131 for guidelines for improving performance when using the ODB API

L7.14
The Odb Object (13/18)

Mathematical operations are supported for FieldOutput objects.

Performed on tensors and vectors.

Examples: stress1 + stress2, 2.*stress

Invariants are calculated after the operation.


www.3ds.com | © Dassault Systèmes

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()
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.15
The Odb Object (14/18)
History Data
historyRegions (type = Repository)

All output values for a single point or for some larger region are collected in a historyRegions object.

The historyRegions object is analogous to the frames object for field data.

The key to the repository should describe the portion of the model that is associated with the data. For
example:
www.3ds.com | © Dassault Systèmes

somePoint = crushStep.historyRegions['Beam Tip']

Field Data

History Data

L7.16
The Odb Object (15/18)
History Data
historyRegions (cont'd)

The history region will correspond to one of the following spatial associations:

A node A region

An integration point A material point


www.3ds.com | © Dassault Systèmes

Consistent with this, a default naming style for repository keys is used by Abaqus.

For example, this name was created for nodal data:

stepObject.historyRegions['Node Part-1-1.415']
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.17
The Odb Object (16/18)
History Data
historyRegions (cont'd)

The type of output variable that is requested by the user (prior to submitting the job) will determine the
spatial association. For example:

Abaqus input file


www.3ds.com | © Dassault Systèmes

*Output, history, freq=1


*node output, nset=tip1
u1,u2,
*element output, elset=E1
S11,S22,
*energy output, elset=E2
ALLIE,

>>> regions = odb.steps[stepName].historyRegions


>>> regions['ElementSet E2'].position
WHOLE_REGION
>>> regions['Element PART-1-1.1 Int Point 7'].position
INTEGRATION_POINT
>>> regions['Node PART-1-1.64'].position
NODAL

L7.18
The Odb Object (17/18)
History Data
historyOutputs (type = Repository)

History data is stored in the historyOutputs repository, under the ODB historyRegions object.

This repository contains all the output for a specific point or region for a given step.

The key to the repository is the name of the output variable.

Each item in the repository contains a sequence of sequences.


www.3ds.com | © Dassault Systèmes

For domain = TIME, the sequence is a tuple of (stepTime, value)

For domain = FREQUENCY, the sequence is a tuple of (frequency, value)

For domain = MODAL, the sequence is a tuple of (mode, value)

Examples:
u2Deflection = endPoint.historyOutputs['U2']
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.19
The Odb Object (18/18)

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')
www.3ds.com | © Dassault Systèmes

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.

L7.20
Writing to the Odb (1/2)

External data is data that is prepared outside Abaqus can be added to the ODB file.

It is useful to add new fieldOutput variables to the ODB.

It is also useful for 3rd-party developers to integrate results inside of Abaqus.

Note: Data cannot be deleted from the output database.


www.3ds.com | © Dassault Systèmes

Workaround: Create a new .odb file, and write data that is copied from an existing .odb file.

We will walk over some of the ASI Python commands to add data to the ODB

Creating an output database

odb = Odb(name='myData', analysisTitle='derived data',


description='test problem', path='testWrite.odb')
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.21
Writing to the Odb (2/2)

Creating a step

myStep = odb.Step(name='My Step', description='',


domain=TIME, timePeriod=1.0)

Creating a frame

myFrame = myStep.Frame(frameId=1, frameValue=0.1,


www.3ds.com | © Dassault Systèmes

description='')

Creating field output

uField = myFrame.FieldOutput(name='U',
description='Displacements', type=VECTOR)

Adding result data to field output

nodeLabels = (1, 2, 3, 4, 5, 6)
nodeDisplacements = (
(1.0,2.0,3.0), (4.0,5.0,6.0), (7.0,8.0,9.0),
(10.0,11.0,12.0), (13.0,14.0,15.0), (16.0,17.0,18.0) )
uField.addData(position=NODAL, instance=myInstance,
labels=nodeLabels, data=nodeDisplacements)

L7.22
Examples (1/3)

Field Data
Example 1: Reading some field data

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']
www.3ds.com | © Dassault Systèmes

# 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)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L7.23
Examples (2/3)

Field Data
Example 1: Reading some field data (cont’d)

# 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.position
print 'Type = ', v.type
print 'Node label = ', v.nodeLabel
www.3ds.com | © Dassault Systèmes

print 'X displacement = ', v.data[0]


print 'Y displacement = ', v.data[1]
print 'Displacement magnitude =', v.magnitude
odb.close()

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

L7.24
Examples (3/3)

Example 2: Multiple frames in one plot


www.3ds.com | © Dassault Systèmes
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

commands

60 minutes
60 minutes

b. display the new field in Abaqus/Viewer


1. When you complete this workshop, you will be able to:
Workshop 10: Linear Superposition
Workshop 9: Working with the ODB Object

a. combine results from 2 separate fields on the ODB to create a new temporary field
1. When you complete this workshop you will be able to read data from an Abaqus ODB file using scripting

L7.26
L7.25
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.1
Lesson 8: Miscellaneous Topics

Lesson content:

Plug-ins
Really Simple GUI (RSG)
Job Monitoring
Custom Data
Setting Abaqus Defaults
www.3ds.com | © Dassault Systèmes

Workshop 11: Creating Kernel and GUI Scripts


Workshop 12: Setting Abaqus Defaults

3 hours

L8.2
Plug-ins (1/4)

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)


www.3ds.com | © Dassault Systèmes

A plug-in registration file must have a name ending in _plugins.py

Abaqus/CAE searches for plug-in registration files in

abaqus_dir/code/python/lib/abaqus_plugins, where abaqus_dir is the Abaqus installation


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.


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.3
Plug-ins (2/4)

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])
www.3ds.com | © Dassault Systèmes

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

L8.4
Plug-ins (3/4)

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.
www.3ds.com | © Dassault Systèmes
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.5
Plug-ins (4/4)

GUI plug-in

GUI plug-ins execute Abaqus GUI Toolkit commands (details are not addressed in this course).

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

RSG:
www.3ds.com | © Dassault Systèmes

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

L8.6
Really Simple GUI (1/14)

RSG: What is RSG?

It is an Abaqus/CAE plug-in
Plug-ins->Really Simple GUI->Create a Dialog...

Interactive tool for building a Graphical User Interface (GUI)

Includes widgets (controls)


www.3ds.com | © Dassault Systèmes

Layout managers for controlling the look of the dialog box


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.7
Really Simple GUI (2/14)

Steps for creating a RSG plug-in

Use RSG to create the look and feel of the GUI

Create icons and/or pictures if needed

Drawing program
www.3ds.com | © Dassault Systèmes

Painting program

Abaqus/CAE

Create a Python kernel script to interface between the RSG and Abaqus/CAE

Must include error checking for user input

Test and debug

L8.8
Really Simple GUI (3/14)

Steps for creating a RSG plug-in (cont’d)

A shortcut for creating the kernel script is to execute the Abaqus/CAE commands that you want via the
normal Abaqus/CAE GUI

All Python commands necessary to reproduce the action are saved to the replay file in your work
directory
www.3ds.com | © Dassault Systèmes

Save this file to kernel_file_name.py

This file will be modified to create the kernel script

Move commands into a function

Substitute variables for hard coded values

Use if statements for other selections or options

Clean out unnecessary Python commands


For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

Python
Includes

commands
option

Replay File
option

Gravity
Material

selection
Cantilever Beam Demo

Really Simple GUI (5/14)


Really Simple GUI (4/14)

results, this executes the kernel script


Hit OK to build model, analyze, and display
Text entry boxes for dimensions and load

Created icon
showing definitions

L8.10
L8.9
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

Indent

indenting)
Includes
New name

code blocks with


Function added

(Python delineates
in the RSG interface)
(Kernel function name

Hard coded values


and keywords are defined

Really Simple GUI (7/14)


Really Simple GUI (6/14)

Kernel Script

GUI keywords
Variables from

Variables
Kernel Script Variable Substitution
L8.12
L8.11
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.13
Really Simple GUI (8/14)

Error checking

“Built In” Error checking

Check button

Radio buttons
www.3ds.com | © Dassault Systèmes

List / Combo boxes

Text Field

Automatically checks for float, integer,


or string

Need to check values

Use raise

L8.14
Really Simple GUI (9/14)

Error checking (cont’d)

File Selection

Type – Use Patterns

Format
www.3ds.com | © Dassault Systèmes

Pick from viewport

Can limit selection type

I. Mesh – nodes, elements, element edges, etc.

II. Geometry – vertices, edges, faces, cells, etc.

III. Sketch – vertices, dimensions, constraints, etc.

Need to verify right selection


For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes www.3ds.com | © Dassault Systèmes

Example
Really Simple GUI (11/14)
Really Simple GUI (10/14)

L8.16
L8.15
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.17
Really Simple GUI (12/14)

Limitations

Plug-in use only

Abaqus/CAE must be running

Some Widgets are not available (yet)


www.3ds.com | © Dassault Systèmes

Cannot currently pop up additional dialogs

getInput( )
GetWarningReply( )
showAFXInformationDialog( )
Other RSG dialogs

Cannot change interface “on the fly”

Greyed out widgets


Changing widget contents based on others

L8.18
Really Simple GUI (13/14)

Generating Fox GUI code

Able to create regular Fox GUI plug-in code

Regular Abaqus GUI Toolkit code

Use it as a basis for more complex GUIs and circumventing RSG limitations
www.3ds.com | © Dassault Systèmes

I. Pop up dialogs

II. Grey out

III. Widget contents

IV. Not easy

V. Additional knowledge of GUI toolkit


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.19
Really Simple GUI (14/14)

Summary

RSG is a great way to quickly create a plug-in GUI for Abaqus/CAE

Modifying replay files is a great shortcut for kernel scripts

Easy to do with RSG and replay


www.3ds.com | © Dassault Systèmes

Quick to do, just a few hours for simple models and designs

Limited to plug-in use for Abaqus/CAE, not a standalone GUI

Complex models may take substantially more time

Kernel scripting will get complex

Changing geometry creation

Surface selection

Point selection

Etc.

L8.20
Job Monitoring (1/3)

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.
www.3ds.com | © Dassault Systèmes

This is accomplished by writing a callback function and registering it with the monitorManager object.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.21
Job Monitoring (2/3)

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):
www.3ds.com | © Dassault Systèmes

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)

L8.22
Job Monitoring (3/3)

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.
www.3ds.com | © Dassault Systèmes

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()
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.23
Custom Data

mdb.customData

User specified data, using Python objects or user specified classes

Persistent (saved to .cae or .odb file)

Lazy evaluation, on import customKernel, i.e.


>>> mdb.customData
www.3ds.com | © Dassault Systèmes

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


>>> import customKernel
>>> mdb.customData
mdb.customData

Adding data is simple, i.e.


>>> mdb.customData.notes = "This model was built in 6.12"
>>> mdb.customData.notes
"6.12"
>>> odb = session.odbs['D:\temp\viewer_tutorial.odb']
>>> odb.customData.myDict = {}

L8.24
Setting Abaqus Defaults (1/2)

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.


www.3ds.com | © Dassault Systèmes

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.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
L8.25
Setting Abaqus Defaults (2/2)

Abaqus environment file: abaqus_v6.env


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

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

# Print preferences
www.3ds.com | © Dassault Systèmes

session.printOptions.setValues(vpDecorations=OFF, vpBackground=OFF,
rendition=COLOR, printCommand='lpr')

# Visualization preferences
def setVisPreferences(module, userData):
from visualization import SHADED, EXTERIOR, CONTINUOUS
session.defaultOdbDisplay.commonOptions.setValues(
renderStyle=SHADED, visibleEdges=EXTERIOR)
session.defaultOdbDisplay.contourOptions.setValues(
contourStyle=CONTINUOUS)
addImportCallback('visualization', setVisPreferences)

# Material properties - read them from a file


execfile('my_material_library.py')

L8.26
Workshop 11: Creating Kernel and GUI Scripts

1. When you complete this workshop you will be able to:


a. transform a replay file into a kernel script
b. build a GUI dialog using RSG to run the kernel script
www.3ds.com | © Dassault Systèmes

60 minutes
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@

www.3ds.com | © Dassault Systèmes

60 minutes
1. When you complete this workshop you will be able to:
Workshop 12: Setting Abaqus Defaults

a. use the Abaqus environment file to customize some default settings of Abaqus/CAE
L8.27
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.1
Appendix 1

Lesson content:

Data Types
Objects
Common Issues for New Users
Setting Abaqus Defaults
Objects
www.3ds.com | © Dassault Systèmes

Custom Data

30 minutes

A1.2
Data Types (1/3)

Function Type

A function encapsulates code to perform a specific task.


>>> def test(arg1, arg2):
... print 'arg1=', arg1
... print 'arg2=', arg2
...
>>> test('pink', 'bicycle')
arg1= pink
www.3ds.com | © Dassault Systèmes

arg2= bicycle

A function can return any object.


>>> def distance(point1, point2):
... x1, y1 = point1[0], point1[1]
... x2, y2 = point2[0], point2[1]
... sq = (x2 - x1)**2 + (y2 - y1)**2
... return sq**(0.5)
...
>>> distance((0,0),(4,6))
7.21110255093
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.3
Data Types (2/3)

File Type

Files are named storage compartments.

The Python file type is an abstract object that provides a way to access files.

All Python file I/O is performed on abstract file objects, rather than file names.
www.3ds.com | © Dassault Systèmes

The open method does not actually read the file; instead it returns a file object.

Once open, file objects must be closed to free system resources.

Closing a file is done with the close method.

Example:
f = open('filename', 'r')
line = f.readline()
f.close()

A1.4
Data Types (3/3)

Traceback Type

The traceback object is created when an exception occurs and contains stack trace information.

This is one type of object that is used by the interpreter and exposed to the user.

Example:
>>> 1+'1'
www.3ds.com | © Dassault Systèmes

Traceback (most recent call last):


File "<interactive input>", line 1, in ?
TypeError: unsupported operand types for +
>>> type(1)
<type 'int'>
>>> type(type(1))
<type 'type'>
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.5
Objects (1/3)

Reference Counting – Increasing the count

Python provides automatic memory management through a reference counting mechanism.

Assignment sets a reference to an object.

All objects are reference counted.


www.3ds.com | © Dassault Systèmes

An object’s reference count increases when it is assigned a new name or placed in a container.

>>> a = 1 a 1
>>> b = a
>>> c = [b, 2] b
2
c

A1.6
Objects (2/3)

Reference Counting – Decreasing the count

An object’s reference count decreases when a reference is reassigned (or goes out of scope) or when
removed by the del statement.

Python keeps track of low level memory details. When an object’s reference count is zero, an object’s
memory space is reclaimed (a process called garbage collection) and the object is put back on the C-
heap*.
www.3ds.com | © Dassault Systèmes

>>> del a 1
>>> c[1] = b
b

* Actually, some internal optimization occurs: small integers and strings are
cached and are not recreated for each use
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.7
Objects (3/3)

Reference Counting – Cyclical references

Later versions of Python are equipped with garbage collecting that can handle cyclical references to
objects.

For example, in the code below, the reference count of each does not normally go to zero because of
the cross reference. To address this problem, the interpreter deletes objects based on cycles of
inaccessibility.
www.3ds.com | © Dassault Systèmes

A module called gc provides user control of the cycle detection algorithm

The del statements removes the pointers and decreases


the reference count of dictA and dictB.
>>> dictA = {}
>>> dictB = {}
>>> dictA[0] = dictB
>>> dictB[0] = dictA
>>> del dictA; del dictB dictA dictB

A1.8
Common Issues for New Users

Frequently asked questions

What are all these .pyc files?

Python creates binary .pyc files from the source .py files when a module is imported. The
.pyc files are recreated on import if the source code changes.

Is this language compiled or interpreted?


www.3ds.com | © Dassault Systèmes

Strictly speaking, Python programs are compiled (translated) to an intermediate form called
bytecode (the .pyc files) which is then run by the interpreter.

The compile step is automatic and hidden from the user.

This functionality provides a nice tradeoff between development speed and computational
performance.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.9
Setting Abaqus Defaults (1/3)

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
www.3ds.com | © Dassault Systèmes

In the onCaeStartup function, you may omit the lines


from abaqus import *
from abaqusConstants import *

To find all variables in the namespace, do the following:


for name in globals().keys():
if name != '__builtins__':
print '%s = %s' % (name , eval(name))
(this code be used at top level or within one of the functions)

A1.10
Setting Abaqus Defaults (2/3)

abaqus_v6.env (continued)

Certain variables are predefined in onJobCompletion and onJobStartup. These include:


savedir, id, scrdir, analysisType, applicationName, abaqus_version.

def onJobCompletion():
import os
extensions = ('res','stt','mdl','prt','abq','pac')
restartDir = savedir + id + '_restart' + os.sep
www.3ds.com | © Dassault Systèmes

if (not os.path.exists(restartDir)):
os.mkdir(restartDir)
for extension in extensions:
fileName = id + '.' + extension
if (os.path.exists(savedir + fileName)):
os.rename(savedir + fileName, restartDir + fileName)

def onJobStartup():
import os, osutils
restartDir = savedir + id + '_restart'
if (os.path.exists(restartDir)):
osutils.removeTree(restartDir)
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.11
Setting Abaqus Defaults (3/3)

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
www.3ds.com | © Dassault Systèmes

In the onCaeStartup function, you may omit the lines


from abaqus import *
from abaqusConstants import *

To find all variables in the namespace, do the following:


for name in globals().keys():
if name != '__builtins__':
print '%s = %s' % (name , eval(name))
(this code be used at top level or within one of the functions)

A1.12
Objects

Repetition Copy

An repetition operation also makes a one-level deep (shallow) copy of the sequence. Shallow copy
example:

>>> L0 = [1, 2, 3]
>>> L1 = L0 * 2 2
www.3ds.com | © Dassault Systèmes

>>> L2 = [L0] * 2
>>> L0[1] = 0
>>> L1 L1
[1, 2, 3, 1, 2, 3]
>>> L2
[[1, 0, 3], [1, 0, 3]]
>>> L2[0][1] = 2
>>> L2 1 0
[[1, 2, 3], [1, 2, 3]]
3
L0
Same as
[L0] + [L0]

Same as L2
[1, 2, 3] + [1, 2, 3]
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by
A1.13
Custom Data

mdb.customData

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


www.3ds.com | © Dassault Systèmes

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

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.
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 1
Creating and Reviewing a Replay File

Goals
When you complete this workshop, you will be able to:
1. Create an Abaqus/CAE model.
2. Understand the commands written to the replay file when creating an
Abaqus/CAE model.
3. Use the replay file to recreate a model.
4. Edit a replay file to modify a model.

Introduction
In this workshop you will create a very simple Abaqus/CAE model and then review the
Abaqus Scripting Interface commands that are written to the replay file. The model is a
square tube with a through hole at one end. It is modeled with shell elements. A free
modal analysis is performed on it. The completed model is shown in Figure W1–1.

Figure W1–1

Preliminaries
1. Start a new session of Abaqus/CAE using the following command:
abaqus cae
where abaqus is the command used to run Abaqus.
2. In the Start Session dialog box, underneath Create Model Database, click With
Standard/Explicit Model.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W1.2

Creating a part
1. Click the Create Part tool.
2. In the Create Part dialog box, name the part Tube.
3. Change the base feature shape to Shell and the type to Extrusion; click
Continue.
4. In the sketcher click the Create Lines: Rectangle tool.
5. For the starting corner enter -10, 10.
6. For the opposite corner enter 10, -10.
7. Click the red X button to quit the rectangle tool.
8. The resulting sketch should look as shown Figure W1–2.

Figure W1–2

9. Click Done.
10. In the Edit Base Extrusion dialog enter 100 for the depth, and click OK.

Create and assign properties


Create a material
1. Switch to the Property module. Click the Create Material tool.
2. In the Create Material dialog box, enter Steel as the material name.
3. In the Material Behaviors menu, select General→Density. Enter 7.7e-9
for the mass density.
4. In the Material Behaviors menu, select Mechanical→Elasticity→Elastic.
Enter 207000 for Young's Modulus and 0.3 for Poisson's Ratio. Click OK.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W1.3

Create a section
1. Click the Create Section tool.
2. In the Create Section dialog box, enter ShellSect as the section name.
3. Switch the Category to Shell and click Continue.
4. Enter 1.0 for the shell thickness and click OK.

Assign the section


1. Click the Assign Section tool.
2. Select all surfaces in the model. Click Done.
3. Click OK in the Edit Section dialog box.

Instance into the assembly


1. Switch to the Assembly module. Click the Create Instance tool. Click OK.

Create a step
1. Switch to the Step module. Click the Create Step tool.
2. Enter Modal as the step name.
3. Select Linear Perturbation as the procedure type.
4. Select Frequency and click Continue.
5. Under Number of eigenvalues requested enter the value 10. Click OK.

Create a mesh
1. Switch to the Mesh module. Make sure the Part Object is set to Tube.
2. Click on the Seed Part Instance tool.
3. Assign a global size of 2.
4. Click the Mesh Part tool to generate the mesh.

Create a job
1. Switch to the Job module. Click the Create Job tool.
2. Enter TubeModal as the job name. Click Continue.
3. Click OK in the Edit Job dialog box.
4. Click the Job Manager tool. Click DataCheck and then click Dismiss.

Finishing up
1. From the main menu bar, select File→Save As.
2. Enter tube.cae for the filename and click OK.
3. Exit Abaqus/CAE.
4. Find the file named abaqus.rpy in your working directory.
5. Rename this file to tube.py.

6. This replay file will be used in later workshops. If you have any difficulty
creating this model you may use the file ws_scr_tube_1_answer.py file
that is provided.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W1.4

Task 1
Delete the tube.cae and tube.jnl files. Use the tube.py file to recreate the model.
Enter the following command:

abaqus cae script=tube.py

Abaqus/CAE will use the replay file to rebuild the model exactly as it was. Exit CAE.

Task 2
Open the tube.py file in a Python-aware text editor (Abaqus PDE or IDLE). Read
through the file and make note of the commands that were created in it as you built the
model.

Questions:
 Which command created the sketch rectangle?
 Which command set the length of the tube?
 Which command set the thickness of the tube?

Task 3
Edit the tube.py file to make some changes to the model. Do the following:

 Change the size of the tube cross section to be 10 by 30 rather than 20 by 20.
 Make the length 200.

Run the revised replay file and note the changes to the model. An answer script is
provided in ws_scr_tube_2_answer.py.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 1 Answers
Creating and Reviewing a Replay File

If you have trouble completing this workshop, the file ws_scr_tube_1_answer.py


contains the answer to the workshop. It is provided for your convenience.

Answers to questions:

 Which command created the sketch rectangle?


o s.rectangle(point1=(-10.0, 10.0), point2=(10.0, -10.0))
rectangle is a method of the sketch object that was created 3 commands
earlier.
 Which command set the length of the tube?
o p.BaseShellExtrude(sketch=s, depth=100.0)
BaseShellExtrude is a method of the part created 2 commands earlier.
 Which command set the thickness of the tube?
o mdb.models['Model-
1'].HomogeneousShellSection(name='ShellSect',
preIntegrate=OFF, material='Steel', thickness=1.0,
poissonDefinition=DEFAULT, thicknessModulus=None,
temperature=GRADIENT, useDensity=OFF,
nodalThicknessField='', integrationRule=SIMPSON,
numIntPts=5)

Answers to Task 3
File ws_scr_tube_2_answer.py contains answers to Task 3. The commands to
change are:

s1.rectangle(point1=(-5.0, 15.0), point2=(5.0, -15.0))


p.BaseShellExtrude(sketch=s1, depth=200.0)

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 2
Running Python

Goals
When you complete this workshop, you will be able to:
● Run Python interactively; from the command line and from Abaqus/CAE.
● Run Python by using scripts.

Introduction & Troubleshooting


Accessing Abaqus Python
A version of Python is delivered with Abaqus. This version contains many extensions that have been
developed to work only with the Abaqus databases. You may access this version at the system shell
command line by typing the command abaqus python like this:

Here, the word abaqus should be the name of the launcher (execution procedure) that is associated with a
particular version of the Abaqus software on your system. Each site may use a slightly different name for
each maintenance release. Typically, the launcher name adheres to a convention that relates to the
maintenance level of the version (for example, abq6121 is usually used for release 6.12-1). If the
appropriate launcher name is not recognized by the system, you will need to fix this.
Troubleshooting Windows Platforms
Windows comes with a command prompt allowing users to run programs from a command-line interface.
The Windows command prompt originated from early versions of MS-DOS and uses the same basic
syntax.
Check to see if the launcher name appears in the directory called:
<your-abaqus-directory>\Commands\
If the launcher name does not exist in this directory as a Windows batch file (.bat extension), then the
name you are using is not appropriate for your installation. If you do not know the appropriate name for
the launcher, speak to the instructor or your systems administrator.
If the name does exist, but it is not recognized by your system, then it is likely that the commands directory
is not defined in the PATH environment variable for your system. If so, set the PATH environment
variable.
The simplest method of setting environment variables is through the System applet in Control Panel.
Depending on your version of Windows, one of the screen shots below should show the lists of user and
system environment variables. To change the value of an existing user variable, select the variable from
the corresponding list and modify the value in the Value field. You use the following steps to create a new
variable:

1. Click the User Variables list to select the type of variable you want to create.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W2.2

2. Replace the Variable field contents with the new variable name that you want to create.

3. Replace the Value field contents with the value that you want to assign to the new variable.

4. Click Set or OK.

The variable list that you selected will list your new variable.

Troubleshooting UNIX Platforms


The easiest way to set a user path environment variable on UNIX is to issue a command like the one below:
set path = ($path /usr/local/bin)
This may be added to your shell configuration file (such as the file called .cshrc for c-shell users or
.kshrc for korn-shell users) to make the launcher name permanently available.
Other Python Versions
Note your Python experience does not have to be limited to the version that is shipped with Abaqus. Users
are free to access other versions of Python that are available free from a variety of sources. There are some
limitations, however. The first limitation is that Abaqus and its affiliates do not provide support for other
versions of the Python language. Also, the Abaqus extensions (the things you will need to work with the
Abaqus database) are only supported for the version of Python that is delivered with the software. For
other versions of Python, you may also need to add the path of the Python executable to your PATH
environment variable. The benefit of using other Python sources is that you may be able to find later
versions of the language and may find that Python is something that you want to use for other applications
besides Abaqus.

Tasks
1. Using the Command-line Interactive Mode. Start Abaqus Python at the command-line. Type any
expression such as: "Hello World!" (include the double quote characters). The string should be
echoed when you hit the return key. Try executing other commands such as 2+2 (no quotes here).
Try the expression sin(pi). Why does the latter not work? Try it again after typing the command

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W2.3

from math import *. Exit the Python session by typing CTRL-Z on UNIX or CTRL-Z,
RETURN on Windows. Type abaqus python -h for more information.

2. Using the Abaqus/CAE Interactive Mode. Create a text file called run_cae.bat in your present
working directory. Include the following line in the new file:
<your-Abaqus-launcher-name> cae
Save the file and start Abaqus/CAE by double-clicking the file icon. This is a convenient means of
quickly launching Abaqus interactive products while assuring that the associated files are written to
your present working directory. You access the Python interactive mode from the command line
interface as shown below.

Now repeat some of the procedures from task 1. What version of Python are you using? Hint: try
looking at the sys.version object. What version of Abaqus are you using? Hint: try calling
uti.getVersion(). In both cases, you will need to “import” the appropriate module like we did in
task 1 for the math module.

3. Using Programs from the Command-line. With a text editor or a Python IDE, write a simple script
file. The file should contain a single print statement such as: print 'Hello World!' (this time
include single quote characters). Store this statement in a file named file1.py. Now, run this file
by passing it to the Python interpreter program on the system shell’s command line (hint: type
something like abaqus python file1.py). Why does a single quote character work for the
string? Is the .py extension required for the file name?

4. Using Programs from Abaqus/CAE. Repeat task 3 from Abaqus/CAE. You may run scripts by using
the File→Run Script pull-down menu, or by using the execfile() method from the command
line interface. Where does the text get displayed? When Python programs are executed as we have
in steps 3 and 4, we say that we are running them as “top level scripts.”

5. Using Unix-style Script Files. Give the file file1.py executable privileges, and “run it” directly as
an executable. Does the first line need to contain anything special for your platform? For UNIX
platforms, add the #! magic line to the top of file1.py. For Windows platforms, depending on
your installation, you may be able to run your script by (i) typing the file1.py at the command line,
(ii) by typing file1 at the command line (i.e. no file extension required), or (iii) by double clicking
the file icon in Windows Explorer. If any of these do not work, we will address remedies in a later
lecture.

If you have trouble completing this workshop, the file ws_scr_hello_answer.py contains the
answer to the workshop. It is provided for your convenience.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 3
Python Types, Operators, and Expressions

Goals
When you complete this workshop, you should be comfortable using basic Python types, operators and
expressions. The material for this workshop has been extracted from Chapter 2 of Learning Python, an
excellent introductory text on the language written by Mark Lutz and David Ascher and published by
O’Reilly & Associates, Inc. More practice examples like these may be found in the text.

Tasks
1. The basics. Experiment interactively with the common type operations that were discussed in this
lecture. To get you started, bring up the Python interactive interpreter, type the expressions below, and
try to explain what's happening in each case:

2 ** 16
2 / 5, 2 / 5.0

"spam" + "eggs"
S = "ham"
"eggs " + S
S * 5
S[:0]
"green %s and %s" % ("eggs", S)

('x',)[0]
('x', 'y')[1]

L = [1,2,3] + [4,5,6]
L, L[:], L[:0], L[-2], L[-2:]
([1,2,3] + [4,5,6])[2:4]
[L[2], L[3]]
L.reverse(); L
L.sort(); L
L.index(4)

{'a':1, 'b':2}['b']
D = {'x':1, 'y':2, 'z':3}
D['w'] = 0
D['x'] + D['w']
D[(1,2,3)] = 4
D.keys(), D.values(), D.has_key((1,2,3))

[[]], ["",[],(),{},None]

2. Indexing and slicing. At the interactive prompt, define a list named L that contains 4 strings or
numbers (e.g., L=[0,1,2,3]). Now, let’s experiment with some boundary cases.

a) What happens when you try to index out-of-bounds (e.g., L[4])?

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W3.2

b) What about slicing out-of-bounds (e.g., L[-1000:100])?

c) Finally, how does Python handle it if you try to extract a sequence in reverse—with the lower
bound greater than the higher bound (e.g., L[3:1])? Hint: try assigning to this slice (L[3:1] =
['?']) and see where the value is put. Do you think this may be the same phenomenon you saw
when slicing out-of-bounds?

3. Indexing, slicing, and ‘del’. Define another list L with 4 items again, and assign an empty list to one of
its offsets (e.g., L[2] = [])—what happens? Then try assigning an empty list to a slice (L[2:3] =
[])—what happens now? Recall that slice assignment deletes the slice and inserts the new value
where it used to be. The del statement can be used to delete offsets, keys, attributes and names: try
using it on your list to delete an item (e.g., del L[0]). What happens if you del an entire slice (del
L[1:])? What happens when you assign a non-sequence to a slice (L[1:2] = 1)?

5. Dictionary keys. Consider the following code fragments:

>>> D = {}
>>> D[1] = 'a'
>>> D[2] = 'b'
We learned that dictionaries aren’t accessed by offsets; what’s going on here? Does the following
shed any light on the subject? (Hint: strings, integers, and tuples share which type category?)

>>> D[(1, 2, 3)] = 'c'


>>> D
{1: 'a', 2: 'b', (1, 2, 3): 'c'}

6. Dictionary indexing. Create a dictionary named D with three entries, for keys "a", "b", and "c".
What happens if you try to index a non-existent key "d" (x = D['d'])? What does Python do if
you try to assign to a non-existent key "d" (e.g., D['d'] = 'spam')? How does this compare to
out-of-bounds assignments and references for lists? Does this sound at all like the rule for variable
names (see lecture 2, slide 46)?

7. Generic operations. Run interactive tests to answer the following questions.


a) What happens when you try to use the + operator on different/mixed types (e.g., string + list, list +
tuple)?
b) Does + work when one of the operands is a dictionary?

c) Does the append method work for both lists and strings? How about the using the keys method
on lists? (Hint: What does append assume about its target?)

d) Finally, what type of object do you get back when you slice or concatenate two lists or two
strings?

8. String indexing. Define a string S of 4 characters: S = "spam". Then type the following expression:
S[0][0][0][0][0]. Any clues about what’s happening this time? (Hint: recall that a string is a
collection of characters, but Python characters are 1-character strings). Does this indexing expression
still work if you apply it to a list like: ['s', 'p', 'a', 'm']? Why?

9. Immutable types. Define a string S of 4 characters again: S = "spam". Write an assignment which
changes the string to "slam", using only slicing and concatenation. Could you perform the same
operation using just indexing and concatenation? How about index assignment?

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 4
Investigating Python Objects

Goals
When you complete this workshop, you should have a basic understanding of Python objects.

Tasks
1. Type, ID, and Value. Investigate the identity, type, and value of different objects. If you want, try
using code similar to the classroom example below. This code may be found in the file called
ws_scr_compare.py): The functionality may be called at the interactive prompt by importing the
module and then calling the function. For example:
>>> import ws_scr_compare
>>> ws_scr_compare.compare(1., 2)

# ws_scr_compare.py
import types
def compare(x, y):
print 'id for x and y =', (id(x), id(y))
if x is y: print 'x and y are the same object'
if x == y: print 'x and y have the same value'
if type(x) is type(y): # in this case, same as using ==
print 'x and y have the same type'
if type(x) is types.IntType:
print 'x is an integer'
else:
print 'x is not an integer'

2. Attributes. Create a list object (e.g. L=[1,2,3]). What attributes are associated with this object?
Hint: try using the dir() function. Which of these attributes are methods? Which are members?
Try the same for a file object.

3. Copies versus Reference. At the Python command line, try some of the examples from class:
#Immutable objects
>>> a = 1; b = a
>>> a = 2
>>> b
1

# Mutable objects
>>> a = [1, 2, 3]; b = a
>>> a[2] = 4
>>> b
[1, 2, 4]

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W4.2
# Empty slice copy
>>> a = b = [1,2,3]
>>> c = a[:]
>>> b.append(4)
>>> a
[1, 2, 3, 4]
>>> c
[1, 2, 3]

#Repetition copy
>>> L0 = [1, 2, 3]
>>> L1 = L0 * 2; L1
[1,2,3,1,2,3]
>>> L2 = [L0] * 2; L2
[[1,2,3],[1,2,3]]
>>> L0[1] = 0
>>> L1
[1, 2, 3, 1, 2, 3]
>>> L2
[[1, 0, 3], [1, 0, 3]]
>>> L2[0][1] = 2
>>> L2
[[1, 2, 3], [1, 2, 3]]

# Explicit copy methods


>>> import copy
>>> a = [[1],[2],[3]]
>>> b = copy.deepcopy(a)
>>> c = copy.copy(a)
>>> a[0][0] = 0
>>> b
[[1], [2], [3]]
>>> c
[[0], [2], [3]]

Can you explain what is happening in each case?

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 5
Defining a Function for a Series Calculation

Goals
When you complete this workshop, you will be able to:
● Use a loop with test operators.
● Create a Python function.
● Work with large integers.

Task 1
Write a function called fib that may be used to print the Fibonacci series up to 10,000. Review the
information in the “Other information” section below if you do not know the definition of the Fibonacci
Series. Put the function in a file called ws_scr_fib.py. Run the script file from within the Python
interpreter and print the series.

Task 2
If you want, try writing the function using two different approaches: with and without recursion (review the
class notes if you need to).

Other information
The Fibonacci series is formed by starting with 0 and 1 and then adding the last two integers to get the
next one: 0, 1, 1, 2, 3, 5, 8, 13, … In general, the series may be defined as follows:
k0 = 0
k1 = 1
kn = kn-1 + kn-2

For example,
0, 1  the series starts like this
0 + 1 = 1  the next term is k0 + k1
So the series is now
0, 1, 1
1 + 1 = 2  the next term is k1 + k2
The series continues...
0, 1, 1, 2
1 + 2 = 3  the next term is k2 + k3
We continue this way to generate the series. For example:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987...

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 5 Answers
Defining a Function for a Series Calculation

Answers
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# OPTION-1: Recursive function to find nth element (slow)
def fib1(n):
if n==0 or n==1:
return 0+n
else:
return fib1(n-1) + fib1(n-2)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# OPTION-2: Utilize fib1() to find series between two integers
def fib2(fromNum, toNum):
n=0
while 1:
fn = fib1(n)
if fn > toNum: break
if fn >= fromNum: print fn,
n = n+1
return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# OPTION-3: Non-recursive function using large integers
def fib3(fromNum, toNum):
a, b = 0L, 1L
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

If you have trouble completing this workshop, the file ws_scr_fib_answer.py contains
the answer to the workshop. It is provided for your convenience.

Note. Integers will not overflow, they will be automatically converted to long integers, so
it is not really necessary to specify a, b = 0L, 1L, the first line of the function could be
a, b = 0, 1

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 6

Modules

Goals
When you complete this workshop, you will be able to:
 Import a module using different techniques.
 Observe some the inherent behavior different module import techniques.

Tasks
1. Import. Start Python at the command line or by launching Abaqus/CAE. In an editor, look at the file
called ws_scr_modules.py. You should see three functions: test1(), test2(), and
test3(). Access this file interactively by using “import.” To do this, at the interactive command
prompt (either in a system shell or at the Abaqus/CAE CLI), type import ws_scr_modules.
Note that the import will fail if you include the .py file extension. Also, this will fail if your
PYTHONPATH setting does not include the directory where the file is stored. How do you know the
present value of PYTHONPATH? Hint: try looking at the sys.path object.

2. dir(). When the import works, look at what gets returned when typing dir() and
dir(ws_scr_modules). You should see two different lists of attributes, one for the interpreter's
namespace, and the other for the namespace of module ws_scr_modules. The three function
names should be included in one of the lists of attributes. Try calling the function called test3() to
see what it does. For example, type ws_scr_modules.test3(ws_scr_modules).

3. from import *. Type from ws_scr_modules import *. Now check dir() and
dir(ws_scr_modules) again. The three function names should be included in both of the lists of
attributes, because the function names have been imported into the interpreter's namespace.

4. Reload. Do not stop the Python interpreter from task 3. After a successful import, you will notice a
file named ws_scr_modules.pyc in the original directory. When was this file created? Try a
few more imports of the same file and notice if the file modification time changes. Edit and save the
file called ws_scr_modules.py. Try another import. You should notice that now the
modification time of the file called ws_scr_modules.pyc has not changed. Try to “reload” the
file by typing reload(ws_scr_modules). Do this several times and note that the modification
time of the .pyc file changes every time. Finally, try moving the file to a different directory and
importing it again. What happens? The import will fail if the new path is not included in
PYTHONPATH.

5. Top level script: Now instead of importing the file, run the file as a top-level script. Continue to work
within the interactive Python mode. One way to run a top-level script is to use the following
command: execfile('ws_scr_modules.py'). What happens when you do this? You
should see that the test function is executed. Why now and not during import? We will answer this
question soon in an upcoming lecture. The answer is related to the namespace that we are in during an
interactive session. The namespace is called __main__.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 7

Creating a Macro and Getting Input Interactively

Goals
When you complete this workshop, you will be able to create and use an Abaqus macro
and requests input interactively using getinputs.

Task 1:
Create a macro that adds three materials, in SI units, to Model-1.

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

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W7.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. Review the file and close it when
completed.
8. Start Abaqus/CAE. Create a new model named Model-2, and run the macro.
Confirm that the materials have been added to Model-1. How can you get the
material from Model-1 to Model-2? What could you do to the macro to create
this material data in the current model?

Note: You will be asked to use the file called abaqusMacros.py again. You
may want to create a backup copy at this time.

Task 2:
Modify the material library macro that you created in Task 1.

1. In an editor, open the file abaqusMacros.py.


2. 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 .
(This will only get the last model if the models are numbered in order).
3. Replace instances of 'Model-1' with the name obtained from the user.
4. Save the file, and exit the editor.
5. Start Abaqus/CAE. Create a new model named Model-2, 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.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 7 Answers

Creating a Macro and Getting Input interactively

Task 1:
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 *

def add_SI_Materials():

import material

m = mdb.models['Model-1'].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['Model-1'].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['Model-1'].Material('Copper')
m.Elastic(table=((110e9,.3),))
m.Plastic(table=((314e6,0),))
m.Density(table=((8970,),))

If you have trouble completing this workshop, the file


ws_scr_abaqusMacros_1_answer.py contains the answer to the workshop. It is
provided for your convenience and must be renamed abaqusMacros.py before it may be
used.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

WA7.2

Task 2:
from abaqus 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 KeyError, 'mdb.models[%r] not found' % (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,),))

If you have trouble completing this workshop, the file


ws_scr_abaqusMacros_2_answer.py contains the answer to the workshop. It is
provided for your convenience. Note that it must be renamed abaqusMacros.py before it
can be used.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 8

Working with the Session Object

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.viewports[name].setValues(...)
session.viewports[name].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('w_beam3d.odb')
vp = session.viewports['Viewport: 1']
vp.setValues(displayedObject=odb)

Before continuing, submit the job called w_beam3d (type abaqus j=w_beam3d from the
system shell command line) in order to generate the output database file (w_beam3d.odb)
noted above.

The object session.drawingArea has members ['height', 'origin', 'width'] that can
be used to make the viewports fit into the current application size.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 8 Answers

Working with the Session Object

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

Answers
from abaqus import *
from abaqusConstants import *
import visualization

def cannedLayout(odbPath):

width, height, margin = 90, 60, 2


data = (
(margin, margin, 'Front'),
(margin*2+width, margin, 'Top'),
(margin, margin*2+height, 'Left'),
(margin*2+width, margin*2+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')

If you have trouble completing this workshop, the file ws_scr_cannedlayout.py


contains the answer to the workshop.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 9

Working with the ODB Object

Goals
When you complete this workshop, you will be able to read data from an Abaqus ODB
file using scripting commands

Tasks
Read some nodal data from an Abaqus ODB file.
1. Open the file viewer_tutorial.odb in Abaqus/Viewer and review the contents.
Close Abaqus/Viewer. Now open the script file odbRead.py in an editor and
view the contents. What do you think this script does?
2. At the command line, run the script. You should see some nodal displacement
information written to the shell.
3. Modify the script. The script is written with a fixed ODB path and node-set
name. Modify the script to accept a command line argument for the ODB path.
Hint: use argv found in the sys module.
4. Modify the script some more. Add some print statements to provide feedback on
all of the node-sets names that are available in the ODB file that is being opened.
Hint: node-set objects are available at the root assembly and also for each
instance.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 9 Answers

Working with the ODB Object


from odbAccess import *
import sys

if len(sys.argv) != 2:
print 'Error, you must supply ODB name at command line'
sys.exit(1)

odbPath = sys.argv[1]

try:
odb = openOdb(path=odbPath)
except IOError, value:
print 'Error:', value

print 3*'\n'
print 'Available steps = ',odb.steps.keys()

print '\n',72*'*','\nnsets in root assembly = ',odb.rootAssembly.nodeSets.keys()


for instance in odb.rootAssembly.instances.values():
print '***\nInstance = ',instance.name
for nodeSet in instance.nodeSets.values():
print ' nset = ',nodeSet.name
print 72*'*','\n'

lastFrame = odb.steps[odb.steps.keys()[-1]].frame[-1]
displacement = lastFrame.fieldOutputs['U']
nsetNames = odb.rootAssembly.instances['PART-1-1'].nodeSets.keys()
center = odb.rootAssembly.instances['PART-1-1'].nodeSets[nsetNames[4]]
centerDisplacement = displacement.getSubset(region=center)

for v in centerDisplacement.values:
print 'Position = ', v.position,'Type = ',v.type
print 'Node label = ', v.nodeLabel
print 'X displacement = ', v.data[0]
print 'Y displacement = ', v.data[1]
print 'Displacement magnitude =', v.magnitude

odb.close()

The file ws_scr_odbObject_answer.py contains the answer to the workshop. It is


provided for your convenience.
© Dassault Systèmes, 2012 Introduction to Abaqus Scripting
tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 10

Linear Superposition of Results

Goals
When you complete this workshop, you will be able to:
 Combine results from 2 separate fields on the ODB to create a new temporary
field.
 Display the new field in Abaqus/Viewer.

Task
The file w_beam3d.odb 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:
 Open the file w_beam3d.odb. Use the command session.openOdb.
 Assign the ODB object to the variable odb.
 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.)

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W10.2

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

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 10 Answers

Linear Superposition of Results

Task
An ODB file is provided named w_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 = session.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,))

If you have trouble completing this workshop, the file ws_scr_addfields.py contains
the answers to the workshop. It is provided for your convenience.

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 11

Creating kernel and GUI scripts

Goals
When you complete this workshop, you will be able to transform a replay file into a kernel script and build
a GUI dialog using RSG to run the kernel script. It is recommended you follow the RSG Dialog Builder
tour before starting this workshop.

Tasks
Abaqus/CAE records the commands from the user interface in the replay file. Thus, this file is a good
starting point in creating a kernel script.

1. Start a new session of Abaqus/CAE .


2. Create a 2D Planar part named Plate and sketch a rectangle from 0, 0 to 30, 20. Inscribe
a circle with its center at 15, 10 and a radius of 5.
3. Exit Abaqus/CAE without saving the model.
4. In your working directory, rename your session replay file (likely named abaqus.rpy) to
createPlateModule.py.
5. Edit createPlateModule.py with any text editor. Delete all the lines up to but not including
the command to create a sketch (ConstrainedSketch).
6. Create a function named createPlateFunction with the remaining commands. This
function should accept four arguments: partName, width, height and radius.
7. Change the values of point2 of the command rectangle to use the variables width and
height.
8. Change the values of center of the command CircleByCenterPerimeter to be
width/2 and height/2.
9. Change the values of point1 of the command CircleByCenterPerimeter to be
width/2+radius and height/2.
10. Change every reference to the string 'Plate' to the variable partName.
11. Add the following lines to the top of the module:
from abaqus import *
from abaqusConstants import *

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W11.2

12. Your module should look like:


from abaqus import *
from abaqusConstants import *
def createPlateFunction(partName, width, height, radius):
s = mdb.models['Model-1'].ConstrainedSketch(
name='__profile__',
sheetSize=200.0)
g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
s.setPrimaryObject(option=STANDALONE)
s.rectangle(
point1=(0.0, 0.0),
point2=(width, height))
s.CircleByCenterPerimeter(
center=(width/2.0, height/2.0),
point1=(width/2.0+radius, height/2.0))
p = mdb.models['Model-1'].Part(
name=partName,
dimensionality=TWO_D_PLANAR,
type=DEFORMABLE_BODY)
p = mdb.models['Model-1'].parts[partName]
p.BaseShell(sketch=s)
s.unsetPrimaryObject()
session.viewports['Viewport: 1'].setValues(displayedObject=p)
del mdb.models['Model-1'].sketches['__profile__']

13. Save createPlateModule.py.


14. Start a new session of Abaqus/CAE and launch the RSG Dialog Builder
(Plug-ins→Abaqus→ RSG Dialog Builder).
15. In the first tab (GUI), click Show Dialog and change the title to Create Plate.

16. Add a group box (click ) with the title Parameters.

17. Add a text field (click ). The label text should be Name: and the keyword value partName.
18. Add another text field. The label text should be Width (w):, the type should be Float and the
keyword width.
19. Add another text field. The label text should be Height (h):, the type should be Float and the
keyword height.
20. Add another text field. The label text should be Radius (r):, the type should be Float and the
keyword radius. Your dialog box should look similar to the following:

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W11.3

21. Add a second group box (click ) with the title Diagram. In this group box, add an icon (click

) and select the file createPlate.png (click to select the file). If necessary, use the

arrows ( ) to position the Diagram group box above the Parameters group
box.
22. Your dialog box should look similar to the following:

23. Your GUI layout should appear as follows:

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W11.4

24. Change to the second tab (Kernel). Click to load a kernel module and select
createPlateModule.py. Select createPlateFunction in the drop-down function menu.

25. Change to the GUI tabbed page and click to save your plug-in as a Standard plug-in.
Enter createPlate as the directory name and Create Plate… as the menu button name.
Note to where the plug-in files are saved. It should be under your HOME directory, in a folder
named abaqus_plugins.
26. Restart Abaqus/CAE and test the plug-in (Plug-ins→Create Plate).

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

Workshop 12

Setting Abaqus Defaults

Goals
When you complete this workshop, you will be able to use the Abaqus environment file to customize some
default settings of Abaqus/CAE. Before continuing, submit the job called w_new_beam3d (type
abaqus j=w_new_beam3d from the system shell command line) in order to generate the output
database file w_new_beam3d.odb.

Tasks
Use the file called ws_scr_abaqus_v6_general.py to customize Abaqus.
1. Using a text editor, open the two files called ws_scr_abaqus_v6_general.py and
ws_scr_material_library.py. The environment file does many things to customize
Abaqus. Make a list of the things that you think it does. What is the purpose of the material file?
How does the environment file use it?
2. Copy the file ws_scr_abaqus_v6_general.py to abaqus_v6.env. Launch
Abaqus/CAE from the same directory. To verify that the environment file was used, you should
see many variable names written to the shell window and to the Abaqus/CAE message area. In the
message area, you should also see the message: "The model 'my_material' has been
created". If you do not see these things, Abaqus is not using your new environment file.
3. Open the ODB file called w_new_beam3d.odb. Plot a contour of any variable. How are the
contour settings different from the normal defaults?
4. Go to the Property module and look at the materials that are available. Now switch to the model
called my_material and review the materials.
5. Close Abaqus/CAE. At the system shell command line, submit the job called w_beam3d (type
abaqus j=w_beam3d). Can you explain the text that is written to the shell window? Look at
the .log file for the job. You should see some non-standard information written to the end of
this file. Now look at the file called newflat.inp. Where did this file come from and how
does it compare with w_beam3d.inp?

If you need to obtain Abaqus release information:

import odbAccess
odbAccess.majorVersion
odbAccess.minorVersion

or, in Abaqus/CAE:

import abaqus
abaqus.majorVersion
abaqus.minorVersion

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W12.2
#################################################################
# from the file called ws_scr_abaqus_v6_general.py
#################################################################

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def onCaeStartup():

# Compatibility issues
backwardCompatibility.setValues(includeDeprecated=OFF)

# Graphics preferences
session.graphicsOptions.setValues(displayLists=ON, dragMode=AS_IS,
autoFitAfterRotate=ON)

# Print preferences
session.printOptions.setValues(vpDecorations=OFF, vpBackground=OFF,
rendition=COLOR, printCommand='lpr')
session.psOptions.setValues(date=OFF)

# Visualization preferences
def setVisPreferences(module, userData):
from visualization import SHADED, EXTERIOR, CONTINUOUS
session.defaultOdbDisplay.commonOptions.setValues(
renderStyle=SHADED, visibleEdges=EXTERIOR)
session.defaultOdbDisplay.contourOptions.setValues(
contourStyle=CONTINUOUS)
addImportCallback('visualization', setVisPreferences)

# Material properties - read them from a file


execfile('ws_scr_material_library.py')

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def onJobStartup():
print 'The job is starting'

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def onJobCompletion():
for glob in globals().keys():
if glob != '__builtins__':
print '%s = %s' % (glob, eval(glob))
import os, shutil
flatFilePath = os.path.join(scrdir,"%s_f.inp" % id)
print 'The present value of os.getcwd() is ', os.getcwd()
if os.path.exists(flatFilePath):
newFlatFilePath = os.path.join(savedir, 'newflat.inp')
print 'newFlatFilePath = ',newFlatFilePath
print "A copy of the flat file has been written."
shutil.copyfile(flatFilePath, newFlatFilePath)

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting


tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@gmail.com tbalaji040@
For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by Balaji Thirupathi. For personal use by

W12.3

#################################################################
# ws_scr_abaqus_v6_general.py (cont.)
#################################################################

# assign some variables


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
memory = 50
explicit_precision=[SINGLE_PRECISION, DOUBLE_PRECISION][0]
ask_delete=ON
cae_no_parts_input_file=ON
auto_calculate=ON
odb_output_by_default=OFF
printed_output=OFF
print_flattened_file=ON

© Dassault Systèmes, 2012 Introduction to Abaqus Scripting

Vous aimerez peut-être aussi