Abaqus_FEA_Scripting

Abaqus uses python as its native macro/scripting language, which makes it easy to develop powerful tools that utilize the robustness and simplicity of the python programming language.
This file is generated using an ipython notebook, which can be easily installed using Anaconda (see the installation section for more detail)

Content Overview
General Abaqus Overview
Abaqus-CAE python console
Beam Example
Beam Example Results
Beam Example Code


Also, I use ! to execute console or terminal commands directly in the notebook here. So for example, in windows we can run dir on windows or ls on linux to show the directory contents

In [2]:
!dir
 Volume in drive C has no label.
 Volume Serial Number is 18C2-EE86

 Directory of C:\Users\ngordon\VirtualBox VMs\mint-cin\share\nagordon.github.io\content

04/02/2015  02:58 PM              .
04/02/2015  02:58 PM              ..
04/02/2015  02:27 PM              .ipynb_checkpoints
04/02/2015  02:58 PM            36,294 Abaqus_FEA_Scripting_with_python.ipynb
04/02/2015  01:35 PM               241 Abaqus_FEA_Scripting_with_python.ipynb-meta
04/02/2015  02:21 PM              code
04/02/2015  02:05 PM             4,369 How I built my blog.md
04/02/2015  02:08 PM              images
03/14/2015  08:45 PM             2,522 Its-About-Time.md
04/02/2015  02:08 PM              pages
03/14/2015  08:45 PM             6,934 Team Fortress 2 Server Install for Dummies.md
               5 File(s)         50,360 bytes
               6 Dir(s)  34,882,461,696 bytes free

General_Abaqus_Overview

Installation

Operating System

I am using windows 7 operating system for work with Abaqus, and I use Linux Mint for generating the blog page

Python

To install a minimal python, I recommend miniconda as a package maanger. Once miniconda or is installed, install these packages by running these commands in a windows console and following the prompts. Packages that a needed to replicate my results are included in the article when they are needed.

conda install numpy  
conda install matplotlib=1.4.3
conda install pandas

For developers, I'd recommend a more complete python installation that includes an IDE (Integrated Development Environment), like spyder.

Abaqus

A commercial license is prohibitvley expensing, but for students out there a nearly full functioning student edition is available here, but is limited by node count and no user subroutines.


Some of the abaqus file types

files generated by created and analyzing a model

  • rpy - replay file , all modeling operation commands executed during a session, are saved in this file
  • cae - model database, contains models and analysis jobs
  • jnl - journal python file, all commands necessary to recreate the most current save model database
  • rec - recover file contains commands to replicate the version of the model database in memory
    ### files created when a job is submitted
  • inp - abaqus config file that is created when a job is submitted. contains all the information necessary to run a analysis
  • odb - output database containing results from completed simulation. Use the step module output request manager to choose variables are saved at what rate. viewed in the visualization module
  • lck - file that protects the odb file when it is current being written to
  • res - used to continue an anaylsis that stopped before it was complete. use the step module to specify which analysis steps should write restart information
  • dat - printed output from the anaylsis input file processor, as well as printed output of selected results written during the analysis.
  • msg - contains diagnostic or informative messages about the progress of the solution. Control the output in the step module
  • fil - contains selected results from the analysis in a neutral format. that can we read/written for third-party post processing
  • *rpt - text file generated from probe data for user specific user requested information
  • ods - scratch output database file
  • mdb - database of the model
  • sim - binary file
  • sta - summary of job info
  • lck - a file that indicates that the odb file is open and cannot be edited if opened by another user

Outputs

  • defaults set in the environment file
  • typical outputs
    • E - strain
    • PE - plastic strain
    • U - displacements and rotations
    • RF - reaction forces
    • CF - concentrated (applied) forces and moments
    • CSTRESS - contact stresses
    • CDISP - contact displacements
    • see Abaqus Scripting User's Guide 5.2 for more info accessing the database

Abaqus Scripting User's Guide - 5.2.2

