mechpy

neal gordon (nealagordon at gmail.com)


Feb 20, 2017


a mechanical engineering toolbox

Table of contents

mechpy
      Introduction
      Modules
      Installation
Python
      Introductory Tutorials
      Engineering Tutorials
      Advanced Tutorials
            Virtual Environments
            Converting an ipython notebook to an html document
            Running jupyter notebook in windows
      Excel and Python - They can be friends
mechpy modules documentation
      composites
      design
      fem
      math
      statics
      units
      catia
      abaqus and abaqus_report
            abaqus documentation
References
      Links
            Python Online Engineering Classes
            Python Engineering Books
            Python Engineering Libraries


mechpy

Introduction

Mechpy was created for few reasons.

There are many different tools available to engineers. Hand-calculations, spreadsheets, and code are all great ways to perform calculations or visualize data or concepts. MATLAB is the defacto tool to solve many engineering calculations, but is just too expensive to be a practical tool for many of us. Octave, Scilab, or Freelab are great alternatives, but is limited in scope to calculation. I began using python for calculations and visualizations and have found it to be a very powerful tool with many existing modules for mathematics and plotting, in addition to the thousands of other libraries for general computing.

To get the source code check out the github project page


Modules

composites. (composites) specialized code to analyze composite plates using classical laminated plate theory https://nagordon.github.io/mechpy/composites.html

design. (design) shear-bending diagrams, assisting hand calculations for stress https://nagordon.github.io/mechpy/design.html

solids. \eqref{sec:solids} https://nagordon.github.io/mechpy/solids.html
https://nagordon.github.io/mechpy/testing.html

fem. (fem) example code for computing finite element models for analysis and education https://nagordon.github.io/mechpy/fem.html

math. (math) various math tools for processing engineering systems https://nagordon.github.io/mechpy/math.html

statics. (statics) code for assisting and checking hand calculations https://nagordon.github.io/mechpy/statics.html

units. (units) unit conversion https://nagordon.github.io/mechpy/units.html

catia. (catia) API code to automate cad in catia

abaqus. (abaqus and abaqus_report) abaqus api interface written in python for automating abaqus fem simulations and reporting.

dynamics. \eqref{sec:dynamics} https://nagordon.github.io/mechpy/dynamics.html

Installation

The easiest way to get mechpy is to download it directly from the mechpy github repository

If you are comfortable using git feel free to clone mechpy with git

git clone https://github.com/nagordon/mechpy.git

Navigate to the setup.py file and run

python setup.py install

this should add the mechpy module to the python path


Python

Introductory Tutorials

For a introduction to python for engineering computing, this is a slideshow for Getting Started with Python in Engineering
https://nagordon.github.io/mechpy/Getting_Started_with_Python_in_Engineering.deckslides.html

or if you prefer a webpage, follow the link below
https://nagordon.github.io/mechpy/Getting_Started_with_Python_in_Engineering.webpage.html

Engineering Tutorials

Here you will find engineering tutorials on popular activities in engineering computing. The notebooks for these can also be found in mechpy/tutorials

Composite_Materials_Quasi-Isotropic_Study.html
Composite_Plate_Mechanics_with_Python_Example.html
Composite_Plate_Mechanics_with_Python_Theory.html
composites.html
Curve_fitting_and_Optimization_with_python.html
design.html
fem.html
math.html
plotting.html
solids.html
Solving_Differential_Equations_with_Python_mechanical_vibrations.html
statics.html
sundries.html
testing.html
units.html

Advanced Tutorials

Virtual Environments

Lets set up our virtual environments with conda. This will allow you to have an isolated environment for different projects. I typically default with the most recent version and create a 2.7 environment.

to check what environments are install type

conda info -e

To install a full version of python 2.7 with many packages, type

conda create -n py27 python=2.7 anaconda

In linux activate different environments by

source activate py27
source deactivate

and in windows

activate py27
deactivate

Converting an ipython notebook to an html document

Ipython notebooks can eaily be converted to an html file with the following python code

get_ipython().system('jupyter nbconvert --to html mechpy.ipynb')

or, in the OS terminal

jupyter nbconvert --to html mechpy.ipynb

Running jupyter notebook in windows

In windows, create a batch file (*.bat) to run a jupyter notebook server in the current directory

:: Use to launch jupyter notebooks
:: change console to the current working directory
Pushd "%~dp0"
:: launch jupyter notebook
jupyter notebook
:: write html output
jupyter nbconvert --to html mechpy.ipynb
pause

Excel and Python - They can be friends

Because it's there and everyone uses it Automate the boring stuff, python excel scripting
Use python intsead of VBA with xlwings
Or with pandas, use xlsxwriter
openpyxl
or just develop directly with Windows COM


mechpy modules documentation

composites

specialized code to analyze composite plates using classical laminated plate theory

design

shear-bending diagrams, assisting hand calculations for stress

fem

example code for computing finite element models for analysis and education

math

various math tools for processing engineering systems

statics

code for assisting and checking hand calculations

units

unit conversion

sympy units

catia

API code to automate cad in catia using wincom32 module

abaqus and abaqus_report

API code to automate running of finite element models and reporting using python-pptx. 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.

abaqus documentation

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 program was designed to generate a dynamic powerpoint presentation based on a user defined odb file. The abaqus.py requires and abaqus license and can be run from the abaqus python console within Abaqus CAE. The abaqus_report.py has many other modules that are not allowed in Abaqus python. PythonReportTool calls functions located in the AbaqusReportTool.py and can be run in any python console or windows terminal and can be executed by opening a windows command prompt by.

In the python console in Abaqus >>> , commands can be typed to use parts of AbaqusReportTool. To execute specific functions in AbaqusReportTool, type:

>>>import os
>>>os.chdir('C:/Users/User1/Directory_with_py_files')
>>>import AbaqusReportTool
>>>odbname='bottle_test/bottle_test.odb'  # odb file cannot have spaces in the name or special characters, just letters, numbers hyphens and underscores!
>>>myOdbTest = AbaqusReportTool.AbaqusReportTool(odbname)

When myOdbTest is loaded, a check is made to determine if the database needs updated, and does so if it does. Also, >>> indicates we are in the python console. and will be dropped henceforth

A few examples of how to run individual functions

# to see all the functions available
dir(myOdbTest)
#['BE_makeReportData', 'BT_makeReportData', 'CBE_makeReportData', 'HS_makeReportData', 'TL_makeReportData', 'VP_edit', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'avi_save', 'clearFiles', 'clearFilesExcept', 'csv_field', 'csv_history', 'csysCyn', 'getMaxField', 'myAssembly', 'myOdb', 'myOdbDat', 'myOdbDat2', 'myOdbVis', 'myOdbs', 'myView', 'myVp', 'png_save', 'png_undeformed', 'replaceElementSets', 'replaceNodeSets', 'rpt_field', 'txt_field_summary', 'txt_history_summary', 'txt_odb_summary', 'xplot_field', 'xplot_history', 'xyList_field', 'xyplot_history']

# to change the viewport to default values of the function, s=0, f=0, o='', c='', csys = '', setsKeyword = '',v='Iso1',myLegend = ON, myState=OFF, myMaxValue = 0, myMinValue = 0)
myOdbTest.VP_edit()

# this code will change the current viewport to step 0,frame 0, object Stress, Component S11, coordinate system default, elementsets all, view Iso1, Legend on, State on, maxvalue auto minvalue auto
myOdbTest.VP_edit(s=0, f=0, o='S', c='S11', csys = '', setsKeyword = '',v='Iso1', myLegend = ON, myState=OFF, myMaxValue = 0, myMinValue = 0)

# to clear all files from the directory except odb and pptx where the odb file resides
myOdbTest.clearFilesExcept(['odb','pptx'])

# to create a text file that describes all the fields in the odb file
myOdbTest.txt_field_summary()

# saves a png of the current viewport
myOdbTest.png_save()

Accessing History Region info using the bottle_test example

myOdbTest.myOdbDat.steps.keys()
# ['pressure']
myStep = myOdbTest.myOdbDat.steps['pressure']
myStep.historyRegions.keys()
# ['Node CATGSD_F_SHAMPOO_BOTTLE_END-1.58', 'Node CATGSD_F_SHAMPOO_BOTTLE_END-1.574']
myRegion=myStep.historyRegions['Node CATGSD_F_SHAMPOO_BOTTLE_END-1.58']
myRegion.historyOutputs.keys()
# ['RF1', 'RF2', 'RF3', 'U1', 'U2', 'U3']
myRegion.historyOutputs['RF1'].description
# 'Reaction force'
# returns a nested tuple of time and the RF1 data
myDat = myRegion.historyOutputs['RF1'].data
# inverts the tuple and unpacks myDat into time and myRF1
time, myRF1  = zip(*myDat)

Extracting Field info

myFieldval = myStep.frames[-1].fieldOutputs['U'].values
myU1 = [myFieldval[k].data[0] for k in range(len(myFieldval))]

Closing the database. even though the database is read-only, it is good practice to close the database

myOdbTest.myOdbDat.close()

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

launch an abaqus program

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

Some of the abaqus file types

files generated by created and analyzing a model

files created when a job is submitted

Outputs

Abaqus Scripting User's Guide - 5.2.2