field output

  • typically requested for the entire model, often only at selected elements
  • used for creating contour, deformed shape, and symbol plots
  • Can be used as a source for x-y plots, but history is better
  • intended for infrequent requests for large portions of model data, such as 3d mesh contour plots
  • can specify output frequency or time intervals
import odbAccess
session.odbs[name].steps[name].frames[i].fieldOutputs[name]
# or 
sdat=session.odbs['customBeamExample/customBeamExample.odb'].steps['beamLoad'].frames[-1].fieldOutputs['S']
integrationPointData = sdat.getSubset(position=INTEGRATION_POINT)
invariantsData = sdat.validInvariants

Abaqus Scripting User's Guide - 9.3.2
Field output is intended for infrequent requests for a large portion of the model and can be used to generate contour plots, animations, symbol plots, and displaced shape plots in the Visualization module of Abaqus/CAE. You can also use field output to generate an X–Y data plot. Only complete sets of basic variables (for example, all the stress or strain components) can be requested as field output. Field output is composed of a “cloud of data values” (e.g., stress tensors at each integration point for all elements). Each data value has a location, type, and value. You use the regions defined in the model data, such as an element set, to access subsets of the field output data. Figure 9–3 shows the field output data object model within an output database.

history output

  • requested for a small subset of the model
  • typically requested at every increment during the anaylsis
  • used to generate xy plots by step and time
  • example - the principal stress at a single node at the root of the beam
import odbAccess
session.odbs[name].steps[name].historyRegions[name]

Abaqus Scripting User's Guide - 9.3.2
History output is output defined for a single point or for values calculated for a portion of the model as a whole, such as energy. History output is intended for relatively frequent output requests for small portions of the model and can be displayed in the form of X–Y data plots in the Visualization module of Abaqus/CAE. Individual variables (such as a particular stress component) can be requested. Depending on the type of output expected, a HistoryRegion object can be defined for one of the following:

  • a node
  • an integration point
  • a region
  • the whole model

The output from all history requests that relate to a particular point or region is then collected in one HistoryRegion object. Figure 9–4 shows the history output data object model within an output database. In contrast to field output, which is associated with a frame, history output is associated with a step.


Basic Checklist for generating an Abaqus simulation

  1. Parts
  2. Materials
  3. Sections
  4. Section Assingments
  5. Assembly(instances)
  6. Steps (after Initial)
  7. BCs (Boundary Conditions)
  8. Loads
  9. Mesh
  10. Jobs

Using abaqus from the command line

abaqus  
abq6132se  
abaqus doc  
abaqus pde      # launches only PDE (python development environment) for abaqus  
abaqus cae -pde # launches PDE and abaqus cae  
abaqus cae      # launches abaqus cae  
abaqus viewer   # launhces abaqus viewer

Execute an existing script or open a file

abaqus python odb_to_txt.py test1.odb       # runs a abaqus python script with input 'test1.odb'
abaqus cae script=myscript.py               # launches cae and runs script
abaqus cae database=filename.cae            # opens an odb file in cae
abaqus viewer script=myscript.py            # launches viewer and executes script
abaqus viewer database=cantilever           # opens a odb file in the viewer
abaqus cae noGUI=myscript.py                # launches cae and runs script
abaqus viewer noGUI=myscript.py             # launches viewer and executes script
abaqus job=my_sample_job interactive        # executes *.inp file
abaqus job=my_sample_job cpus=8 interactive # executes *.inp file and utilizes 8 cpu cores

Executing an abaqus python script passing in variables

abaqus cae noGUI=myscript.py -- variable1 variable2

Fetch demos

abaqus fetch job=beamExample   # fetches the beamExample.py file
abaqus fetch job=gsi_frame_caemodel.py     
abaqus cae script=gsi_frame_caemodel.py

Common Abaqus/CAE User interface activities

Accessing the help documentation

  • Help -> Search and Browse Guides
  • or type 'abaqus doc' in console

execute a abaqus/python script

  • File -> Run Script

record a abaqus/python macro

  • File -> Macro Manager
  • files stored in users home directory in abaqusMacros.py

edit and execute a abaqus python script in using the provided python development environment (PDE)

  • File -> Abaqus PDE...

plugins

abaqus_plugins\reportGenerator\htmlReportGeneratorForm.pyc

Change font of legend

Click on "Viewport" in the top Menu Bar Select "Viewport Annotation Options" Click on the "Triad" tab Click on the "Set Font..." button to adjust the font You can even change all 3 at once by checking on the "Legend", "Title Block", or "State Block" check boxes under the "Apply To" heading


Abaqus/Python Scripting

Abaqus specific Python modules imports

  • Module - Abaqus/CAE functionality
  • assembly - The Assembly module
  • datum - The Datum toolset
  • interaction - The Interaction module
  • job - The Job module
  • load - The Load module
  • material - Materials in the Property module
  • mesh - The Mesh module
  • part - The Part module
  • partition - The Partition toolset
  • section - Sections in the Property module
  • sketch - The Sketch module
  • step - The Step module
  • visualization - The Visualization module
  • xyPlot - The X–Y toolset

Examples

Abaqus-CAE_python_console

We can run these commands from the abaqus/CAE python console at the bottom of the screen

print("Hello World!")

This python snippet will show a user dialog box asking for a number and it will calculate the square root of it

from abaqus import getInput
from math import sqrt
number = float(getInput('Enter a number:'))
print sqrt(number)

VOILA!

We can see that the version of python that abaqus uses is older, but has most of the modules we need

Abaqus python

In [3]:
!python -c "import sys; print(sys.version)"
2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Jul  2 2014, 15:12:11) [MSC v.1500 64 bit (AMD64)]

My system python

In [4]:
!abaqus python -c "import sys; print(sys.version)"
2.6.2 for Abaqus 6.13-2 (r262:71600, Jul 27 2013, 13:44:36) [MSC v.1600 64 bit (AMD64)]

Beam_Example

print the current working directory to ensure that all the output will be in one file

In [8]:
pwd
Out[8]:
u'C:\\Users\\ngordon\\VirtualBox VMs\\mint-cin\\share\\nagordon.github.io\\content'

Use 'fetch' to retrieve an abaqus example python script. The code can be found here

In [6]:
!abaqus fetch job=beamExample
Abaqus FETCH job beamExample
  fetching: beamExample.py

To execute the beamExample script we just fetched, run

In [9]:
!abaqus cae noGUI=beamExample.py
Abaqus JOB beam_tutorial
Abaqus Student Edition 6.13-2
Begin Analysis Input File Processor
4/2/2015 2:09:48 PM
Run pre.exe
4/2/2015 2:09:49 PM
End Analysis Input File Processor
Begin Abaqus/Standard Analysis
4/2/2015 2:09:49 PM
Run standard.exe
4/2/2015 2:09:50 PM
End Abaqus/Standard Analysis
Abaqus JOB beam_tutorial COMPLETED

Excellent, now we have some output. Let have a look at what we have

Beam_Example_Results

In [13]:
!abaqus cae noGUI=abaqus_read_odb.py

Now lets grab some images from the odb file and see how the simulation turned out

We can load the images using markdown, such as

  

which is the method I prefer because if I want to use this notebook, I can copy the entire notebook folder with all the images and not have to worry about obscure image locations that pelican requirwes otherwise.

or for the blog post using pelican abaqus_python_console2

![beam_tutorial_Iso]({filename}/notebooks/Abaqus_FEA_Scripting_with_python/beam_tutorial_Iso.png)

Here is an image of the undeformed plot

And here is an image for $U_{1}$ for the last frame (indicated by -1, which in python selects the last list item)

And here is an image for $\sigma_{11}$ for the last frame

We can also plot directly in Abaqus. This is a plot of the strain energy of the entire model.

We can also easily create aniamtions directly from abaqus. Using a python module, we convert the avi to an animated gif