field output

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

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:

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.

Common Abaqus activities

Access the help documentation by typing abaqus doc in console or

Help -> Search and Browse Guides

execute a abaqus/python script

File -> Run Script

record a abaqus/python macro, where files are stored in users home directory in abaqusMacros.py

File -> Macro Manager

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

File -> Abaqus PDE...

set default working directory

plugins

abaqus_plugins\reportGenerator\htmlReportGeneratorForm.py

Change font of legend

Viewport -> Viewport Annotation Options -> Triad -> Set Font

Abaqus/Python Scripting

Abaqus specific Python modules imports

built in abaqus gui example

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

def printCurrentVp(picname = 'file1'):

    from abaqus import session, getInputs
    from abaqusConstants import PNG
    name = getInputs( (('File name:', ''),),
        'Print current viewport to PNG file')[0]
    vp = session.viewports[session.currentViewportName]
    session.printToFile(
        fileName=name, format=PNG, canvasObjects=(vp, ))

viewVector    =(0,1,0)  #  x,y,z
cameraUpVector=(0,0,1)

myViewport.view.setValues(session.views['Front'])
myViewport.view.setViewpoint(viewVector=(0,0,1), cameraUpVector=(0,1,0))

myViewport.view.setValues(session.views['Back'])
myViewport.view.setViewpoint(viewVector=(0,0,-1), cameraUpVector=(0,1,0))

myViewport.view.setValues(session.views['Top'])
myViewport.view.setViewpoint(viewVector=(0,1,0), cameraUpVector=(0,0,-1))

myViewport.view.setValues(session.views['Bottom'])
myViewport.view.setViewpoint(viewVector=(0,-1,0), cameraUpVector=(0,0,1))

myViewport.view.setValues(session.views['Left'])
myViewport.view.setViewpoint(viewVector=(-1,0,0), cameraUpVector=(0,1,0))

myViewport.view.setValues(session.views['Right'])
myViewport.view.setViewpoint(viewVector=(1,0,0), cameraUpVector=(0,1,0))

myViewport.view.setValues(session.views['Iso'])
myViewport.view.setViewpoint(viewVector=(1,1,1), cameraUpVector=(0,1,0))

Other random tests from the documentation

abaqus fetch job=odbElementConnectivity
abaqus fetch job=viewer_tutorial
abaqus cae odbElementConnectivity.py -- viewer_tutorial.odb

This document was generated from content in the abaqus documentation as a quick reference guide when using abaqus. To access this content

Help -> Search and Browse` Guides...

End of abaqus documentation


References

Hibbler - Statics
Hibbler - Mechanics of Materials
Collins et al - Mechanical Design of Machine Elements and Machines
Flabel - Practical Stress Analysis for Design Engineers
Peery - Aircraft Structures
Niu - Airframe Stress Analysis and Sizing

Links

Python Online Engineering Classes

scientific-python-lectures
Practical Numerical Methods with Python with source code
Aerodynamics / Hydrodynamics with Python
Cornell
Python numerical methods mooc
Computational Physics with Python
Coding the Matrix

Python Engineering Books

Numerical Python - A Practical Techniques Approach for Industry with source code
Elementary Mechanics Using Python
A Primer on Scientific Programming With Python
Coding the Matrix

Python Engineering Libraries

General Numeric Python

Python has mature scientific computation packages, namely scipy

Scipy.

Scipy Cookbook
Scipy Guide
Scipy Lectures
Learning Scipy
Scipy Tutorial

Numpy.

Numpy
Official Docs Numpy for matlab users
100 numpy examples
numpy on windows

Sympy.

sympy tutorial
sympy features
sympy physics

Matplotlib.

matplotlib gallery and matplotlib tutorial
interactive matplotlib

Fluids/Aero

aeropy
NACA airfoils
aeropython or aeropython
pyaero

Mechanics/Composites/Materials

pyply composites
sympy classical mechanics
pygear
AeroComBAT https://github.com/elainecraigie/MechanicsOfCompositesProject_ECraigie

FEM / Math

pynastran
grid solvers with example
ode solver
differential equations demo
DiffyQ
pycalculix
FEniCS tutorial
SfePy-Simple Finite Elements in Python
PyODE
getfem++
pycalculix
Pysimulator
pyfem

Units

pint units
Unum units
quantities scipy units

Dynamics and Control Systems

pyndamics
Python for Controls, System Dynamics, and Mechatronics
python-control
vibrationdata
CoupledSpringMassSystem
PyDSTool
python control
pydy with examples and here

Plotting and Visualization

bumpy
pygame physics
Pymunk visualization and here
vpython


Neal Gordon, 2016
Developed using doconce with the bootstrap theme and github hosting