In [11]:
from moviepy.editor import VideoFileClip
import glob, os
avinames=glob.glob('*.avi')
for aviname in avinames:
    VideoFileClip(aviname).write_gif(os.path.splitext(aviname)[0]+'.gif')
    # os.remove(aviname)   ### if you want to remove the avi file

The gif file format is really handy. We can simple load the gif file just like we loaded png to show the animations


$U{1}$ over all frames

$\sigma_{11}$ over all frames

Plot of the strain energy

This is handy, but the real problem at hand is accessiblity. Abaqus is good software, but expense. Some short-term goals I have is to look into some open-source pacakges that I can run some more complex models in. GetFEM++ looks fun and I will be trying it out soon, so stay tuned!

Beam_Example_Code

All the code can be downloaded here
abaqus_read_odb
beamExample

To view the file we can use an ipython magic function prefixed with %

%load code/beamExample.py
In [ ]:
# %load code.beamExample.py
"""
beamExample.py

Reproduce the cantilever beam example from the
Appendix of the Getting Started with
Abaqus: Interactive Edition Manual.
"""

from abaqus import *
from abaqusConstants import *
backwardCompatibility.setValues(includeDeprecated=True,
                                reportDeprecated=False)

# Create a model.

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

# Create a new viewport in which to display the model
# and the results of the analysis.

myViewport = session.Viewport(name='Cantilever Beam Example',
    origin=(20, 20), width=150, height=120)
    
#-----------------------------------------------------

import part

# Create a sketch for the base feature.

mySketch = myModel.ConstrainedSketch(name='beamProfile',
    sheetSize=250.)

# Create the rectangle.

mySketch.rectangle(point1=(-100,10), point2=(100,-10))

# Create a three-dimensional, deformable part.

myBeam = myModel.Part(name='Beam', dimensionality=THREE_D,
    type=DEFORMABLE_BODY)

# Create the part's base feature by extruding the sketch 
# through a distance of 25.0.

myBeam.BaseSolidExtrude(sketch=mySketch, depth=25.0)

#-----------------------------------------------------

import material

# Create a material.

mySteel = myModel.Material(name='Steel')

# Create the elastic properties: youngsModulus is 209.E3
# and poissonsRatio is 0.3

elasticProperties = (209.E3, 0.3)
mySteel.Elastic(table=(elasticProperties, ) )

#-------------------------------------------------------

import section

# Create the solid section.

mySection = myModel.HomogeneousSolidSection(name='beamSection',
    material='Steel', thickness=1.0)

# Assign the section to the region. The region refers 
# to the single cell in this model.

region = (myBeam.cells,)
myBeam.SectionAssignment(region=region,
    sectionName='beamSection')

#-------------------------------------------------------

import assembly

# Create a part instance.

myAssembly = myModel.rootAssembly
myInstance = myAssembly.Instance(name='beamInstance',
    part=myBeam, dependent=OFF)

#-------------------------------------------------------

import step

# Create a step. The time period of the static step is 1.0, 
# and the initial incrementation is 0.1; the step is created
# after the initial step. 

myModel.StaticStep(name='beamLoad', previous='Initial',
    timePeriod=1.0, initialInc=0.1,
    description='Load the top of the beam.')

#-------------------------------------------------------

import load

# Find the end face using coordinates.

endFaceCenter = (-100,0,12.5)
endFace = myInstance.faces.findAt((endFaceCenter,) )

# Create a boundary condition that encastres one end
# of the beam.

endRegion = (endFace,)
myModel.EncastreBC(name='Fixed',createStepName='beamLoad',
    region=endRegion)

# Find the top face using coordinates.

topFaceCenter = (0,10,12.5)
topFace = myInstance.faces.findAt((topFaceCenter,) )

# Create a pressure load on the top face of the beam.

topSurface = ((topFace, SIDE1), )
myModel.Pressure(name='Pressure', createStepName='beamLoad',
    region=topSurface, magnitude=0.5)

#-------------------------------------------------------

import mesh

# Assign an element type to the part instance.

region = (myInstance.cells,)
elemType = mesh.ElemType(elemCode=C3D8I, elemLibrary=STANDARD)
myAssembly.setElementType(regions=region, elemTypes=(elemType,))

# Seed the part instance.

myAssembly.seedPartInstance(regions=(myInstance,), size=10.0)

# Mesh the part instance.

myAssembly.generateMesh(regions=(myInstance,))

# Display the meshed beam.

myViewport.assemblyDisplay.setValues(mesh=ON)
myViewport.assemblyDisplay.meshOptions.setValues(meshTechnique=ON)
myViewport.setValues(displayedObject=myAssembly)

#-------------------------------------------------------

import job

# Create an analysis job for the model and submit it.

jobName = 'beam_tutorial'
myJob = mdb.Job(name=jobName, model='Beam',
    description='Cantilever beam tutorial')

# Wait for the job to complete.

myJob.submit()
myJob.waitForCompletion()

#-------------------------------------------------------

import visualization

# Open the output database and display a
# default contour plot.

myOdb = visualization.openOdb(path=jobName + '.odb')
myViewport.setValues(displayedObject=myOdb)
myViewport.odbDisplay.display.setValues(plotState=CONTOURS_ON_DEF)

myViewport.odbDisplay.commonOptions.setValues(renderStyle=FILLED)
%load abaqus_read_odb.py
In [ ]:
# %load code/abaqus_read_odb.py
"""
Neal Gordon
Abaqus Scripting
http://nagordon.github.io/
2015-04-2

"""

# Import abaqus modules
from abaqus import session
import visualization
import xyPlot
from abaqusConstants import PNG, AVI, CONTOURS_ON_DEF, \
                            INTEGRATION_POINT, COMPONENT, OFF, ON, \
                            FEATURE, DISCRETE, CONTINUOUS, ALL_FRAMES, \
                            TIME_HISTORY, UNLIMITED, UNDEFORMED, \
                            SCALE_FACTOR, NODAL, LARGE

# load odb file
myViewport = session.Viewport(name='myViewport', origin=(10, 10), width=300, height=200)
myOdb = visualization.openOdb(path='beam_tutorial.odb')
myViewport.setValues(displayedObject=myOdb)

# set viewport settings
v = 'Iso'
myViewport.view.setValues(session.views[v])
myViewport.maximize()
myViewport.view.fitView()
myViewport.odbDisplay.basicOptions.setValues(coordSystemDisplay=OFF, translucencySort=ON)
myViewport.odbDisplay.commonOptions.setValues(visibleEdges=FEATURE)  # NONE
myViewport.odbDisplay.contourOptions.setValues(contourStyle=CONTINUOUS) # DISCRETE CONTINUOUS
#myViewport.odbDisplay.contourOptions.setValues(showMinLocation=ON,showMaxLocation=ON)
#myViewport.odbDisplay.contourOptions.setValues(numIntervals=6)
myViewport.viewportAnnotationOptions.setValues(triad=OFF, title=OFF, state=ON,  compass=OFF,
                                              legend=ON, legendPosition=(75, 95), legendBox=OFF,
                                              legendFont='-*-verdana-medium-r-normal-*-*-120-*-*-p-*-*-*',
                                              statePosition=(1, 15),
                                              titleFont='-*-verdana-medium-r-normal-*-*-120-*-*-p-*-*-*',
                                              stateFont='-*-verdana-medium-r-normal-*-*-120-*-*-p-*-*-*')


# saving undeformed image
myViewport.odbDisplay.display.setValues(plotState=(UNDEFORMED, ))
path_filename = '%s_%s' % (myOdb.name.replace('.odb',''),v)
try:
    session.printToFile(path_filename, PNG, (myViewport,))
    print('saving %s' % path_filename)
except:
    pass

# save stress plots
v = 'Iso' ; o = 'S' ; c = 'S11' ; s = 0 ; f = -1
myViewport.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF, ))
myViewport.odbDisplay.setFrame(step=s, frame=f)

myViewport.odbDisplay.setPrimaryVariable(variableLabel=o,outputPosition=INTEGRATION_POINT,refinement=(COMPONENT, c), )
path_filename = '%s_step-%s_%s_%s_%s' % (myOdb.name.replace('.odb',''),s,o,c,v)
try:
    myViewport.view.fitView()
    session.printToFile(path_filename+'.png', PNG, (myViewport,))
    print('saving %s' % path_filename)
    
    myViewport.view.fitView()
    session.animationController.setValues(animationType=TIME_HISTORY, viewports=(myViewport.name, ))    # SCALE_FACTOR   TIME_HISTORY                              
    session.animationController.play(duration=UNLIMITED)
    session.animationController.animationOptions.setValues(frameRate=15)         
    session.writeImageAnimation(fileName=path_filename+'.avi', format=AVI, canvasObjects=(myViewport,))
    print('saving %s' % path_filename+'.avi')    
except:
    pass
       
# save displacement plots
v = 'Iso' ; o = 'U' ; c = 'U1' ; s = 0 ; f = -1
myViewport.odbDisplay.setPrimaryVariable(variableLabel=o,outputPosition=NODAL,refinement=(COMPONENT, c), )

path_filename = '%s_step-%s_%s_%s_%s' % (myOdb.name.replace('.odb',''),s,o,c,v)
try:
    myViewport.view.fitView()
    session.printToFile(path_filename+'.png', PNG, (myViewport,))
    print('saved %s' % path_filename+'.png')
    
    myViewport.view.fitView()
    session.animationController.setValues(animationType=TIME_HISTORY, viewports=(myViewport.name, ))    # SCALE_FACTOR   TIME_HISTORY                              
    session.animationController.play(duration=UNLIMITED)
    session.animationController.animationOptions.setValues(frameRate=15)       
    session.writeImageAnimation(fileName=path_filename+'.avi', format=AVI, canvasObjects=(session.viewports[myViewport.name], ))
    print('saved %s' % path_filename+'.avi')    
except:
    pass

# PLotting 
xyp = session.XYPlot(name='XYPlot-1')
## can be run multiple times but the line >>>session.xyPlots['XYPlot-1'] , can only be run once >>>ession.XYPlot('XYPlot-1')
chartName = xyp.charts.keys()[0]
chart = xyp.charts[chartName]
chart.legend.setValues(show=False)
chart.legend.titleStyle.setValues(font='-*-verdana-medium-r-normal-*-*-240-*-*-p-*-*-*')
chart.gridArea.style.setValues(fill=False)
xyp.title.style.setValues(font='-*-arial-medium-r-normal-*-*-240-*-*-p-*-*-*')
        
x = 'Strain energy: ALLSE for Whole Model'
sName = myOdb.steps.keys()[s]
xy1 = xyPlot.XYDataFromHistory(odb=myOdb, outputVariableName=x, steps=(sName, ), )
c1 = session.Curve(xyData=xy1)
chart.setValues(curvesToPlot=(c1, ), )
myViewport.setValues(displayedObject=xyp)
chartName = xyp.charts.keys()[0]
chart = xyp.charts[chartName]
path_filename = '%s_Xplot_step-%s_x-%s' % \
    (myOdb.name.replace('.odb',''), sName, x.split(':')[1].split(' ')[1])
try:
    myViewport.view.fitView()
    session.printToFile(path_filename+'.png', PNG, (myViewport,))

    myViewport.view.fitView()
    session.animationController.setValues(animationType=TIME_HISTORY, viewports=(myViewport.name, ))    # SCALE_FACTOR   TIME_HISTORY                              
    session.animationController.play(duration=UNLIMITED)
    session.animationController.animationOptions.setValues(xyShowSymbol=True, xySymbolSize=LARGE)
    session.writeImageAnimation(fileName=path_filename+'.avi', format=AVI, canvasObjects=(session.viewports[myViewport.name], ))
    print('saved %s' % path_filename+'.avi')
except:
    pass

top


Comments

comments powered by Disqus