13.07.2015 Views

Analysis of Structures - Baustatik-Info-Server

Analysis of Structures - Baustatik-Info-Server

Analysis of Structures - Baustatik-Info-Server

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong>Book <strong>of</strong> Examples2011University <strong>of</strong> Duisburg-EssenFaculty <strong>of</strong> EngineeringDepartment <strong>of</strong> Civil EngineeringStructural <strong>Analysis</strong> and ConstructionDr. E. Baeck2.12.2011


Page iv<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/112.12 Date, Time and Timespan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382.13 Working with Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.13.1 Open a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.13.2 Write Data into a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.13.3 Close a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412.14 OOP with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412.14.1 Some UML Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412.14.2 Implementation <strong>of</strong> a Time Stack Class . . . . . . . . . . . . . . . . . . . . . . . 433 Python Projects 473.1 Newton, Step2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473.2 Pr<strong>of</strong>iles, Thin Walled Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.2.1 Implementation <strong>of</strong> a general Pr<strong>of</strong>ile Classes . . . . . . . . . . . . . . . . . . . . 513.2.2 Implementation <strong>of</strong> basic Classes for a Thin Walled Model . . . . . . . . . . . . 563.2.3 Implementation <strong>of</strong> a little Pr<strong>of</strong>ile Database . . . . . . . . . . . . . . . . . . . . 62II Scripting with Abaqus 654 Some Aspects and Introduction 674.1 Aspects <strong>of</strong> the Abaqus GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674.2 The Abaqus CAE Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684.3 A Modeling Chain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.4 A little interactive Warm Up Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 704.4.1 Create a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704.4.2 Create a Sketch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704.4.3 Create a Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704.4.4 Create and Assign Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714.4.5 Create the Instance, Assign the Part . . . . . . . . . . . . . . . . . . . . . . . . 714.4.6 Create a Load Step . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714.4.7 Create Loads and Boundary Conditions . . . . . . . . . . . . . . . . . . . . . . 714.4.8 Create the Mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714.4.9 Create a Job and Submit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 Scripts and Examples 735.1 3 Trusses Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735.2 U Pr<strong>of</strong>ile Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80III Appendix 95A Some Theory 97A.1 Section Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97A.1.1 The Area <strong>of</strong> a Pr<strong>of</strong>ile Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97A.1.2 First Moments <strong>of</strong> an Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97A.1.3 Second Moments <strong>of</strong> an Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98A.1.4 Center <strong>of</strong> Mass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99E. Baeck


CONTENTS Page 1A.1.5 Moments <strong>of</strong> Inertia with Respect to the Center <strong>of</strong> Mass . . . . . . . . . . . . . . 99A.1.6 Main Axis Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1002.12.2011


Page 2<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11E. Baeck


Part IProgramming with Python3


1How to get started with Python1.1 Python, Packages, UtilitiesIf we start with Python, we should think about the choice <strong>of</strong> the Python version. Because we will usesome additional Python packages, we should be sure, that this packages are available for the desiredPython version. In the case <strong>of</strong> our lecture we will select the Python version 2.6, which is properly stableand furthermore all the needed add-on packages are available.To start from the beginning, we have to download the following packages for windows first. It is recommendedto download the windows installer version, if available because this is the easiest kind <strong>of</strong>installation. The installation procedure should start with the installation <strong>of</strong> the kernel package.• python-2.6.4.msiThe installer <strong>of</strong> the python kernel system 2.6.• comtypes-0.6.2.win32.exeThe installer <strong>of</strong> Windows types, which are necessary to use Windows API-calls.• numpy-1.4.1-win32-superpack-python2.6.exeThe installer <strong>of</strong> the NumPy package for numerical programming.• scipy-0.8.0-win32-superpack-python2.6.exeThe installer <strong>of</strong> the SciPy package for sientific programming.• matplotlib-0.99.3.win32-py2.6.exeThe installer <strong>of</strong> the MatPlotLib package.• pywin32-214.win32-py2.6.exeThe installer <strong>of</strong> a little nice Python IDE.1.1.1 Installing the KernelThe python kernel should be the first package, which is to install, because this installation sets up thePython base folder. Within this folder you can find the folder Lib, which contents a lot <strong>of</strong> libraries andadditional packages and besides that a further sub folder called site-packages. Add ons are copied intothis folder by their installers or by the install Python script.5


Page 6<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11The start screen <strong>of</strong> the Python installer shows the Python version. You can select, whether the setupshould make Python available for all users or not. After clicking next you’ll get within the second formthe possibility to select the base folder <strong>of</strong> Python. By default Python uses the folder C:\Python26.We overwrite the default and select the Windows standard program folder as starting folder, so we writec:\Programme\Python26 1 .The figures 1.1 and 1.2 show the input forms installing the Python kernel.Figure 1.1: Start Screen <strong>of</strong> the Python Installer and Choice <strong>of</strong> Base FolderFigure 1.2: Selection the Features and Starting the Installation1.1.2 Installing the ComType PackageIf you want to use the Python language on a Windows system, it’s recommended to install the ComTypespackage. This package will give you a simple access to the Windows resources. It can be understood asa wrapper layer, an interface layer for the access to Windows DLL-modules. ComTypes can be a help todevelop a s<strong>of</strong>tware with a proper Windows look and feel.The installation <strong>of</strong> the most Python packages will run very simular to the following installation. Thefigures 1.3 show the first and second form <strong>of</strong> the installation procedure. The first form gives a few1 The discussed installation was performed on a German systemE. Baeck


1.1. PYTHON, PACKAGES, UTILITIES Page 7information to the package. The second form is usually used to select the Python version. Each installedand supported Python version will be listed in the list box <strong>of</strong> the second form. You can select the desiredPython version and can go on with the installation procedure clicking the next button.Figure 1.3: Start Screen <strong>of</strong> the Package Installer and Choice <strong>of</strong> the installed Python Version1.1.3 Installing the NumPy PackageNumPy [2] is the fundamental package for scientific computing in Python. It is a Python library that providesa multidimensional array object, various derived objects (such as masked arrays and matrices), andan assortment <strong>of</strong> routines for fast operations on arrays, including mathematical, logical, shape manipulation,sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations,random simulation and much more.At the core <strong>of</strong> the NumPy package, is the ndarray object. This encapsulates n-dimensional arrays <strong>of</strong>homogeneous data types, with many operations being performed in compiled code for performance. 2The installation runs like the installation <strong>of</strong> the ComTypes package (see figure 1.4).Figure 1.4: Start Screen <strong>of</strong> the Package Installer and Choice <strong>of</strong> the installed Python Version1.1.4 Installing the SciPy PackageSciPy [3] is a collection <strong>of</strong> mathematical algorithms and convenience functions built on the Numpy extensionfor Python. It adds significant power to the interactive Python session by exposing the user to2 For more details see NumPy User Guide available on the http://info.baustatik.uni-due.de2.12.2011


Page 8<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11high-level commands and classes for the manipulation and visualization <strong>of</strong> data. With SciPy, an interactivePython session becomes a data-processing and system-prototyping environment rivaling sytemssuch as Matlab, IDL, Octave, R-Lab, and SciLab.The additional power <strong>of</strong> using SciPy within Python, however, is that a powerful programming languageis also available for use in developing sophisticated programs and specialized applications. Scientificapplications written in SciPy benefit from the development <strong>of</strong> additional modules in numerous niche’s<strong>of</strong> the s<strong>of</strong>tware landscape by developers across the world. Everything from parallel programming to weband data-base subroutines and classes have been made available to the Python programmer. All <strong>of</strong> thispower is available in addition to the mathematical libraries in SciPy. 3The installation runs like the installation <strong>of</strong> the ComTypes package (see figure 1.5).Figure 1.5: Start Screen <strong>of</strong> the Package Installer and Choice <strong>of</strong> the installed Python Version1.1.5 Installing the PythonWin IDEThere are lot <strong>of</strong> IDEs available for the development <strong>of</strong> Python s<strong>of</strong>tware. Most <strong>of</strong> them are commercial.One very nice IDE especially for large development projects with a lot <strong>of</strong> python files is called Aptana.Apatana is a special version <strong>of</strong> the free Eclipse IDE. For this IDE there is a plugin available, which iscalled PyDev. To use this IDE first you have to install the basis version <strong>of</strong> Aptana and then you shouldinstall the plugin and select the desired Python version, which should be installed before. An exampleproject within the Aptana is shown in figure 1.6.PythonWin is very much simpler than Aptana and has the advantage, that really only the feature areavailable that are nessesary to get started with small Python programs. The installation runs like theinstallation <strong>of</strong> the ComTypes package (see figure 1.7).After having installed the PythonWin IDE it’s recommended to set up a link onto the desktop (see figure1.8).3 For more details see SciPy Reference Guide available on the http://info.baustatik.uni-due.deE. Baeck


1.1. PYTHON, PACKAGES, UTILITIES Page 9Figure 1.6: Aptana IDEFigure 1.7: Start Screen <strong>of</strong> the PythonWin IDE Installer and Choice <strong>of</strong> the installed Python VersionFigure 1.8: Creating a Link to the pythonwin.exe2.12.2011


Page 10<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/111.2 Hello WorldLike in every computer language there is a Hello World application in Python also possible. We startdhe PythonWin IDE and create a new file. We save this file as HelloWorld.py. With Ctrl-R the executionform is shown and the execution mode should be selected (see figure 1.9).The following available execution modes are available.• No debugging,execution without debugging.• Step-through in the debugger,the debugger is stated and starts with the first statement.• Run in the debugger,the script is started. Execution is only interrupted at the first breakpoint.• Post-Mortem <strong>of</strong> unhandled led exceptions,the debugger is started, if the script crashes with a unhandled exception.Figure 1.9: Executing the HelloWorld.py ScriptIf the HelloWorld.py script is executed, the output is written into the Interactive Window, see figure 1.10.1.3 Python CalculatorOne <strong>of</strong> Python’s advantages is the feature to execute only one statement within the Python shell. ThePython shell within the PythonWin IDE is given by the Interactive Window, see figure 1.10.If we want to calculate the vertical position <strong>of</strong> a ball thrown up in the air with an initial velocity v 0 aftera time t we get from the Newton’s lawy(t) = v 0 · t − 1 2 · g · t 2 (1.1)E. Baeck


1.3. PYTHON CALCULATOR Page 11Figure 1.10: Executing the HelloWorld.py Script and Console WindowSo, if we want to calculate the vertical position for an initial velocity v 0 = 5m/s after 0,6 seconds, wecan calculate the y(t = 0, 6) with one simple Python call.>>> print 5*0.6 -0.5*9.81*0.6**21.2342>>>A second version <strong>of</strong> the calculation can be performed introducing and using variables as follows. So wecan check every Python command within the Interactive Window.>>> v0 = 5>>> g = 9.81>>> t = 0.6>>> y = v0*t - 0.5*g*t**2>>> print y1.2342>>>A third version <strong>of</strong> our calculation <strong>of</strong> the ball’s height could be a Python script, which we can load andexecuted within the PythonWin IDE. To comment the code we insert some comments, which starts withthe # character. Characters at the right side <strong>of</strong> the # character are ignored by the Python interpreter.First small Example# program for computing the height <strong>of</strong> a ball thrown up in the airv0 = 5# initial velocityg = 9.81# acceleration <strong>of</strong> gravityt = 0.6# timey = v0*t - 0.5*g*t**2 # vertical positionprint y# printing the resultEnd <strong>of</strong> Coding2.12.2011


Page 12<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11E. Baeck


2Basics in Python2.1 Reserved WordsWe have seen in section 1.3, starting with a Python calculation within the Python shell is very easy. Wecan use simple formulas with numbers or we can use symbolic names to make it more readable. InPython like in other programming languages there are some reserved word, which are used to build upthe language. This words can not be used as variable names.The reserved words <strong>of</strong> the Python language are the following.and del from not whileas elif global or withassert else if pass yieldbreak except import printclass exec in raisecontinue finally is returndef for lambda tryIf you want to use such a word it’s recommended to extent the name with an underscore, like vor examplebreak_ instead <strong>of</strong> break.2.2 Packages and ModulesA package within Python is a container <strong>of</strong> s<strong>of</strong>tware objects, global variables, functions and objects. In Cor Fortran, a package could be termed as library.Packages should be imported into the Python session or into the Python source file, if external featureshould be used. A typical package import is the import <strong>of</strong> the mathematical package. This is necessaryif you want to call some basic mathematical functions like trigonometric functions or the square root. Ifsuch a package is not imported, it’s objects, especially it’s functions, are unknown and can not be used.Packages are like header includes within the C language. In C as well, external functions, whose headersare not included, are unknown and can not be called.13


Page 14<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/112.2.1 Import <strong>of</strong> a whole Module or PackageA whole package is imported with the statement "import" module. The following example showsthe import <strong>of</strong> the mathematic package to apply the square root function. With the import statement themodule math will be linked. The square root function sqrt will be then available with the usual dot accessmath.sqrt.>>> import math>>> math.sqrt(4)2.0>>>2.2.2 Selective Import <strong>of</strong> Module NamesIf we only want to import a symbolic name <strong>of</strong> a module (package), then we can import in a selectiveway. The nex example shows the selective import <strong>of</strong> the function sqrt from the module math. If we dothis, then the function can be used without the prefixing module name.>>> from math import sqrt>>> sqrt(4)2.0>>>2.2.3 Import with new NamesIf some names <strong>of</strong> <strong>of</strong> module should be imported with new names, the statement as can be used withinthe import statement. The following example shows the import <strong>of</strong> the trigonometric functions sin andcos with the new names s and c and the constant pi with it’s original name, to calculate the Cartesianordinates <strong>of</strong> a 45 ◦ point with radius 10.>>> from math import sin as s, cos as c, pi>>> r = 10>>> x = r*c(pi/4)>>> y = r*s(pi/4)>>> x7.0710678118654755>>> y7.0710678118654746>>>You see, that we change the original name <strong>of</strong> the trigonometric functions with the as key word. Withinthe formulas the functions can be used with it’s new names.2.3 OperatorsWe have already seen, that Python also has it’s operators calculation the height <strong>of</strong> a vertical thrownball. Python uses the same precedence as we know form the mathematics. The power operation has thestrongest binding followed by the point operators (products and divisions) followed by the line operatorsE. Baeck


2.3. OPERATORS Page 15(plus and minus). Unary operators will always be applied first. To change the standard precedence <strong>of</strong> theoperators we use like in mathematics parenthesis to dictate the way a formula should be evaluated.2.3.1 Unary OperatorsUnary operators are working only on one value, therefor unary. In Python there are three unary operatorsavailable.Operator Comment Example+ plus operator a = 2 >>> x = +a >>> +2- minus operator a = 2 >>> x = -a >>> -2˜ bitwise inversion a = 2 >>> x = ˜a >>> -3The bitwise inversion shows the internal representation <strong>of</strong> negative numbers. A negative number isrepresented by the so called b-complement <strong>of</strong> a number. This is the complement, i.e. the bitwise invertednumber plus 1. So we get−a =∼ a + 1 or ∼ a = −(a + 1) (2.1)2.3.2 Arithmetic OperatorsPython <strong>of</strong>fers the following arithmetic operators. You should be careful with the usage <strong>of</strong> data typesespecially within divisions. If you use integers, the result generally will be truncated. 1Operator Comment Example+ sum operator x = 2+3 >>> 5- substraction operator x = 4-2 >>> 2* product operator x = 2*4 >>> 8/ division operator x = 9/2 >>> 4x = 9./2. >>> 4.5** power operator x = a**2% modulo operator x = a%2// integer division operator x = a//22.3.3 Bit OperatorsLike in C bit operators can be easily be used to manipulate a number’s bits. The following operators areavailable 21 The exception <strong>of</strong> the power operator all the arithmetic operators are used with the same symbol like in C. In C there is nopower operator available.2 Python’s bit operators are exactly the some as the C bit operators.2.12.2011


Page 16<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Operator Comment Example& bitwise AND x = 23 & 13 >>> 5ˆ bitwise exclusive OR x = 23 ˆ 13 >>> 26| bitwise OR x = 23 | 13 >>> 31> 16>> right shift <strong>of</strong> bits x = 4 >> 1 >>> 2The left shift <strong>of</strong> a numbers bit by 1 is equal to a multiplication by 2. The right shift by one is the same asa division by 2. The bitwise AND and OR operator are usually used to set or to clear a number’s bits.The following example shows how to apply the shift operator. We start with the bit 0, which has thevalue 1. Within a for loop (see section 2.7) the bit is shiftet subsequently to the left. So we create the bitsin the range from n to m. After shifting the bit, it’s value is printed into the console window.List the Bit’s Values# print the value the bits from bit n to bit m#n = 1m = 10bit 0 = 1for i in range(n,m+1):bit i = bit 0


2.3. OPERATORS Page 17>>> a = 27563>>> "%X" %a’6BAB’>>>The binary number representation is easily available from the hexadecimal representation, if we knowthe binary representation <strong>of</strong> the hexadecimal digits 4 .6 16 = 6 10 = 4 + 2 = 0110 2A 16 = 10 10 = 8 + 2+ = 1010 2B 16 = 11 10 = 8 + 2 + 1 = 1011 2So we get assembling the binary digits <strong>of</strong> 6BAB the following bit sequence.27563 10 = 6BAB 16 = 0110|1011|1010|1011 2 (2.2)If we now want to set the highest bit <strong>of</strong> the discussed number, we can use the bitwise OR operator | (seesection 2.3.3). A number with only the highest bit set we can obtain by shifting the first bit to the desiredposition within the 2 bytes, i.e. we shift the bit 15 times. Now we can see that we get a hexadecimalnumber with only the highest digit non vanishing. Within the digit <strong>of</strong> 8 the forth bit is set, which is thehighest <strong>of</strong> a have byte 5 .>>> b = 1>>> b = b> b32768>>> "%X" % b’8000’If we now want to set the highest bit <strong>of</strong> our original number 27563, we simple can overlay it with the lastnumber 8000.>>> a = 27563>>> b = a | (1> b60331>>> "%X" % b’EBAB’After having set the highest bit, we see that the decimal number has changed totally. However thehexadecimal number only changes in the first digit. Instead <strong>of</strong> 6 we have now E. And E is representedbinary withE 16 = 14 10 = 8 + 4 + 2 = 1110 2so we get60331 10 = EBAB 16 = 1110|1011|1010|1011 2 (2.3)4 The index <strong>of</strong> the example’s numbers represent the base <strong>of</strong> the numbering system.5 A half byte is also called nibble.2.12.2011


Page 18<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Comparing the binary result with the binary result <strong>of</strong> equation 2.2 we see that obiously only the first bitis set as wanted.How we can now clear a bit <strong>of</strong> a number? Clearing a bit <strong>of</strong> a number uses two steps. First we have tocreate the inverse <strong>of</strong> the filtering number, having set only the desired bit. And within a second step weuse the AND operator & to overlay bitwise the inverse <strong>of</strong> the filtering number and the number, whose bitshould be cleared. In our example we want to clear the highest bit <strong>of</strong> the first byte. The filtering numberwe get shifting the 1st bit 7 times.>>> a = 27563>>> b = a & (˜(1> b27435>>> "%X" % b’6B2B’We also notice, that the decimal representation has changed widely after the clearing <strong>of</strong> the bit on thecontrary to the hexadecimal.27435 10 = EB2B 16 = 1110|1011|0010|1011 2 (2.4)2.3.5 Comparison OperatorsBoolean operators are used to branch and to make decisions. The comparing operators are identical tothe C comparing operators. 6Operator Comment Example< less than x = 23 < 13 >>> False> True> greater x = 23 > 13 >>> True>= left shift <strong>of</strong> bits x = 23 >= 23 >>> True== equal x = 23 == 23 >>> True equal x = 23 13 >>> False!= non equal x = 23 != 23 >>> FalseThe result <strong>of</strong> a boolean expression like above are the boolean values False or True. To combinecomparing expressions the following logical operators can be used. 7Operator Comment Exampleand logical and x = 1 < 2 and 2 < 3 >>> Trueor logical or x = 1 < 2 or 2 > 3 >>> Truenot logical not x = not (1 < 2) >>> False6 There are two non equal operators available. ! = is the C version and is the Basic version.7 To make expressions clear parenthesis should be used. A term within a parenthesis is evaluated first and it’s result then isused in further evaluations outside the parenthesis. With parenthesis the order <strong>of</strong> the evaluation can be set.E. Baeck


2.4. PRINT AND OUTPUT FORMATS Page 19The truth table for the AND operator ∧ is given as follows.True ∧ True = True (2.5)True ∧ False = FalseFalse ∧ True = FalseFalse ∧ False = FalseThe truth table for the OR operator ∨ is given as follows.True ∨ True = True (2.6)True ∨ False = TrueFalse ∨ True = TrueFalse ∨ False = False2.3.6 Membership OperatorsWith the membership operators you can check whether a value or an object is part <strong>of</strong> sequence <strong>of</strong> objects.Operator Comment Examplein is member x = 2 in (1,2,3) >>> Truenot in is not a member x = 2 not in (1,2,3) >>> False2.3.7 Identity OperatorsWith the identity operators you can check the identity <strong>of</strong> two objects.Operator Comment Exampleis is identical x = (1,2) >>> y = x >>> x is y >>> Trueis not is not identical x = (1,2) >>> y = x >>> x is not y >>> False2.4 Print and Output FormatsIf you want to print data into the console window, you have to think about formating. The formatingsequences are very similar to the formating sequences <strong>of</strong> the C printf function. The formating is a socalled escape sequence within a string, which is started with the % operator.The most common formats are the following.• formating an integerAn integer (independent <strong>of</strong> the data type) is formated by the escape %d for decimal representationand %x or %X for hexadecimal representation.• formating a floatA float is formated by the escapes %f, %e, %E, %g and %G2.12.2011


Page 20<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11• formating a stringA string is formated by the escapes %sA leading number n within a format %nT, with T the type <strong>of</strong> the format, sets up the width <strong>of</strong> the output.The following example shows the formating <strong>of</strong> an integer in decimal and hexadecimal mode. At thehexadecimal format a lower x sets lower digit letter, the capital X sets capital digit letters.>>> "%d,%3d,%6d" % (2,2,2)’2, 2, 2’>>> "%x,%3X,%6X" % (31,31,31)’1f, 1F, 1F’Formating floats there are two different formats available, the fixed format and the exponential format,which is also called scientific format. The f format sets a non exponential representation. The e or Eformat sets a exponential format. e uses a small e letter, and E uses a capital E letter. The g or G formatsets an optimized representation, i.e. a fixed or an exponential format, depending on the outputs length.The number after the dot sets the number <strong>of</strong> digits after the comma for f and e format, it sets the number<strong>of</strong> significant digits for the g format.>>> "%f,%e,%g" % (12.34,12.34,12.34)’12.340000,1.234000e+01,12.34’>>> "%.2f,%.2e,%.2g" % (1234567.89,1234567.89,1234567.89)’1234567.89,1.23e+06,1.2e+06’2.5 Basic Data TypesRecording to the available data types, Python is very different comparing it with common languages likeC, Fortran and Basic. Most <strong>of</strong> the languages <strong>of</strong>fers the programmer data types, which are one by onerelated to the underlaying hardware.So for example Fortran and C <strong>of</strong>fer 2 and 4 byte integers on 32 bit operating systems by default 8 On a64 bit operating platform a long integer <strong>of</strong> 8 bytes will be available. On the other hand there are 4 and 8byte floats available.Python however <strong>of</strong>fers on 32 bit platforms a normal integer <strong>of</strong> 4 bytes, which is directly related to thehardware, for example 11234, and furthermore a so called long integer, for example 1234L, which ishandled by the Python s<strong>of</strong>tware. The long integer, which is marked by a succeeding L, is only restrictedby the computers memory, that means that a really incredible number <strong>of</strong> digits can be considered. Laterwe will calculate the factorial <strong>of</strong> a incredible high number.Furthermore Python as already mentioned <strong>of</strong>fers only one float data type with 8 bytes. The standardized4 byte float is not supported, for example 1.23 or 1.23e+2.Python also supports a complex arithmetic with an complex data type, consisting <strong>of</strong> two floats for realand imaginary part <strong>of</strong> the complex number. The complex unit in Python is called j. Therefor the complexnumber 1 + 4i will be represented in Python with 1 + 4j .8 That means without applying provider depended tricks.E. Baeck


2.6. CODE BLOCKS Page 21The last data type used in Python is a string consisting <strong>of</strong> one or more characters.The data type <strong>of</strong> a variable can be determined using the build in function type, as shown in the followingexample. Within a first step different variables were created by a simple assignment. The content <strong>of</strong> thevariable determines the type <strong>of</strong> the variable, no explicit declaration is needed or available, like in C. Afterhaving created the variables the type <strong>of</strong> the variables will be determined by subsequent type calls.To check the data type within a program the following tests can be made.1. if type(d).__name__ == ’int’You can check the type with the types __name__ member.2. if type(d) == int... or you can check the type with the type class name (discussed later).>>> a = 2>>> b = 3L>>> c = 4.5>>> d = 6 + 7j>>> e = "Hello World">>> type (a)>>> type (b)>>> type (c)>>> type(d)>>> type(e)You see, ’int’ is integer, ’long’ is long integer, ’float’ is float, ’complex’ is complex and’str’ is string data type.Furthermore there are some sequences in Python available, which combines the mentioned data types ina more or less sophisticated mode. More about that later.2.6 Code BlocksOne very imported feature <strong>of</strong> Python is, that code blocks are bracketed by an unique indent. The mostprogramming languages uses there specific code parenthesis. There is one opening parenthesis whichstarts the code block and there is one closing parenthesis, which closes the code block.The following example shows a code block in C.if (a > b){c = a + bd = a - bFurther Lines <strong>of</strong> C-Code}2.12.2011


Page 22<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11The following example shows a code block in Fortran77.if (a .gt. b) thenc = a + bd = a - bFurther Lines <strong>of</strong> Fortran-CodeendifCompared with this in Python the code block is bracketed by indent as follows.if a > b:c = a + bd = a - bFurther Lines <strong>of</strong> Python-Codea = bOne statement which uses a code block, in this case an if statement, is closed by a colon. After the colonan unique indent for the lines <strong>of</strong> the code block must be used. If not, it will be a syntax error. The codeblock is closed, if the last line <strong>of</strong> the code block is the last line <strong>of</strong> the whole code, or is closed by a line<strong>of</strong> code which is indented like the opening statement. In our example the assignment a=b has the sameindent as the if statement and so this line will be the first line <strong>of</strong> code outside our code block.2.7 Loop for RepetitionsLike all programming languages, which make sense, Python also has some implementations <strong>of</strong> repetitions,<strong>of</strong> loops. Like in C an explicit loop is available - the for loop - as well as an implicit loop isavailable - the while loop.The for loop is controlled by an iterated set. One very common variant is the for loop, which is controlledby an iteration counter. The iteration counter will be configured by a range object. The range object has3 parameters 9 . The first parameter sets the start value <strong>of</strong> the iteration counter, the second parameter setsup the iteration value, which will be the first value that is not performed. The third parameter sets up theincrement.The following typical example for the usage <strong>of</strong> an iterative for loop implements the calculation <strong>of</strong> thefactorial.n∏n! = i (2.7)i=1The implementation <strong>of</strong> the factorial is given below. Note the importance <strong>of</strong> the indent, see section 2.6.9 A parameter is a information unit, which is passed to the called object. If more then one parameter is passed, the parametersare separated by commas.E. Baeck


2.7. LOOP FOR REPETITIONS Page 23n = 10# factorial inputp = 1 # result variable must be initalized by 1for i in range(2,n+1): # the counter runs from 2 up to np *= i# here we perform the productprint "%3d! = %10d" % (n,p) # write the result into the console>>>... console window ...10! = 3628800The second loop type, the while loop is working implicit with a boolean expression, which controls thebreak condition. If we want to implement the factorial using the while loop we get the following code.n = 10# factorial inputp = 1 # result variable must be initalized by 1i = 2# the counter runs from 2 up to nwhile i >>... console window ...10! = 3628800The next example shows a nested loop. Very important is the correct code block indent.for i in range(0,4):# outer loopfor j in range(0,2):# inner loopprint "i:%2d, j:%2d" % (i,j) # print counter variables>>>... console window ...i: 0, j: 0i: 0, j: 1i: 1, j: 0i: 1, j: 1i: 2, j: 0i: 2, j: 1i: 3, j: 0i: 3, j: 1For the detailed controlling <strong>of</strong> the loops cycles two statements are available.• continueIf the continue statement is used a cycle is immediately stopped and the next cycle is started.• breakIf the break statement is used a cycle is immediately stopped and the loop is exited.The next example shows an application <strong>of</strong> the continue statement. A loop is performed with the values0 · · · 4. The cycle with the counter 2 is prematurely canceld.2.12.2011


Page 24<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11>>> for i in range(0,5):... if i == 2: continue... print "i=%d" % i...i=0i=1i=3i=4One very interesting feature <strong>of</strong> Python is the long integer arithmetic. So we can calculate incredible largefactorials. Figure 2.1 shows the code in the upper window. The console window shows the result. Anumber with a lot <strong>of</strong> digits and every digit is exact.Figure 2.1: Calculating the Factorial for a long integerThe next example shows the calculation <strong>of</strong> the factorial using a float. The float factorial can only beevaluated up to 170! = 7.25742e+306. In the case <strong>of</strong> 400! we will get an overflow, because theexponent exceeds the available memory in 8 bytes (see figure 2.2).E. Baeck


2.8. BRANCHES FOR DECISIONS Page 25Figure 2.2: Calculating the Factorial for a float2.8 Branches for DecisionsDecisions are made by the usage <strong>of</strong> the if statement. The if statement is defined as follows.if [boolean expression 1]:code block 1elif [boolean expression 2]:code block 2elif [boolean expression 3]:code block 3...elsecode block elseThe calculation <strong>of</strong> roots <strong>of</strong> a quadratic equation is a nice and simple example to show the application <strong>of</strong>the if statement. The quadratic equation is given bya · x 2 + b · x + c = 0 (2.8)If we want to solve the quadratic equation, we have to analyze the available cases. A general solutionmust handle the following cases.• constant casea = b = c = 0• linear casea = 0, b ≠ 0• quadratic casea ≠ 0• no solution casea = b = 0 and c ≠ 02.12.2011


Page 26<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11The implementation uses a real arithmetic importing the module math. The solver <strong>of</strong> the quadraticequation is implemented in a function called QuadSolve. The function analyzes the different cases andreturns in the constant case only a comment, in the linear case the solution value and a comment. In thequadratic real case 2 values and a comment were returned and in the complex quadratic case there are 4return values and a comment. All return values are packed into a tuple. The case can be identified formthe calling program using the function len, which returns the number <strong>of</strong> items <strong>of</strong> a tuple. To avoid thetesting for zero, which would produce numerical problems in principle, we set the relative precision to10 −15 . An absolute value less then this relative precision is treated as zero value.Quadratic Equation Solver’’’solution <strong>of</strong> a quadratic equation- handling all special cases -’’’# import the used functionsfrom math import fabs as abs, sqrtdef QuadSolve(a,b,c):p = 1.e-15 # precision <strong>of</strong> float, is used to# avoid to test for zero with ==# case: a=0if abs(a) < p:# case: b=0if abs(b) < p:# case: c=0if abs(c) < p:return ("Infinit number <strong>of</strong> solutions.",)# case: c!=0else:return ("No solution possible.",)# case b != 0 (linear case)else:x = -c/breturn (x, "Linear case found.")# case a != 0 (quadratic case)else:d = b**2 -4.*a*cE. Baeck# real caseif d >= 0.:


2.8. BRANCHES FOR DECISIONS Page 27s = sqrt(d)x1 = 1./(2.*a)*(-b +s)x2 = 1./(2.*a)*(-b -s)return (x1,x2,"Real case <strong>of</strong> the quadratic problem.")# complex caseelse:s = sqrt(-d)x1r= -b/(2.*a)x2r= x1rx1i= s/(2.*a)x2i=-x1ireturn (x1r,x1i,x2r,x2i,"Complex case <strong>of</strong> the quadratic problem.")# -------- main program -------------------# input sectiona = 1.b = 0.c = 4.# call <strong>of</strong> QaudSolve functionresult = QuadSolve(a,b,c)# check the result tuple, to select the found casevalues = len(result)print "%d values found in return" % values# format the found result case# no or infinit solution(s)if values == 1:print result[0]# linear caseelif values == 2:print "x = %f, info: %s" % result # (result[0],result[1])# real quadratic caseelif values == 3:print "x1 = %f, x2 = %f, info: %s" % result# complex quadratic caseelif values == 5:print "x1 = %f+(%fi), x2= %f+(%f), info: %s" % resultEnd <strong>of</strong> Coding2.12.2011


Page 28<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11The return values are packed into a tuple (see section 2.10.1). The tuple is used in the set order. So wecan use it for the string format. Reordering is not needed. The output into the console window is thefollowing for the selected test example.x1 = -0.000000+(2.000000i), x2= -0.000000+(-2.000000i),next> info: Complex case <strong>of</strong> the quadratic problem.2.9 FunctionsA function is a callable type. A function starts with the def command. The parameter list succeeds thefunction name and consists <strong>of</strong> names separated by commas. The return <strong>of</strong> return values is optional. Anice example to study cases <strong>of</strong> a solution and their specific return values is discussed in section 2.8.def (Parameter list):Code Blockreturn The following code shows a special version <strong>of</strong> the abs function. The data type is checked first. Only int,long or float type are senseful supported. We check the type with the type function. The type functionreturns a type object. Within the function we check the object member __name__. If the type is notsupported, a error string is returned. If the type is supported, the return value is return. The callingprogram checks the return values type using the object name (int, long and float).Abs Function with Type Checking# declaring our version <strong>of</strong> an abs functiondef MyAbs(x):# process only sensful data types# here we use the type class member name# to check the data typet = type(x). nameif t != ’int’ and t != ’long’ and t != ’float’:return "Error: Type ’%s’ is not allowed." %t# if data type ok change sign if necessaryif x < 0.: return -xreturn x# input sectiony = -4 # test 1# y = "hello" # test 2# function callz = MyAbs(y)# get return typeE. Baeck


2.9. FUNCTIONS Page 29t = type(z)if t == str:print zelse:print "Absolute Value <strong>of</strong> %f = %f" % (y,z)# second version to check the type# print error message# print resultEnd <strong>of</strong> CodingThe following example shows, how to pass a function asa functions parameter. Within the Newton’s algorithma root <strong>of</strong> an equation should be calculated. So we haveto specify the function <strong>of</strong> interest. This function can beconsidered as an input parameter. This function nameis passed to the derivative calculator and to the newtonmain routine. Further we see, that it’s recommended touse standard parameter, to configure the algorithm. Weintroduce the precision parameter e, which sets up thethreshold for a zero compare. Further we need the stepwidth to calculate the derivative <strong>of</strong> the function <strong>of</strong> ourinterest.Figure 2.3: Scheme <strong>of</strong> the Newton AlgorithmThe derivative - it’s called fs in the code - is calculated numerical as follows.f ′ (x) = dfdx ≈ (f (x + h 2 ) − f (x − h 2 ) )/h(2.9)The Newton scheme can be described as follows.x i+1 = x i − f (x)f ′ (x)(2.10)There are three possible situations to handle within the iteration loop.• The function value is vanishing with respect to our selected precision. The iteration loop will bebroken and the found result is passed back to the caller.• The slope <strong>of</strong> the function is vanishing. This situation can not be handled by the simple iterationscheme. The iteration will be broken with an error message.• During the iteration each cycle is counted. So the iteration loop will be broken, if the maximumavailable iterations are reached. The actual values and an error message is passed bake to the caller.The code consists <strong>of</strong> the following functions.• Myf, the function <strong>of</strong> our interest.• fs, the function which calculates the slope <strong>of</strong> a given function numerically.2.12.2011


Page 30<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11• newton, implements the newton scheme.Implementation <strong>of</strong> Newtons Algorithmfrom math import fabs as abs# import the fabs as abs# implementation <strong>of</strong> the function <strong>of</strong> interestdef Myf(x):return x**2 +1.# calculating the derivativedef fs(f,x,h=1.e-6):h = float(h)x = float(x)return (f(x+0.5*h) - f(x-0.5*h))/h# implementation <strong>of</strong> a newton algorithmdef newton(f,x0,e=1.e-10,h=1.e-6,imax=100):error = None# initialize the error code with Noneh = float(h) # we need some floatse = float(e)x1= float(x0) # x to interatei = 1while True:# iteration counterf0 = f(x1) # function’s valueif abs(f0) < e:break# calculating the derivativef1 = fs(f,x1,h)if abs(f1) < e:error = "*** Error: vanishing derivate!"break# available iterations exceededif i >= imax:error = "*** Error: no root found!"break# calculating the values for next iterationx1 -= f0/f1E. Baeck


2.9. FUNCTIONS Page 31# increment the iteration counteri+=1# return the actual position, the function value# and the functions slope, the number <strong>of</strong> performed# iterations and the error code.return (x1,f0,f1,i,error)# the function newton is called with standard parameters# we pass the function <strong>of</strong> interest and a supposed start# positionres = newton(Myf,4.)# the returned tuple is printed into the console windowprint resEnd <strong>of</strong> Coding2.12.2011


Page 32<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/112.10 Data SequencesIn Python there are some sequential data types available.• Strings, a list <strong>of</strong> characters.• Tuples are fixed sequences, which are only extensible. The advantage <strong>of</strong> tuples is the performance.• Lists are changeable sequences but with lower performance.2.10.1 Working with TuplesThe following example shows the creation <strong>of</strong> a tuple. An empty tuple is declared. We extend the tuplewith a one element tuple - note the comma. The second extension extends the tuple with a two elementtuple.>>> t = () # initialize the tuple>>> t()>>> t += (1,) # append the tuple with a number>>> t(1,)>>> t += (2,3) # append at tuple with a second tuple>>> t(1, 2, 3)>>> t[0] # calling the tuple’s first element1>>> t[2] # calling the tuple’s third element3>>> t[3] # an error occur, if the index goes out <strong>of</strong> rangeTraceback (most recent call last):File "", line 1, in IndexError: tuple index out <strong>of</strong> range>>> len(t) # the number <strong>of</strong> elements is given by the len function3Note, that tuples are input data for complex string formatings.>>> "x1 = %8.2f, x2 = %8.3f" % (12.3456,12.3456)’x1 = 12.35, x2 = 12.346’With the function tuple() a tuple can be created from an iterable object like string or list.E. Baeck>>> T =tuple([1.,2.])>>> T(1.0, 2.0)>>> L = list(T)>>> L[1.0, 2.0]>>> T = tuple("Hello World")>>> T(’H’, ’e’, ’l’, ’l’, ’o’, ’ ’, ’W’, ’o’, ’r’, ’l’, ’d’)


2.10. DATA SEQUENCES Page 33Note, that the data <strong>of</strong> a list can be converted into a tuple using the function tuple() and reverse into alist using the function list().2.10.2 Working with ListsLists are more flexible as tuples. Creating and extending lists can be coded like in the case <strong>of</strong> tuples.The only difference is, that lists uses in their declaration the [..] parenthesis. So using lists the codeexample <strong>of</strong> the section 2.10.1 can be coded like follows.>>> L = {] # initialize the list>>> L[]>>> L += [1,] # append the list with a number>>> L[1,]>>> L += [2,3] # append at list with a second list>>> L[1, 2, 3]>>> L[0] # calling the lists first element1>>> L[2] # calling the list’s third element3>>> len(L) # the number <strong>of</strong> elements is given by the len function3You can read somewhere, that tuples are much more faster than lists. This is surely not valid for everyproblem. So it’s recommended to check the performance explicitly before you decide to use tuples orlists.The list object <strong>of</strong>fers a wide set <strong>of</strong> methods. Some <strong>of</strong> them are discussed in the following table.Methode Comment Exampleappend(i) Append an item to the list. Same as += operator. L.append(3)count(x) Counts the value x in the list. L.count(1.2)extend(s) Append a list to the list. Same as += operator. L.extend(t)index(x) Evaluates the lowest index <strong>of</strong> the value x in the list. L.index(1.2)insert(i,x) Inserts the object x before the item i. L.insert(2,1.2)pop() Returns the last item and deletes it from the list. L.pop()remove(x) Removes the first item with the value x. L.remove(1.2)reverse() Invert the order <strong>of</strong> the items <strong>of</strong> a list. L.reverse()sort() Sort the items <strong>of</strong> list in ascending order. L.sort(t)2.12.2011


Page 34<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11A very important data object or container class which is used especiallyfrom the compiler to implement function calls is called stack.A very common error situation is the so-called stack-overflow error.This error will occur especially, if functions are called recursively. Inthis case the return addresses are pushed to the stack to remember theway back. If an address should be read from the stack, the address ispoped form the stack, which means, that the last value is read and thislast value is removed from the stack. 10 A stack is also called LIFO,i.e. Last In First Out.Figure 2.4: Stack OperationsFigure 2.5 shows the history <strong>of</strong> a stack in use.Onto the empty stack the H is pushed. The thee, the l and the o are pushed. After that the o ispoped, that means the element is returned to thecaller and removed from the stack. With two furtherpops the elements l and e are removed fromthe stack. A further push stores the w on the stack.After two pops the w and the e are removed. TheH remains on the stackFigure 2.5: Stack ExampleNow, how can we implement a stack with basic Python? We simply need a list instance with the tw<strong>of</strong>unctions append(), which implements the Push and pop() which implements the Pop <strong>of</strong> a stack.2.10.3 Working with DictionariesA dictionary is a powerful and very general container, it’s also called map, because a key value is mappedonto the pointer <strong>of</strong> the stored item. In Python an instance pointers is stored in a dictionary using anarbitrary key strings. So a dictionary is like a list container with a more general access. Because thedictionary commonly hashes the key information onto some smaller index lists, the dictionary commonlyhas a better performance as a linked list container. The dictionary therefore is used in the abaqus classlibrary (we will discuss it later) to store named instances.A dictionary can be created like a list using curled parenthesis. Each key-value pair is separated by acomma. The key is separated from the value by a colon.10 If we save data on a stack, it’s called push data onto the stack. If we take data from the stack, it’s called pop data from thestack.E. Baeck


2.11. RANDOM NUMBERS Page 35>>> myDict = {’first item’:1, ’second item’:2}>>> print myDict[’second item’]2>>>>>> beatles = {}>>> beatles[’drums’] = ’Ringo’>>> beatles[’bass’] = ’Paul’>>> beatles[’vocal’] = ’John, Paul’>>> beatles[’guitar’] = ’George, John’>>> print beatles{’guitar’: ’George, John’, ’vocal’: ’John, Paul’, ’bass’: ’Paul’,’drums’: ’Ringo’}>>>2.11 Random NumbersBecause a computer is system, which works systematically reproducible, a computer will not be able tocreate real random numbers. If we start a program twice with exact the same input values, the result alsowill be the same. But with a little trick, we can produce so called pseudo random numbers. If we usethe time as input for the initialization <strong>of</strong> our random number generator, we will be sure, that it will beextremely improbable, to get twice the same random number set.So every programing language has it’s own random number generator. Python <strong>of</strong>fers us a build-in package,which is called random. Like in C the random number generator is to initialize with a functionseed(). This function uses the computer time information to make varying starting conditions.The following example will discuss two features <strong>of</strong> the Python library.• How can we use the random package to create random numbers or to create a random order <strong>of</strong>lists, i.e. shuffle the list’s data.• How can we create simple 2d diagram plots using the matplotlib package.The example code consists <strong>of</strong> three sections.• At the beginning the lists xPos and yPos are filled with random numbers. This random x and yvalues are interpreted as point coordinates. Two subsequent points are joint by a line.• Within a second step the list’s element are sorted. The result is plotted again. The result is anincreasing function.• Within the third step the sorted lists are shuffled by the random package. The random order <strong>of</strong> therandom numbers is plotted again.Figure 2.6 shows the walk for random points (blue line), for sorted points (red line) and for shuffledpoints (green line). The left figure shows the content <strong>of</strong> the created png file, the right figure shows theplot within the viewers window.Random Walk visualized with two Lists <strong>of</strong> Random Numbers2.12.2011


Page 36<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Figure 2.6: Random, Sorted and Shuffled Walkimport randomimport pylab# import the random package# part <strong>of</strong> matplotlib# create random ’count’ numbers in the range [lower:upper]# a list is returned to the callerdef GetRandomNumbers(lower,upper,count):random.seed() # initialization <strong>of</strong> random number generatornumbers = []for i in range(count):r = lower + (upper-lower)*random.random()numbers.append(r)return numbers# main program ------------------------------L = -10. # lower boundU = +10. # upper boundxN = 100 # number <strong>of</strong> randoms# random positionsxPos = GetRandomNumbers(L,U,xN)yPos = GetRandomNumbers(L,U,xN)# ...in x-direction# ...in y-direction# creating plot <strong>of</strong> original random values xPos/yPospylab.plot(xPos,yPos,"b")# sort the random valuesxPos.sort()yPos.sort()E. Baeck


2.11. RANDOM NUMBERS Page 37# creating plot <strong>of</strong> sorted values xPos/yPospylab.plot(xPos,yPos,"r")# create a random orderrandom.shuffle(xPos)random.shuffle(yPos)# creating plot <strong>of</strong> the shuffeled values xPos/yPospylab.plot(xPos,yPos,"g")# save the plot in a figure using an png-formatpylab.savefig("RandomWalk.png")# plot a figure in the matplotlib viewerpylab.show()End <strong>of</strong> Coding2.12.2011


Page 38<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/112.12 Date, Time and TimespanDate and time functions in common are very important and therefor Python supports this with a standardpackage datetime. Within this package you will find some very simple and powerful objects andfunctions.The package is loaded with the following statement. We load from datetime the subpackage datetimeand set the alias name time. The second line shows, how to get the actual time. The datetime objectcontents from the left to the right the year, the month, the day, the hour, the minutes, the seconds andthe microseconds. Because the computer does not support microseconds but milliseconds the measuredmilliseconds are multiplied with the factor 1000.>>> from datetime import datetime as time>>> time.now()datetime.datetime(2010, 11, 4, 19, 25, 33, 15000)To implement some performance checking code it is very useful to have a timespan, which is the difference<strong>of</strong> two datetime objects. The timespan object is called timedelta and is as well an object <strong>of</strong> thedatetime package.If we now want to check the performance <strong>of</strong> a code snippet, we will implement the following code.First we have to import the datetime package. Then we get the actual time and assign this object to thevariable t1. Then the code to check follows. Within a last step we again create a datetime object callingthe time.now() function and assigning the object to the variable t2. If we subtract t1 from t2 wewill get a timedelta object. The timedelta objects contents the number <strong>of</strong> days, the number <strong>of</strong> secondsand the number <strong>of</strong> microseconds <strong>of</strong> the time difference.from datetime import datetime as timet1 = time.now()... our code snippet ...t2 = time.now()t3 = t2 -t1print t3>>> datetime.timedelta(0, 12, 906000)If we want to have the time difference in seconds, we have to write a little function, which adds all thistime parts in the unit second. If we suppose, that T is a valid timedelta object, we extract the seconds withthe seconds attribute and assign it to our seconds variable. The next part handles the microseconds.We divide them by 10 6 and add the part to the seconds variable. The last part calculates the seconds <strong>of</strong>the given hours and add this value to our second variable. The value is returned to the caller.def GetTimeSpanInSeconds(T):secs = float(T.seconds)secs += float(T.microseconds)/1.e6secs += float(t.days)*24.*60.*60.return secsOne very important application <strong>of</strong> the timedelta object is the measurement <strong>of</strong> a program’s performance.The next example shows how to investigate the performance <strong>of</strong> the creation <strong>of</strong> a tuple and the creation <strong>of</strong>a list. Here we apply the above discussed function GetTimeSpanInSeconds.Investigating the Creating Time <strong>of</strong> Tuples and Lists using a Function ApprochE. Baeck


2.12. DATE, TIME AND TIMESPAN Page 39# we need the datetime packagefrom datetime import datetime as time# calculating the timespan in floatsdef GetTimeSpanInSeconds(T):t = float(T.seconds)t+= float(T.microseconds)/1.e6t+= float(T.days)*24.*60.*60return tnX = 100000# number <strong>of</strong> entities to createT = () # empty tupleL = [] # empty list# create a tuple with nX itemst1 = time.now()for i in range(nX):T += (i,)t2 = time.now()sT = GetTimeSpanInSeconds(t2-t1) # and calculate the timespanprint "Creation <strong>of</strong> a tuple with %d items: %.3fs" % (nX,sT)# create a list with nX itemst1 = time.now()for i in range(nX):L += [i,]t2 = time.now()sL = GetTimeSpanInSeconds(t2-t1) # and calculate the timespanprint "creation <strong>of</strong> a list with %d items: %.3fs" % (nX,sL)# convert the list into a tuplet1 = time.now()TL = tuple(L)t2 = time.now()sTL= GetTimeSpanInSeconds(t2-t1) # and calculate the timespanprint "Create tuple from list: %.3fs" % sTLEnd <strong>of</strong> CodingThe console output on a one year old double processor notebook is given below. You see that it is verywasteful to create a tuple with a lot <strong>of</strong> items concatenating them with a += operator. On the other hand alist with the some number <strong>of</strong> items is created in no time. And the conversion <strong>of</strong> a list into a tuple costsnothing. So we can resume the the creation <strong>of</strong> a very large tuple should be done by creating a list and2.12.2011


Page 40<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11converting it into a tuple.c:\CM\Cm-AoS\WS1011\Python>Timecheck1.pyCreation <strong>of</strong> a tuple with 100000 items: 33.297screation <strong>of</strong> a list with 100000 items: 0.063sCreate tuple from list: 0.000s2.13 Working with FilesA file is a sequence <strong>of</strong> bytes written to an external media like a hard disk, a CD or an USB stick. A file’sbytes are indexed with an integer. So the the fist byte <strong>of</strong> a file has the index 0 and the second byte theindex 1 and so on. A text file is structured with a line break character \n. If a text line should be read,the io 11 system reads all the bytes up to the next line break.Python as a lot <strong>of</strong> functions which are able to handle every situation concerning files. So files can becreated. We can read data from a file or write data into a file. We can close a file. We can delete a file orchange it’s permissions.2.13.1 Open a FileWithin Python a file is an object an has a lot <strong>of</strong> attributes and methods (see also the next section). Theaccess to a file is initialized with the file constructor. The file constructor needs the name <strong>of</strong> the file andthe type <strong>of</strong> access. The file access type is like C’s access type <strong>of</strong> the function fopen 12 . The type ’r’ isused to read from a file, the type ’w’ is used to create a new file for writing. An old still existing filewill be deleted. The type ’a’ is used to write appending to an existing or a new file. If we want to readfrom and write into a file the type ’w+’ can be used.f = file(,)...... example ......f = file("myfile.txt", "w")2.13.2 Write Data into a FileThe file method write writes a stream <strong>of</strong> bytes into a file. In contrast to the print function the write methodadds no carriage return to the file. If a line <strong>of</strong> text should be written, the text should be closed with an \ncharacter.f.write()...... example ......f.write("This is my first line\n")11 io means input output.12 The function fopen is C’s classical function to open a file. The return will be a pointer to a FILE structure.E. Baeck


2.14. OOP WITH CLASSES Page 412.13.3 Close a FileAfter the usage <strong>of</strong> a file, the file should be closed.f.close()...... example ......f.open("log.txt","a")f.write("Write a little log line\n")f.close()2.14 OOP with ClassesPython is an object orientated programing language 13 . Everything within Python is implemented as anobject, even a simple integer number. So what is the concept <strong>of</strong> a class? A class or an object combinesdata, called attributes, with functions, called methods. This can be described by so called UML 14An instance <strong>of</strong> a class, that is the realization <strong>of</strong> the class in memory, is created simply by assigning theclass’s name followed by the constructors parameter list to a symbolic name, which than is the pointer orthe reference to this instance. Within the class the self pointer to the actual instance is called self. Toaccess member attributes or methods <strong>of</strong> a class the dot notation is used, i.e. ..We can remove an instance <strong>of</strong> a class by calling the del operator (del example). The referencesto an instance are handled by the python runtime system. If an instance has lost all it’s references, theinstance is removed from the memory. 152.14.1 Some UML DiagramsUML structure diagrams <strong>of</strong> the emphasize the things that must be present in the system being modeled.Since structure diagrams represent the structure they are used extensively in documenting the architecture<strong>of</strong> s<strong>of</strong>tware systems. In our description <strong>of</strong> the examples we want to implement we use the ClassDiagram which describes the structure <strong>of</strong> a system by showing the system’s classes, their attributes, andthe relationships among the classes.A UML class diagram (see figure 2.7) consists <strong>of</strong> a rectangular box, which is dividedinto three sections. The fist section contents the class’s name. This nameis written centered in bold letters. The second section contents the attribute’snames <strong>of</strong> the class and the third section contents the method’s names.Class Nameattribute 1attribute 2method 1method 2Figure 2.7: A UMLClass Diagram13 Object orientated Programming is <strong>of</strong>ten used with the abbreviation OOP.14 The Unified Modeling Language includes a set <strong>of</strong> graphic notation techniques to create visual models <strong>of</strong> s<strong>of</strong>tware-intensivesystems. The Unified Modeling Language is an international standard see [4], UML 2.3 was formally released in May 2010.15 This is also called Garbage Collector. In contrast to this in poor C or C++ an once allocated object has to be removedexplicitly from the memory to avoid so called memory leaks, this are blocked parts <strong>of</strong> the applications memory, which remainunaccessible until the application is closed.2.12.2011


Page 42<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11A UML note diagram (see figure 2.8) consists <strong>of</strong> a stylized note sheet which isfilled with some information.This is onlya simple NoteFigure 2.8: A UML NoteDiagramClass Nameattribute 1attribute 2method 1method 2This isClass 1A UML note diagram (see figure 2.9) will be assigned to another component <strong>of</strong> the diagram scene with a simple line.Figure 2.9: A UML Note Diagram AssignmentFigure 2.10 shows how to draw diagrams for inheriting classes. An arrow witha white filled arrowhead points from the inheriting class, the special class, tothe inherited class, the base class. The attributes and the methods <strong>of</strong> the Baseclass are now available in the name space <strong>of</strong> the inheriting class, i.e. the specialclass now has the attributes attributB1, attributB2, attributS1 andattributS2.Base ClassattributeB1attributeB2methodB1methodB2Special ClassattributeS1attributeS2methodS1methodS2Class 1List AList Bmethod 1*Figure 2.10: A UMLInheritance DiagramClass Aattribute A1attribute A2method A12..*Class Battribute B1attribute B2method B1..*Figure 2.11: A UML Diagram for a Composition andan AggregationFigure 2.11 shows a aggregation and a composition.An aggregation is drawn by a white filled rhombus.An composition is drawn by a black filled rhombus.Aggregation and compositions describe a containeror a list <strong>of</strong> several instances <strong>of</strong> an object, which aremembers <strong>of</strong> a main class. If for example a pr<strong>of</strong>ileconsists <strong>of</strong> several parts, the parts can be described asan composition, if a part only exists within a pr<strong>of</strong>ile.If a part exists also without a pr<strong>of</strong>ile, the parts aredescribed within the pr<strong>of</strong>ile with an aggregation.At the ends <strong>of</strong> the connecting lines the multiplicities are noted. The multiplicity gives the range <strong>of</strong>referenced instances in the form from..to. For the Class A we have 2 up to infinite instances in ancomposition, therefor at the end <strong>of</strong> the line we can not have a multiplicity <strong>of</strong> zero. In our examplewe have exactly one instance <strong>of</strong> the class 1. On the other hand Class B is referred to Class 1 withinan aggregation. In our example on instance <strong>of</strong> Class B can be reverenced by an undefined number <strong>of</strong>instances <strong>of</strong> Class 1. This is shown by the * icon. On the other hand the class 1 references at least oninstance <strong>of</strong> the Class B. Otherwise the number <strong>of</strong> references is arbitrary. This is also shown by the *icon.E. Baeck


2.14. OOP WITH CLASSES Page 432.14.2 Implementation <strong>of</strong> a Time Stack ClassIn section 2.12 we have discussed a little program which implements a time checker using a stack container.We can implement this problem in a much more clearer version, if we do it in terms <strong>of</strong> the OOPapproach. The class TimeCheck, which is introduced, encapsulates the time stack list and the log filesname as attributes and the following methods.• Set reads the actual time with the datetime.now() and pushes it onto the time stack.• Get reads the actual time with the datetime.now(), pops the the last time object from the stack andcalculates the timespan. The timespan is optionally printed into the console window or into a logfile.• GetTime calculates the seconds in floats form the passed timedelta object.The main program, which is used to discuss the class follows the steps <strong>of</strong> the classical implementation<strong>of</strong> the problem discussed in section 2.12. We first create an empty tuple and an empty list. Than wecreate the TimeCheck instance 16 simple by assigning it’s name to a variable (s = TimeCheck()). Topush a time object onto the stack, we call the class’s member function Set. So, if we want to check theperformance <strong>of</strong> a code, we first call the Set method and after having executed the code, we call the Getmethod. The Get method will print the comment and will return the used seconds <strong>of</strong> execution time infloats. The simplest kind <strong>of</strong> an implementation is the implementation in the file <strong>of</strong> the main program.This you can see in the following example.A UML diagram <strong>of</strong> the class TimeCheck is given in figure 2.12.TimeCheckself. log: name <strong>of</strong> the log fileself. stack: stack listself. init (..): contructorself.Set(..): push a timeself.GetTime(..): calculate secondsself.Get(..): pop a timeThe class TimeCheck contentsall the data and functions touse a time stack and to get thetime-span information in a properfloat format. The class is able topresent a formated output <strong>of</strong> themeasured time-spans.Figure 2.12: UML-Diagram <strong>of</strong> the TimeCheck ClassOOP Implementation <strong>of</strong> the Time Checking Problem’’’Class to investigate the timespan, to measure the performanceby implementing a time stack container’’’# - module - member aliasfrom datetime import datetime as time # we need the datetime packageclass TimeCheck():# class name# constructor16 A physical created object in memory <strong>of</strong> a class is called instance <strong>of</strong> a class.2.12.2011


Page 44<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11definit (self,log = "timestack.log"):self. stack = [] # empty listself. log = log # set the logfile’s name# set up the actual time and push it onto the stackdef Set(self):self. stack.append(time.now())# calculate the timespan in floatdef GetTime(self,T):s = float(T.microseconds)/1.e6 +float(T.seconds) +float(T.days)*24.*60.*60.return s# calculate the timespan with a stack objectdef Get(self,text = ""):# get the stack lengthitems = len(self. stack)# assert(items > 0) # to assert, that there is a time object# stored in stack (alternative solution)if items < 1:print "*** Error: timestack empty!"returntStart = self. stack.pop()# pop the time object from the stacktEnd = time.now() # get the end timetDel = self.GetTime(tEnd -tStart) # calculate the timedelta in floats# we have an maximal indent <strong>of</strong> 6 columnsindent = 6space1 = ""# leading characters for level indentspace2 = ""# trailed characters to aling the comment# set up indent textfor i in range(items-1): space1 += "." # fill in dotsfor i in range(indent -items): space2 += " " # fill in white spaces# print comment if givenif len(text) > 0:textout = "%s %8.3f%s: %s" % (space1,tDel,space2,text)# comment to the screenprint textoutE. Baeck


2.14. OOP WITH CLASSES Page 45# logging the commentf = file(self. log,"a")f.write(textout + "\n")f.close()return tDel# return the seconds in floats# application <strong>of</strong> the TimeCheck classprint ">> Start.."nX = 50000T = () # empty tupleL = [] # empty list# create the timecheck objects= TimeCheck()# check the total performances.Set()# check the performance <strong>of</strong> the tupless.Set()for i in range(nX): T+= (i,)s.Get("Creating %d item tuple." % nX)# check the performance <strong>of</strong> the lists.Set()for i in range(nX): L+= [i]s.Get("Creating %d item list." % nX)# check the whole performances.Get("total time")End <strong>of</strong> CodingIf we run the program, we see that two time stamps are indented with one dot. This timestamps are setfor inner performance measurements, that is the time-stamp for the creation <strong>of</strong> the tuple and after thatthe time-stamp for the the creation <strong>of</strong> the list. The last time-stamp shows the total execution time and iscreated by the first push, i.e. the first Set call and the last pop, i.e. the last Get call.>> Start... 8.282 : Creating 50000 item tuple.. 0.016 : Creating 50000 item list.8.329 : total time2.12.2011


Page 46<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11E. Baeck


3Python Projects3.1 Newton, Step2We have discussed the newton’s scheme in section 2.9. Within this section the project’s code will beextended by plot features. The function and it’s derivative as well as the path <strong>of</strong> iteration will be plottedusing the PyLab package.The following features are added to the implementation <strong>of</strong> newton’s scheme.1. Import the PyLab package.2. The function GetFunctionValues creates a list <strong>of</strong> the function values for the plot routine.3. The function GetFunctionDerivativeValues creates a list <strong>of</strong> the function’ derivative values for theplot routine.4. The function Newton will be extended by two lists, which should store the values <strong>of</strong> the iterationpath. After each iteration step, the x-value and it’s function value are stored for later drawings.Newton’s Algorithm, Step 2import pylabfrom math import fabs as abs# plot a little (not used in this step)# import the fabs as abs# implementation <strong>of</strong> the function <strong>of</strong> interestdef Myf(x):return x**2 -1.# calculating the derivativedef fs(f,x,h=1.e-6):h = float(h)x = float(x)return (f(x+0.5*h) - f(x-0.5*h))/h# implementation <strong>of</strong> a newton algorithm47


Page 48<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11def newton(f,x0,e=1.e-10,h=1.e-6,imax=100):error = None# initialize the error code with Noneh = float(h) # we need some floatse = float(e)x1= float(x0) # x to interatexL= []yL= []# list for x-values# list for the function values for xi = 1while True:# iteration counterf0 = f(x1)# function’s valuexL.append(x1)yL.append(f0)# save x Value# save the functions valueif abs(f0) < e:break# calculating the derivativef1 = fs(f,x1,h)if abs(f1) < e:error = "*** Error: vanishing derivate!"break# available iterations exceededif i >= imax:error = "*** Error: no root found!"break# calculating the values for next iterationx1 -= f0/f1# increment the iteration counteri+=1# return the actual position, the function value# and the functions slope, the number <strong>of</strong> performed# iterations and the error code.# index 0 1 2 3 4 5 6return (x1,f0,f1,i,error,xL,yL)E. Baeck


3.1. NEWTON, STEP2 Page 49# creating a list <strong>of</strong> function values for a x-listdef GetFunctionValues(xL,f):yL = []for x in xL:y = f(x)yL.append(y) # yL += [y]return yL# create a list <strong>of</strong> function’ derivative valuesdef GetFunctionDerivateValues(xL,f):yL = []for x in xL:y = fs(f,x)yL.append(y)return yL# parameters <strong>of</strong> the problemxl = -5. # lower boundxu = 5. # upper boundxc = 0.5 # increment# visalization <strong>of</strong> the function and it’s derivative# create the x-ListxList = pylab.arange(xl,xu,xc)# create list <strong>of</strong> function’s valuesyList = GetFunctionValues(xList,Myf)pylab.plot(xList,yList,’b’)# create list <strong>of</strong> function’s derivative valuesysList = GetFunctionDerivateValues(xList,Myf)pylab.plot(xList,ysList,’g’)# the function newton is called with standard parameters# we pass the function <strong>of</strong> interest and a supposed start# positionres = newton(Myf,4.)# the returned tuple is printed into the console windowprint "\n> next run"print "x = %f" % res[0] # last x value2.12.2011


Page 50<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11print "f(x) = %f" % res[1] # last f(x) valueprint "f’(x) = %f" % res[2] # last f’(x) valueprint "i = %d" % res[3] # number <strong>of</strong> iterationsif res[4] is not None:print "%s" % res[4] # error messageprint "--- end <strong>of</strong> code ---\n"# plot the iteration pathpylab.plot(res[5],res[6],’rp’)# output <strong>of</strong> plot datapylab.grid(True)# show grid linespylab.savefig("NewtonStep2.png")# - show plot datapylab.show()End <strong>of</strong> CodingAfter the output lists are created the lists are passed to the plot postprocessor by the plot method <strong>of</strong>PyLab. After enabling the grid the plot data are written in a graphic file and are visualized in the PyLabviewer application.Figure 3.1 shows the iteration path for the equation f (x) = x 2 − 1 with an starting value <strong>of</strong> 4 with reddots.Figure 3.1: Newton’s Iteration PathE. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 513.2 Pr<strong>of</strong>iles, Thin Walled ApproachIn this section we will implement a class hierarchy to model a pr<strong>of</strong>ile’s data. We will implement logginginto file and screen in a common base class and we will implement the thin walled approach to analyzeand calculate the pr<strong>of</strong>ile’s section properties.3.2.1 Implementation <strong>of</strong> a general Pr<strong>of</strong>ile ClassesSo if we want to develop a s<strong>of</strong>tware, which is able to calculate the pr<strong>of</strong>ile’s section properties like it’sarea, moment <strong>of</strong> inertia and so on, we can consequently split up the problem in general and specific parts.So we start with the data and the functions <strong>of</strong> a general object. This data is collected in a class whichwe call Base. So if we want to describe a wide range <strong>of</strong> pr<strong>of</strong>ile types, then we should think about thepr<strong>of</strong>ile’s common features. Every pr<strong>of</strong>ile has a name and therefore this name is a common feature. Thiscommon features are collected in a general pr<strong>of</strong>ile class which is called Pr<strong>of</strong>iles. If we want to handle aspecific pr<strong>of</strong>ile type like an U-pr<strong>of</strong>ile ore a tube pr<strong>of</strong>ile, we collect the specific type dependent featuresin the classes UPr<strong>of</strong>ile and TubePr<strong>of</strong>ile.Baselog: global log file namecount: global instance counterself. init (..): constructorself.AppendLog(..): write to logPr<strong>of</strong>ileself. name: The pr<strong>of</strong>ile’s nameself. PL: Point containerself. LL: Line containerself. init (..): constructorself.List(..): List pr<strong>of</strong>iles valuesself.AddPoint(..): insert a new Pointself.AddLine(..): insert a new Lineself.GetLength(..): distance between to pointsself.GetArea(..): calculate pr<strong>of</strong>ile’s areaself.View(..): views a pr<strong>of</strong>ile plotUPr<strong>of</strong>ileself. h: pr<strong>of</strong>ile’s heightself. w: pr<strong>of</strong>ile’s withself. t: pr<strong>of</strong>ile’s thicknessself. init (..): constructorself.List(..): list pr<strong>of</strong>iles valuesself.Create(..): create thin walled modelTubePr<strong>of</strong>ileself. d: pr<strong>of</strong>ile’s diameterself. t: pr<strong>of</strong>ile’s thicknessself. init (..): constructorself.List(..): list pr<strong>of</strong>iles valuesThe class Base contentscommon features which are usedin every class.The class Pr<strong>of</strong>ile contentsall common features <strong>of</strong> a pr<strong>of</strong>ileespecially the containers for thePoints and Lines <strong>of</strong> shape modellThe class UPr<strong>of</strong>ile contentsthe special features <strong>of</strong> a U-Pr<strong>of</strong>ile,especially the geometric parameters.The class TubePr<strong>of</strong>ile contents thespecial features <strong>of</strong> a Tube-Pr<strong>of</strong>ile,especially the geometric parametersFigure 3.2: Some UML-Diagrams for the Pr<strong>of</strong>ile HierarchyFigure 3.2 shows in the left column the UML class diagrams, which starts with the name <strong>of</strong> the class.The second box contents the classes attributes and the third box contents the classes methods. The rightcolumn contents note diagrams. A note diagram is like a help page which gives some comments and2.12.2011


Page 52<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11elucidations.If we want to develop reusable code, it’s recommended to create a separate file for every class and putthem into a package. A package is a folder with the package’s name. So we introduce a folder calledPr<strong>of</strong>iles. To initialize a package we have to create a file named __init__.py in this folder. If thepackage is loaded, the __init__.py is executed.This file is executed, when the Pr<strong>of</strong>ile package is loaded.# This script is executed only once, if the package is loaded.# So we print a little to show what’s going onprint ">> Package ’Pr<strong>of</strong>iles’ is loaded"End <strong>of</strong> CodingIn our Pr<strong>of</strong>iles class Base we implement the common features <strong>of</strong> our package classes. The class Basecounts the instances using the global class attribute __count. A common logging method is implemented.So the name <strong>of</strong> the log file is implemented as a class method (not an instance method) __log.The method AppendLog is implemented as a general logging function. The actual time is called ancopied as heading for our logging comment. Then the completed logging text is written into the log fileand into the screen.Base class <strong>of</strong> all package classes’’’Base class for general attributes and methodes <strong>of</strong> the packages’s classes.Every class <strong>of</strong> this package will be derivated from this class’’’# we need the datetime for the log’s timestampfrom datetime import datetime as timeclass Base:log = "pr<strong>of</strong>iles.log" # standard log file name for all instancescount = 0# counter for the class’s instances# - optional we can set up the log’s file namedef init (self,log = ""):Base. count += 1 # increment the instance counterif len(log) > 0: Base. log = logself.AppendLog(">> Instance %d created" % Base. count)# general logging methode# - we pass the text to logdef AppendLog(self,text):E. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 53t = time.now() # get actual timetstamp = "%2.2d.%2.2d.%2.2d|" % (t.hour,t.minute,t.second)textout = tstamp + text # copy the stamp in front <strong>of</strong> the commentf = file(Base. log,"a")f.write(textout + "\n")f.close()# open the log file for appending "a"# write the text into the file with linebreak# close the log, to save the data on discprint textout# write the log to the screenEnd <strong>of</strong> CodingIf we want to use the code <strong>of</strong> an existing class within a new class, we can inherit this old class and useit as a base class. That means, that the new class contents also the attributes and the methods <strong>of</strong> the oldone. A base class is used in the class statement as an argument. A class can inherit more than one class.Because we implement the new class Pr<strong>of</strong>ile within the Pr<strong>of</strong>iles package, we only have to import themodule base, i.e. the file base.py. From this module we import the class Base. So we can write theimport statement as follows.from . import as The class pr<strong>of</strong>ile now contents common pr<strong>of</strong>ile features. One <strong>of</strong> them is the pr<strong>of</strong>ile’s name. Note,if we inherit a class from a base class, we have to call the base class’s constructor method. Everyattribute and every method <strong>of</strong> the base class is now available. A second feature <strong>of</strong> the Pr<strong>of</strong>ile class is theimplementation <strong>of</strong> the thin walled model. Therefore we introduce a line and a point container using theAList class. With a specific method we insert point and line instances into the container. To calculate thesection values <strong>of</strong> the created thin walled model we introduce a method to calculate the distance betweento points and a further method to calculate the line’s area, which is given by the product <strong>of</strong> line length andline thickness. At least we introduce a little viewing method, which should create a png picture file <strong>of</strong> thepr<strong>of</strong>ile and should optionally start the pylab viewer tool. To be sure, that the environment supports theTkinter package 1 , which is used by the viewer, we import the package using a try: ... except:handler.Pr<strong>of</strong>ile, a common base class for all pr<strong>of</strong>ile classes’’’General Pr<strong>of</strong>ile class, derivated from the package’s Base class’’’from Base import Base # the pr<strong>of</strong>ile’s base classfrom AList import AList # container for points/linesfrom Point import Point # a point classfrom Line import Line # a line class1 We will see later trying to apply our package Pr<strong>of</strong>iles in the frame <strong>of</strong> the Abaqus scripting, that we will get problems,because the Abaqus environment is not developed with Tkinter.2.12.2011


Page 54<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11from mathimport sqrt as sqrtclass Pr<strong>of</strong>ile(Base):# Pr<strong>of</strong>ile inherits Basedef init (self,name): # each pr<strong>of</strong>ile will have a nameBase. init (self) # call base class contructorself. name = name # pass the the name <strong>of</strong> the pr<strong>of</strong>ileself. PL = AList() # List <strong>of</strong> pointsself. LL = AList() # Line listdef AddPoint(self,No,y,z):p = Point(No,y,z)self. PL.Add(No,p)# create a new point# add the point to listdef AddLine(self,No,nA,nB,t):# first calculate the line’s lengthL = self.GetLength(nA,nB)l = Line(No,nA,nB,t,L) # create a new lineself. LL.Add(No,l) # add the line to listdef GetLength(self,nA,nB): # calculate distance between pointsdy = self. PL[nA]. x[0] - self. PL[nB]. x[0]dz = self. PL[nA]. x[1] - self. PL[nB]. x[1]return sqrt(dy*dy + dz*dz)def GetArea(self):# calculate pr<strong>of</strong>ile’s areaA = 0.for line in self. LL: # over the linesif line is not None: # only for valid objectsA += line. t * line. Lreturn A# return the area valuedef List(self):# print the pr<strong>of</strong>ile’s dataself.AppendLog(" Name: %s" % self. name)self.AppendLog(" %d Points" % len(self. PL))self. PL.List()self.AppendLog(" %d Lines" % len(self. LL))self. LL.List()def View(self,viewer = True):try:import pylab# try to import the pylab# import for plottingsE. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 55except:self.AppendLog("*** Error: yplab could not be loaded!")returnlines = []# list for the lines to plotfor line in self. LL: # iterate the line containerif line is not None: # only for valid objects# point nrx1 = self. PL[line. p[0]]. x[0]x2 = self. PL[line. p[1]]. x[0]y1 = self. PL[line. p[0]]. x[1]y2 = self. PL[line. p[1]]. x[1]# ---- line -----# x-List y-Listlines += [ [[x1,x2], [y1,y2]] ]# plot the list itemsfor line in lines:pylab.plot(line[0],line[1],’b’)# plot pointfor line in lines:pylab.plot(line[0],line[1],’rp’)# configure the plot layoutpylab.title(self. name)pylab.axis(’equal’)pylab.grid(True)pylab.savefig(self. name + ".png")if viewer: pylab.show()End <strong>of</strong> CodingIf we now want to use the package we have to create a new main program. The main program to showthe usage <strong>of</strong> our new classes is given below.Simple test program for the usage <strong>of</strong> the pr<strong>of</strong>ile class# Package |Module Class Aliasfrom Pr<strong>of</strong>iles.Pr<strong>of</strong>ile import Pr<strong>of</strong>ile as pr<strong>of</strong>u100 = pr<strong>of</strong>("U100")2.12.2011


Page 56<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11u120 = pr<strong>of</strong>("U120")End <strong>of</strong> CodingA class hierarchy UML diagram is given in figure 3.3.Baselog: global log file namecount: global instance counterself. init (..): constructorself.AppendLog(..): write to logPr<strong>of</strong>ileself. name: The pr<strong>of</strong>ile’s nameself. PL: Point containerself. LL: Line containerself. init (..): constructorself.List(..): List pr<strong>of</strong>iles valuesself.AddPoint(..): insert a new Pointself.AddLine(..): insert a new Lineself.GetLength(..): distance between to pointsself.GetArea(..): calculate pr<strong>of</strong>ile’s areaself.View(..): views a pr<strong>of</strong>ile plotUPr<strong>of</strong>ileself. h: pr<strong>of</strong>ile’s heightself. w: pr<strong>of</strong>ile’s withself. t: pr<strong>of</strong>ile’s thicknessself. init (..): constructorself.List(..): list pr<strong>of</strong>iles valuesself.Create(..): create thin walled modelTubePr<strong>of</strong>ileself. d: pr<strong>of</strong>ile’s diameterself. t: pr<strong>of</strong>ile’s thicknessself. init (..): constructorself.List(..): list pr<strong>of</strong>iles valuesFigure 3.3: Class Hierarchy Diagram <strong>of</strong> the Pr<strong>of</strong>iles Package3.2.2 Implementation <strong>of</strong> basic Classes for a Thin Walled ModelThe simplest approach to calculate the pr<strong>of</strong>ile’s cross section values (area, moments <strong>of</strong> inertia, the center<strong>of</strong> mass, etc.) is given by the thin walled model, a one dimension approximation <strong>of</strong> the pr<strong>of</strong>iles geometry.The pr<strong>of</strong>ile is described only by points and lines like in the finite element approach. Therefore weintroduce a point as well as a line class (see figure 3.4). To hold the desired point and line informationwe implement a slightly modified list class, which should work like an array with a well defined indexaccess. If we use a standard list class, we will get problems if we want to insert an object at a positionoutside the list range. Then a standard list object simply appends this object as a new item at the tail<strong>of</strong> the list and we would loose the correct index position. So we implement a new Add method, whichchecks the list length and if necessary enlarges the list up to the desired index position.Figure 3.5 shows the pr<strong>of</strong>ile class’s UML diagram with the composition <strong>of</strong> the point and line class. TheUML diagram shows, that thin-walled model consists <strong>of</strong> minimally 2 points and one line. The code <strong>of</strong>the Point class is given below.E. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 57Pointn: point numberx[]: List for point coordinatesself. init (..): constructorself.List(..): print point dataLinen: line numberp[]: List <strong>of</strong> point numberst: line’s thicknessL: line’s lengthself. init (..): constructorself.List(..): print line dataAListno attributesself. init (..): constructorself.Add(..): Add by indexself.List(..): print instance’s dataThe class Point contentsthe coordinates and the number <strong>of</strong>a pr<strong>of</strong>ile’s point.The class Line contentsthe line’s point data and the line’sthickness.The class AList is based on aa list. The Add method adds an objectwith a given index value.Figure 3.4: Some UML-Diagrams for Pr<strong>of</strong>ile Points and LinesPr<strong>of</strong>ileself. name: The pr<strong>of</strong>ile’s nameself. PL: Point containerself. LL: Line containerself. init (..): constructorself.List(..): List pr<strong>of</strong>iles valuesself.AddPoint(..): insert a new Pointself.AddLine(..): insert a new Lineself.GetLength(..): distance between to pointsself.GetArea(..): calculate pr<strong>of</strong>ile’s areaself.View(..): views a pr<strong>of</strong>ile plot112..*Pointn: point numberx[]: List for point coordinatesself. init (..): constructorself.List(..): print point data1..*Linen: line numberp[]: List <strong>of</strong> point numberst: line’s thicknessL: line’s lengthself. init (..): constructorself.List(..): print line dataFigure 3.5: UML-Diagram <strong>of</strong> the Pr<strong>of</strong>ile Composition2.12.2011


Page 58<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Class <strong>of</strong> a Pr<strong>of</strong>ile Pointfrom Base import Base# the Point class is inherited from the Baseclass Point(Base):def init (self,no,y,z): # The Point is created passing the point numberBase. init (self)# and the coordinates. The constructor <strong>of</strong> the# Base class is called.self. no = noself. x = [y,z] # the coordinates are stored in the lisdef List(self):# print the point’s dataself.AppendLog(" Point: %3d, y= %10.3f, z= %10.3f" % (self. no,self. x[0],self. x[1]))End <strong>of</strong> CodingThe following code shows the code <strong>of</strong> Line class.Class <strong>of</strong> a Pr<strong>of</strong>ile Linefrom Base import Base# Line inherits Baseclass Line(Base):def init (self,No,nA,nB,t,L): # we pass the number, point# numbers and the thicknessBase. init (self)# first we call the base class’s constructorself. No = Noself. p = [nA,nB] # the point numbers are store in a listself. t = tself. L = L # the line length is calculated according to# the thin walled approachdef List(self):# the list method calls the base class’s AppendLogself.AppendLog(" Line: %3d, A= %3d, B= %3d, t= %7.3f" % \(self. No,self. p[0],self. p[1],self. t))End <strong>of</strong> CodingThe following code shows the code <strong>of</strong> the container class ALast. In a first version the class AList inheritsthe content <strong>of</strong> the class Base. The python buildin container class list is used as an attribute _L. Theaccess to the container is handled with access methods.E. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 59from Base import BaseCode <strong>of</strong> the class AList Version 1# Version 1 <strong>of</strong> the AList class inheritingclass AList(Base):definit (self):Base. init (self)self. L = []# call the Base constructor# the list is used as an attributdef Add(self,No,obj):# adds an object reference with an indexUBound = len(self. L) -1 # get largest valid indexif No > UBound:# if the list is undersized extendfor i in range(UBound+1,No +1): # to the used lengthself. L += [None,] # add a new item to the listself. L[No] = obj# the save the referenceself.AppendLog(">> New Length: %d Items in List" % len(self. L))# the List method calls the List method <strong>of</strong> it’s items# if there is no item, the case is handled with an exception blockdef List(self):iobj = 0# initialize the object counterfor obj in self. L: # iterate the slots <strong>of</strong> the listtry:# open the try blockobj.List() # try to list an objectexcept:# if not possible log it to the log fileself.AppendLog(" Error: No object in slot %d" % iobj)iobj += 1# increment the counterEnd <strong>of</strong> CodingThe following code shows the code <strong>of</strong> the container class ALast. In a second version the class AListinherits besides the class Base the buildin class list. The advantage comparing this version with themember implementation <strong>of</strong> a list is, that the class AList will have exactly the same interface a the buildinclass list.Code <strong>of</strong> the class AList Version 2from Base import Base# the AList class should inherit the Base class# Version 2 <strong>of</strong> the AList class inheriting the buildin# object "list" tooclass AList(Base,list):2.12.2011


Page 60<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11definit (self):Base. init (self)# call the Base constructordef Add(self,No,obj): # adds an object reference with an indexUBound = len(self) -1 # get largest valid indexif No > UBound:# if the list is undersized extendfor i in range(UBound+1,No +1): # to the used lengthself += [None,]self[No] = obj# the save the referenceself.AppendLog(">> New Length: %d Items in List" % len(self))# the List method calls the List method <strong>of</strong> it’s items# if there is no item, the case is handled with an exception blockdef List(self):iobj = 0# initialize the object counterfor obj in self:# iterate the slots <strong>of</strong> the listtry:# open the try blockobj.List() # try to list an objectexcept:# if not possible log it to the log fileself.AppendLog(" Error: No object in slot %d" % iobj)iobj += 1# increment the counterEnd <strong>of</strong> CodingTo check the package code, we create an instance <strong>of</strong> the Point and the Line class. The instances’ dataare printed with their list method. Then a AList instance is created and the Point and Line instances areinserted into to AList instance. Then the AList’s data are printed.Within a second step a Pr<strong>of</strong>ile instance is created. We add two Point instances and one Line instance toPr<strong>of</strong>ile instance and print the Pr<strong>of</strong>ile instance’s data.Code for a first Check <strong>of</strong> the Pr<strong>of</strong>ile Package’’’Test program for Point, Line and AList class’’’# -package-module classfrom Pr<strong>of</strong>iles.Point import Pointfrom Pr<strong>of</strong>iles.Line import Linefrom Pr<strong>of</strong>iles.AList2 import AListfrom Pr<strong>of</strong>iles.Pr<strong>of</strong>ile import Pr<strong>of</strong>ilep = Point(1,1.1,2.1)p.List()# create a point and# list the point’s datal = Line(2,10,11,2.5)# create a line andE. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 61l.List()# list the line’s dataLA = AList()# create a AList instanceLA.Add(0,p) # save the point at slot 0LA.Add(3,l) # save the line at slot 1LA.List()# list the AList’s data# create a Pr<strong>of</strong>ile instancepr<strong>of</strong> = Pr<strong>of</strong>ile("Test Pr<strong>of</strong>ile")pr<strong>of</strong>.AddPoint(0,0.1,0.2) # add a Point to the pr<strong>of</strong>ilepr<strong>of</strong>.AddPoint(2,2.1,2.2) # add a 2nd Point to the pr<strong>of</strong>ilepr<strong>of</strong>.AddLine(0,0,2,1.5) # add a Line to the pr<strong>of</strong>ilepr<strong>of</strong>.List()# list all the stored dataEnd <strong>of</strong> CodingThe following output will be written to screen and into a file, if the check script will be executed. Theoutput shows, that first the package is loaded with the control string <strong>of</strong> the __init__.py module. Ifan instance is created the instance counter is logged.>> Package ’Pr<strong>of</strong>iles’ is loaded20.21.47|>> Instance 1 created20.21.47| Point: 1, y= 1.100, z= 2.10020.21.47|>> Instance 2 created20.21.47| Line: 2, A= 10, B= 11, t= 2.50020.21.47|>> Instance 3 created20.21.47|>> New Length: 1 Items in List20.21.47|>> New Length: 4 Items in List20.21.47| Point: 1, y= 1.100, z= 2.10020.21.47| Error: No object in slot 120.21.47| Error: No object in slot 220.21.47| Line: 2, A= 10, B= 11, t= 2.50020.21.47|>> Instance 4 created20.21.47|>> Instance 5 created20.21.47|>> Instance 6 created20.21.47|>> Instance 7 created20.21.47|>> New Length: 1 Items in List20.21.47|>> Instance 8 created20.21.47|>> New Length: 3 Items in List20.21.47|>> Instance 9 created20.21.47|>> New Length: 1 Items in List20.21.47| Name: Test Pr<strong>of</strong>ile20.21.47| 3 Points20.21.47| Point: 0, y= 0.100, z= 0.20020.21.47| Error: No object in slot 120.21.47| Point: 2, y= 2.100, z= 2.20020.21.47| 1 Lines2.12.2011


Page 62<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11To next script implements a little testing environment for the usage <strong>of</strong> the classes UPr<strong>of</strong>ile and Pr<strong>of</strong>ile<strong>of</strong> the Pr<strong>of</strong>iles package. A UPr<strong>of</strong>ile instance will be created with the data <strong>of</strong> an U100 pr<strong>of</strong>ile. Thethin walled model will be created automatically within the constructor <strong>of</strong> the UPr<strong>of</strong>ile instance. Thenthe whole data <strong>of</strong> the pr<strong>of</strong>ile will be written to the screen and into the log file using the base classesAppendLog method. Then the area <strong>of</strong> the pr<strong>of</strong>ile model will be created and printed. At last using theView method <strong>of</strong> the inherited class Pr<strong>of</strong>ile a picture file is written and the PyLab viewer is started.Figure 3.6 shows the viewers window as well as the picture file’s content. The blue lines are the centerlines<strong>of</strong> the pr<strong>of</strong>ile parts, i.e. the lines. The red dots are the points <strong>of</strong> the thin walled model. We see thatheight and width are reduced by the thickness values.Testing Script for the Classes UPr<strong>of</strong>ile and Pr<strong>of</strong>ile’’’The test environment implements the creation<strong>of</strong> a U100 pr<strong>of</strong>ile, the listing <strong>of</strong> it’s dataand the creation <strong>of</strong> it’s model picture’’’# package module classfrom Pr<strong>of</strong>iles.UPr<strong>of</strong>ile import UPr<strong>of</strong>ile# create the instance <strong>of</strong> an U-Pr<strong>of</strong>ilepr<strong>of</strong> = UPr<strong>of</strong>ile("U100",100.,50.,6.0,8.5)# and check itpr<strong>of</strong>.List()# calculate the area and print it in cmˆ2Acm2 = pr<strong>of</strong>.GetArea()/100.pr<strong>of</strong>.AppendLog(" Area: %10.3f cmˆ2" % Acm2)# plot and view the pr<strong>of</strong>ile’s geometrypr<strong>of</strong>.View()End <strong>of</strong> Coding3.2.3 Implementation <strong>of</strong> a little Pr<strong>of</strong>ile DatabaseTo implement a simple pr<strong>of</strong>ile data base for arbitrary pr<strong>of</strong>ile instances, we can simply use the Pythonbuildin object dict 2 and extend it by inheritance with a specific list method (see figure 3.7). The listiterates the dictionary getting the keys <strong>of</strong> the stored instances. With the given key we get the instancepointer from the dictionary. Then we can use the mechanism <strong>of</strong> the polymorphism and call the instancesspecific list method. If there is an error occurring, the try/except error handler will do his job andexecutes the except branch code. So we can avoid program crashing due to invalid ore missing pointers.2 A dictionary is used to store instance pointers with an arbitrary access key.E. Baeck


3.2. PROFILES, THIN WALLED APPROACH Page 63Figure 3.6: Picture <strong>of</strong> an U100 Pr<strong>of</strong>ile ModelPr<strong>of</strong>DBno attributesself. init (..): constructorself.List(..): print instance’s dataThe class Pr<strong>of</strong>DB is based on aa dictionary. Pr<strong>of</strong>ile instances areare stored like in a database.Figure 3.7: UML-Diagram <strong>of</strong> the Pr<strong>of</strong>ile DatabaseThe code <strong>of</strong> the Pr<strong>of</strong>DB class is given below.Class Pr<strong>of</strong>DB to implement a simple Pr<strong>of</strong>ile Databasefrom Base import Base# the Pr<strong>of</strong>DB class should inherit the Base class# The Pr<strong>of</strong>DB class should store arbitray pr<strong>of</strong>ile objects in# a dictionary. Therefore we inherit from the buildin dict objectclass Pr<strong>of</strong>DB(Base,dict):definit (self):Base. init (self)# call the Base constructor# the List method calls the List method <strong>of</strong> it’s items# if there is no item, the case is handled with an exception blockdef List(self):iobj = 0# initialize the object counterfor name in self:# iterate the keys <strong>of</strong> the dictionarytry:# open the try blockself[name].List() # try to list an objectexcept:# if not possible log it to the log fileself.AppendLog(" Error: No pr<strong>of</strong>ile key %s found, slot %d" % \(name,iobj))iobj += 1# increment the counterEnd <strong>of</strong> Coding2.12.2011


Page 64<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11To check the database class Pr<strong>of</strong>DB we write a little script, which first creates a Pr<strong>of</strong>DB instance. Thenwe create a UPr<strong>of</strong>ile instance with the values <strong>of</strong> the U100. This instance is stored in the dictionary usingthe key <strong>of</strong> it’s name U100. Then we create a second UPr<strong>of</strong>ile instance with the values <strong>of</strong> the U140 andstore it as well in the dictionary using it’s name U140 as it’s key. After that we simple call the Pr<strong>of</strong>DBinstance method list. The data <strong>of</strong> the two pr<strong>of</strong>iles are listed on the screen and into the log file. The code<strong>of</strong> the testing environment is given below.Testing code to check the Pr<strong>of</strong>ile Database Class Pr<strong>of</strong>DB’’’This testing example implements a little pr<strong>of</strong>iledatabase. Two U-pr<strong>of</strong>iles are created and stored inthe database. Then the whole content <strong>of</strong> the databaseis printed using the AppendLog method <strong>of</strong> the base class’’’# package module classfrom Pr<strong>of</strong>iles.UPr<strong>of</strong>ile import UPr<strong>of</strong>ilefrom Pr<strong>of</strong>iles.Pr<strong>of</strong>DB import Pr<strong>of</strong>DB# create Pr<strong>of</strong>ile databasedb = Pr<strong>of</strong>DB()# create the instance <strong>of</strong> an U-Pr<strong>of</strong>ilepr<strong>of</strong> = UPr<strong>of</strong>ile("U100",100.,50.,6.0,8.5)# and save it into the dbdb.setdefault("U100",pr<strong>of</strong>)# create the instance <strong>of</strong> an U-Pr<strong>of</strong>ilepr<strong>of</strong> = UPr<strong>of</strong>ile("U140",140.,60.,7.0,10.)# and save it into the dbdb.setdefault("U140",pr<strong>of</strong>)# print the content <strong>of</strong> the dbdb.List()End <strong>of</strong> CodingE. Baeck


Part IIScripting with Abaqus65


4Some Aspects and IntroductionIn this chapter we talk about the Abaqus Student Edition Licence 6.10.. A main aspect will be thedevelopment <strong>of</strong> Python programs, which should automate the creation <strong>of</strong> FE models and the subsequentcalculation and preprocessing.4.1 Aspects <strong>of</strong> the Abaqus GUIIn this chapter we talk about the Abaqus Student Edition Licence 6.10. GUI 1 .Figure 4.1 shows the Abaqus GUI. A very important item is the combo box to select the module. Theselected module loads the specific menu items. The left window shows the Abaqus object tree. Thebottom window contents an output window for the output messages and the command window for thePython commands.Figure 4.1: Abaqus-GUI1 Graphical User Interface is a window driven program which contents all commands in terms <strong>of</strong> menu items, buttons, boxesand so on which are commonly called widgets.67


Page 68<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/114.2 The Abaqus CAE ModuleThe Abaqus/CAE kernel <strong>of</strong>fers several possibilities to build up an FE model.• The GUI <strong>of</strong>fers interactive functions to create the FE model.• The Python command window <strong>of</strong>fers the possibility to execute single Python commands.• The Scripting interface <strong>of</strong>fers the possibility to run Python scripts.• The GUI <strong>of</strong>fers the possibility to record interactive actions in a Python script format. So we canrecord and replay everything we do within the GUI.The Python interpreter creates the input for the CAE kernel. The CAE kernel creates the input stream forthe Abaqus FE-Module. 22 The input file for the Abaqus FE-Module is a simple Text file, the classical input file, which can also be written ’by hand’.E. Baeck


4.3. A MODELING CHAIN Page 694.3 A Modeling ChainFigure 4.2 shows how to create a Finite Element modelin Abaqus/CAE. It is not possible to create elements andnodes directly. Element and nodes are only created bythe mesh generator, which works an the geometric objects,which are created drawing a sketch.The only FE model parameter, which are created directly,are the material properties and the section values.This properties are created within the module Property.The properties are then assigned to the geometric objects(lines, areas and volumes).After having created a sketch the sketch has to be assignedto a part. If no part exists, a part hast to be created. Theproperties (materials and section data) are assigned to thesketches’ geometric objects.To create a mesh, an instance is needed, so an instance hasto be created. The part with the sketch are assigned to theinstance for later meshing.Loadcases are modeled in terms <strong>of</strong> load steps. So a newstep has to be created as a container for loads and boundaryconditions. Loads and boundaries are assigned to thegeometric objects <strong>of</strong> the sketch which were assigned to apart before.To create the mesh, the mesh’s control parameters shouldbe configured and the element types are to be assigned.Then the instance can be meshed.After the mesh is created, the complete model can be assignedto a job. To calculate the results the job has to besubmitted.Create a databaseModule SketchDraw a sketchModule PartCreate a part andassign the sketchModule PropertyCreate a properties,materials and sections,assign them to sketch linesModule AssemblyCreate an instanceand assign the part to itModule StepCreate a step ascontainer for a load caseModule LoadCreate loads andboundary condition within the stepModule MeshSet Seeds, elements per lengthselect and assign element typemesh the instanceModule JobCreate a Job and submitFigure 4.2: Modeling Chain Diagram2.12.2011


Page 70<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/114.4 A little interactive Warm Up ExampleIn section 4.3 we have discussed the Abaqus modeling chain.Following this outlines the subsequent example based on [5]shows how to create and calculate a simple 3 truss systemwith a concentrated force. We use the following parameters.• L x horizontal length 1000 mmLy• L y vertical length 1500 mm• F x horizontal force -100 kN• F y vertical force -100 kNF xF yL x4.4.1 Create a DatabaseFigure 4.3: 3 TrussesCreate Model DatabaseFile/Set Working Directory (setup the desired work folder if necessary)4.4.2 Create a SketchModule: SketchSketch => Create => Name: ’Truss-Example’ => ContinueAdd=> Point=> enter coordinates (0,0), (1000,0), (1000,1500), (0,1500)Add => Line => Connected Line=> select (0,0) node with mouse, then (1000,0) node,right click => CancelAdd => Line=> Connected Line=> select (0,0) node with mouse, then (1000,1500) node,right click => CancelAdd => Line=> Connected Line=> select (0,0) node with mouse, then (0,1500) node,right click => Cancel=> Done4.4.3 Create a PartModule: PartPart => Create => Name: ’Part-1’,=> select 2D Planar, Deformable, Wire=> ContinueAdd => Sketch => select ’Truss-Example’ => Done => DoneE. Baeck


4.4. A LITTLE INTERACTIVE WARM UP EXAMPLE Page 714.4.4 Create and Assign PropertiesModule: PropertyMaterial => Create => Name: ’Steel’, Mechanical, Elasticity, Elastic=> set Young’s modulus = 210000, Poisson’s ratio = 0.3 => OKSection => Create => Name: ’Truss-Section’, Beam, Truss => Continue=> set Material: ’Material-1’,Cross-sectional area: 2Assign Section => select all elements by dragging mouse => Done=> ’Truss-Section’ => OK => Done4.4.5 Create the Instance, Assign the PartModule: AssemblyInstance => Create => ’Part-1’ => Independent (mesh on instance) => OK4.4.6 Create a Load StepModule: StepStep => Create => Name: ’Step-1’, Initial, Static, General => Continue=> accept default settings=> OK4.4.7 Create Loads and Boundary ConditionsModule: LoadLoad => Create => Name: ’Step-1’, Step: ’Step 1’, Mechanical,Concentrated Force => Continue => select node at (0,0) => Done=> set CF1: -10000 set CF2: -10000 => OKBC => Create => Name: ’BC-1’, Step: ’Step-1’, Mechanical,Displacement/Rotation => Continue=> select nodes at (1000,0), (1000,1500) and (0,1500) using SHIFT keyto select multiple nodes => Done => set U1: 0 and U2: 04.4.8 Create the MeshModule: MeshSeed => Edge by Number => select entire truss by dragging mouse=> Done => Number <strong>of</strong> elements along edges: 1 => press Enter => DoneMesh => Element Type => select entire truss by dragging mouse => Done=> Element Library: Standard,Geometric Order: Linear: Family: Truss => OK => DoneMesh => Instance => OK to mesh the part Instance: Yes2.12.2011


Page 72<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/114.4.9 Create a Job and SubmitModule: JobJob => Create => Name: Job-1, Model: Model-1 => Continue=> Job Type: Full analysis, Run Mode: Background,Submit Time: Immediately => OKJob => Submit => ’Job-1’Job => Manager => Results (enters Module: Visualization)E. Baeck


5Scripts and ExamplesIn this chapter we implement to example scripts, to discuss the automation in Abaqus using the Pythonscript language.1. 3 TrussesThe first script gives the implementation <strong>of</strong> the interactive example, a little 3 trusses system withone concentrated load. The calculation is performed automatically for a linear analysis.2. U Pr<strong>of</strong>ileThe second script gives the implementation <strong>of</strong> the automated model creation <strong>of</strong> U Pr<strong>of</strong>ile using thethin-walled approach (see also section 3.2 and A.1). The calculation is performed automaticallyfor a linear analysis and a buckling analysis.5.1 3 Trusses ScriptWithin this section the implementation <strong>of</strong> a script is shown, which automates the example <strong>of</strong> section4.4. With the change <strong>of</strong> the parameter’s values, every system can be calculated with the execution <strong>of</strong> thescript.Creating the calculation model we follow our outlines discussed in section 4.3. To avoid problems withexisting project files, we first delete an old database, if exist. Then we set the work directory by the use<strong>of</strong> Python’s standard chdir function. 1To get the Python code for the necessary steps, we can simple run the macro recorder and record theinteractive actions. If you do this, then it’s recommended to save the macro file into the work directoryand not into the home directory. The recorded macros are saved into the file abaqusMacros.py.Note, that the work directory will be set, if the script is executed.Within the script code the following steps are numbered in the same way.(1) Create a modelThe model is member <strong>of</strong> the global mdb class. We have to specify the name and the type <strong>of</strong> themodel. The reference to the created model is saved into the variable myModel for further usage.1 Note, that on Windows-Systems a path contents backslashes, which in Python are used as escape characters. Therefore ifa backslash is used, we have to duplicate it.73


Page 74<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11(2) Create a sketchThe ConstrainedSketch is member <strong>of</strong> the model class, so we use the before saved model referencemyModel to create the sketch. Initializing a sketch we have to specify the sketch’s name and thesketch page’s size. The return reference is saved into the variable mySketch.Within our sketch we draw the lines with the method Line. This is done within a for loop iteratingthe tuple containing the endpoint coordinates <strong>of</strong> the lines.(3) Create a partThe part class is a member <strong>of</strong> the model class. We create the part instance specifying it’s nameand it’s type. In this we select the TWO_D_PLANAR type. The return <strong>of</strong> the constructor is savedinto the variable myPart. The method BaseWire <strong>of</strong> myPart is used to assign the sketch. Nowwe have the geometry to start with the creation <strong>of</strong> nodes and elements using the Abaqus meshgenerator. 2(4) Create the elements propertiesThe material class is a member <strong>of</strong> the model class. A material instance is created specifying thematerials name. Within a second step we assign material properties using the Elastic method <strong>of</strong>the material class. A tuple containing the Young’s module and the Poisson ratio is assigned to theparameter table.In a second step we create the truss section instance. The TrussSection class is a member <strong>of</strong> themodel class. The return is saved into the variable mySection.Within the third step the section, which is also linked to the material, will be assigned to the lineobjects <strong>of</strong> the part. So we have to create a region containing the line objects - in this case callededges - to perform the assignment. By default the selection is recorded with the parts memberedges method getSequenceFromMask(mask=(’[#7 ]’, ), ). This selection methodis fastest version <strong>of</strong> selection, but it is also the most cryptic one. If you use this mask, you have tobe sure, that the index <strong>of</strong> the selected elements does not change and you have to know the selectedobjects’ index value. The mask value is created assigning the index values as binary digits. So ingeneral the mask’s value can be calculated with the following equation.mask =∑2 i , with i = Objectlabel − 1 for all selected objects (5.1)i∈SelectionIn our case the lines 1, 2 and 3 are selected. So we get#7 = 7 16 = 7 = 2 1−1 + 2 2−1 + 2 3−1 = 1 + 2 + 4 (5.2)After having selected the lines the truss section will be assigned by the part’s methodSectionAssignment. We have to specify the region and the name <strong>of</strong> the section.(5) Create an instanceTo create the instance, which is needed for meshing, we have to select the rootAssembly object,which is member <strong>of</strong> the model class. Because the rootAssembly also is needed later, we assignit’s reference to the variable root. Within the rootAssembly we create the instance object,specifying it’s name and the part to assign.2 Note, that within the GUI nodes and elements can only be created by the mesh generator, i.e. not directly. If the mesh iscreated, the node’s and element’s properties can be changed by special system edit methods.E. Baeck


5.1. 3 TRUSSES SCRIPT Page 75(6) Create loads and boundary conditionsFirst we should create a StaticStep class, which is a member <strong>of</strong> the modul class. The StaticStepclass is a container for loads and boundary conditions.To create a concentrated load, which is a points load, we have to select first some points, which arecalled vertices in Abaqus. The vertices container is a member <strong>of</strong> the instance class. Vertices alsocan be selected with the getSequenceFromMask method, if the label number <strong>of</strong> the points areknown. The class methode regionToolset.region converts a set <strong>of</strong> vertices into a region.The class ConcentratedForce is a member <strong>of</strong> the model class. We have to specify the loads name.We have to assign the load to a step and a region and have to set up the load values.To create boundary conditions we select vertices as well and convert them into a region. Then theDisplacementBC object, a member <strong>of</strong> the instance class has to be created like the concentratedforces specifying it’s name and assigning it to a load step.(7) Create the meshThe mesh will be created on the geometric data, in this case the lines <strong>of</strong> the sketch. So we haveto set up the seeds <strong>of</strong> the lines, the number <strong>of</strong> elements, which should be created by the meshgenerator. Like in the case <strong>of</strong> the section assignment we select all lines using the edges container<strong>of</strong> the part object. With #7 we set the mask for our 3 lines. To set the numbers <strong>of</strong> elements,we apply the method seedEdgeByNumber <strong>of</strong> the part class passing the selected edges and thenumber <strong>of</strong> elements to create, in this case one.Within a second step we select the element type to use in our model with the method elemType <strong>of</strong>the class mesh. We select from the standard element library the truss element with the code T2D2.Then the selected element type is assigned to all elements using the method setElementType<strong>of</strong> the part class. As parameters we pass a region, which is created with the mask #7 for all edgesand with an tuple <strong>of</strong> selected element types.Within an ultimate step we simple call the method generateMesh <strong>of</strong> the part class.Now the mesh is created with all it’s properties and with the method setValues <strong>of</strong> the standardviewport instance, which is a member <strong>of</strong> the session class, we can view the mesh passing thepart instance as displayedObject parameter. If no viewport is explicitly created, the standardviewport is called Viewport: 1.(8) Create the job and submitWe set up the jobname and create the job using the standard parameter values. In this case thejob is executed immediately after submission. The return value <strong>of</strong> the creation step is saved into avariable for later usage. After the creation <strong>of</strong> the job, the job is submitted with the job classes’ themethod submit. To automate the analysis <strong>of</strong> the results two features are available.– synchronous analysisIn this case the script halts for completion <strong>of</strong> the calculation. This can be obtained by theusage <strong>of</strong> the job classes’ method waitForCompletion. The next commands <strong>of</strong> the scriptare executed after the calculation is completed.– asynchronous analysisIn this case the script does not halt for completion and the next instructions are executedimmediately. To automate the analysis <strong>of</strong> the results we have to set up a call back function.This function is executed automatically after the calculation is done.2.12.2011


Page 76<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11In our script we implement a synchronous analysis.(9) <strong>Analysis</strong> <strong>of</strong> the result valuesTo start with the analysis we have to open the result database first. This can be done by theopenOdb method <strong>of</strong> the class visualization passing the name <strong>of</strong> the result database. The returnvalue is a reference to the data base instance.To access the result values first we have to select the desired step. The step instance contains aframe container. The result values are to obtain from the member class fieldOutputs. In our casewe select the displacements with the output variable name U. The stresses can be selected withthe output variable S. The values container <strong>of</strong> the fieldOutput instance contains a memberelementLabel, which is set, if an element result data set is available. If a node result data setis available the nodeLabel member is set. The result values are items <strong>of</strong> the data array.After the analysis is done, you should not forget to close the database with the close memberfunction.Code <strong>of</strong> the Example 3-Trusses# copy the next line into the abaqus command window and execute# execfile("c:\\CM\\Cm-AoS\\WS1011\Abaqus\\3Trusses.py")from abaqus import *from abaqusConstants import *from caeModules import *# this we need for regionToolsetmodelname = ’3Trusses’# delete old database if existstry:del mdb.Models[modelname]print "model ’%s’ deleted." % modelnameexcept:print "No model ’%s’ found!" % modelnameimport os# os toolsos.chdir(r’c:\\cm\\Cm-AoS\\WS1011\\Abaqus’)# set up parametersdx = 1000. # length in xdy = 1500. # length in zA = 13.5*100. # U100 areaFx = -100000. # horzontal loadFy = -100000. # vertikal loadEMod = 210000. # Young’s modulenue = 0.3 # Poisson’s ratioE. Baeck


5.1. 3 TRUSSES SCRIPT Page 77# (1) create a modelmyModel = mdb.Model(name=modelname, modelType=STANDARD EXPLICIT)# (2) create a sketchmySketch = myModel.ConstrainedSketch(name=’3Truss-Sketch’,sheetSize=1.1*2*dy)# - create tuple with coordinatesxyPoint = ( (0,0), (dx,0), (dx,dy), (0,dy) )# - iterate the tuple and draw linesfor i in range(1,len(xyPoint)):mySketch.Line(point1=xyPoint[0], point2=xyPoint[i])# (3) create partmyPart = myModel.Part(name=’Trusse-Part-1’,dimensionality=TWO D PLANAR, type=DEFORMABLE BODY)# - assign the sketchmyPart.BaseWire(sketch=mySketch)# (4) set up properties# - create material for steelmySteel = myModel.Material(name = ’Steel’)mySteel.Elastic(table=( (EMod,nue), ))# - create truss sectionmySection = myModel.TrussSection(name=’Truss-Section’, area=A,material=’Steel’)# - assign the section to all linesalledges = myPart.edgesedges = alledges.getSequenceFromMask(mask=(’[#7 ]’, ), )region = regionToolset.Region(edges=edges)myPart.SectionAssignment(region=region, sectionName=’Truss-Section’, <strong>of</strong>fset=0.0<strong>of</strong>fsetType=MIDDLE SURFACE, <strong>of</strong>fsetField=’’,thicknessAssignment=FROM SECTION)# (5) create an instanceroot = myModel.rootAssemblymyInst = root.Instance(name=’Trusses-Instance’, part=myPart, dependent=ON)# (6) create a load stepmyModel.StaticStep(name=’First Step’, previous=’Initial’,description=’Static Load Step’)2.12.2011


Page 78<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11# - create loads for the loadstepv1 = myInst.verticesverts1 = v1.getSequenceFromMask(mask=(’[#2 ]’, ), )region = regionToolset.Region(vertices=verts1)myModel.ConcentratedForce(name=’Load-1’,createStepName=’First Step’, region=region, cf1=Fx, cf2=Fy,distributionType=UNIFORM, field=’’, localCsys=None)# - create boundary conditions for the loadstepverts1 = v1.getSequenceFromMask(mask=(’[#d ]’, ), )region = regionToolset.Region(vertices=verts1)myModel.DisplacementBC(name=’BC-1’,createStepName=’First Step’, region=region, u1=0.0, u2=0.0, ur3=UNSET,amplitude=UNSET, fixed=OFF, distributionType=UNIFORM, fieldName=’’,localCsys=None)# (7) create mesh# - number <strong>of</strong> elments / linee= myPart.edgespickedEdges = e.getSequenceFromMask(mask=(’[#7 ]’, ), )myPart.seedEdgeByNumber(edges=pickedEdges, number=1, constraint=FINER)# - set up the element typeelemType1 = mesh.ElemType(elemCode=T2D2, elemLibrary=STANDARD)e = myPart.edgesedges = e.getSequenceFromMask(mask=(’[#7 ]’, ), )Region=(edges, )myPart.setElementType(regions=Region, elemTypes=(elemType1, ))# - create the meshmyPart.generateMesh()# - show the meshsession.viewports[’Viewport: 1’].setValues(displayedObject=myPart)# (8) create a job and submit itjobname = modelname+’-Job-1’myJob = mdb.Job(name=jobname, model=modelname,description=’Calculation <strong>of</strong> the 3 Trusses System’, type=ANALYSIS,atTime=None, waitMinutes=0, waitHours=0, queue=None, memory=50,memoryUnits=PERCENTAGE, getMemoryFrom<strong>Analysis</strong>=True,explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine=’’,scratch=’’)E. Baeck


5.1. 3 TRUSSES SCRIPT Page 79myJob.submit(consistencyChecking=OFF)# - note: wait for completion, if the result values should be read form DBmyJob.waitForCompletion()# (9) analysis <strong>of</strong> results# - open the database: odb filemyOdb = visualization.openOdb(jobname+’.odb’)# - read data from the last frameframe = myOdb.steps[’First Step’].frames[-1]# - printing the displacementsdata = frame.fieldOutputs[’U’]n = len(data.values)print "%d Result records" % nprint ’--no ---ux----- ---uy----’for value in data.values:print "%4d %10.5f %10.5f" % (value.nodeLabel,value.data[0],value.data[1])# - printing the stressesdata = frame.fieldOutputs[’S’]n = len(data.values)print "%d Result records" % nprint ’--no --S11-----’for value in data.values:print "%4d %10.5f" % (value.elementLabel,value.data[0])# close the databasemyOdb.close()End <strong>of</strong> Coding2.12.2011


Page 80<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/115.2 U Pr<strong>of</strong>ile ScriptThe goal <strong>of</strong> our next example is, to create a mesh from a 2 dimensionalsketch <strong>of</strong> an U geometry by extrusion. Figure 5.2 shows an U pr<strong>of</strong>ile withit’s parameters [6].The model <strong>of</strong> the U pr<strong>of</strong>ile is created step by step according to the modelingchain diagram (figure 4.2). The created mesh is shown in figure 5.2.Figure 5.3 shows the load onto the upper flange <strong>of</strong> the girder. The girder issupported on both ends at the lower flange’s edges. Additional point supportis needed to avoid longitudinal and transversal movements as well asrigid body rotations.Note that the figures are printed automatically after having created the finiteelement model.Figure 5.1: U Pr<strong>of</strong>ileWithin the header section <strong>of</strong> the script all parameters are defined and initialized.The script is able to perform optionally a linear or a buckling analysis. This is controlledby the flag bBuckl. Optionally system plots as well as result plots are created and printed intopng graphic files. This is controlled by the flag bPNGFile.Within this implementation steps were recorded with the macro recorder and the recorded codewas reduced by the settings <strong>of</strong> standard parameters which are generally also recorded. Furthermorewe introduce consequently abbreviations for larger instance item accesses. This gives us a morecompact and readable code.Automated creation and analysis <strong>of</strong> an U pr<strong>of</strong>ile system’’’the script can be starte like this commandexecfile("c:\\Cm\\CM-AoS\\Ws1011\\Abaqus\\UPr<strong>of</strong>ile2 1.py")note: macros are recorded in to the work directory into afile "abaqusMacros.py"’’’from abaqus import *from abaqusConstants import *from caeModules import *import math# set working folderimport osos.chdir(r’C:\\CM\\Cm-AoS\\WS1011\\Abaqus’)# >> for recording coordinate picking# session.journalOptions.setValues(replayGeometry=COORDINATE)from Base2 import BaseE. Baeck


5.2. U PROFILE SCRIPT Page 81prjname = "UPr<strong>of</strong>ile2 1"logname = prjname + ’.log’Logger = Base(logname)Logger.reset()Logger.AppendLog(">> Project: ’%s’" % prjname)# delete the model, if stil existstry:del mdb.models[prjname]except:pass# (2) Create a sketch# (2.1) - parameterdH = 100.0 # pr<strong>of</strong>ile heightdW = 50.0 # pr<strong>of</strong>ile widthds = 6.0 # web thicknessdt = 8.5 # flange thicknessdL = 4000. # pr<strong>of</strong>ile lengthEMod = 210000. # Young’s modulnue = 0.3 # Poisson’s rationSecSeed = 2# elements on pr<strong>of</strong>ile section linesnDepSeed = 140# elements in length directiondPressur = 0.1# pressure loadnumEigen = 10# number <strong>of</strong> eigenvaluesnumIterX = 100# maximum number <strong>of</strong> iterationsbBuckl = True # selection <strong>of</strong> the calculation# True : buckling# False: linear calculationbPNGFile = True# Print png-File# True : export png file# False: no png file exportnodepos = {} # dictionary for node positionsnodedis = {} # dictionary for node displacements# (1) Create a modelLogger.AppendLog("Create model...")myModel = mdb.Model(name=prjname)# (2.2) - the sketchLogger.AppendLog("Create sketch...")2.12.2011


Page 82<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11mySketch = myModel.ConstrainedSketch(name=’UPr<strong>of</strong>ile-Sketch’, sheetSize=200)# (2.3) - the pointsxyPoints = ( (dW,-dH/2.), (0.,-dH/2.), (0.,dH/2.), (dW,dH/2.) )# (2.4) - the linesfor i in range(1,len(xyPoints)):mySketch.Line(point1 = xyPoints[i-1], point2 = xyPoints[i])# (3) Create a partLogger.AppendLog("Create part...")myPart = myModel.Part(name=’UPr<strong>of</strong>ile-Part-1’, dimensionality=THREE D, \type=DEFORMABLE BODY)# - extrude the linesmyPart.BaseShellExtrude(sketch=mySketch, depth=dL)# (4) Create a materialLogger.AppendLog("Create material and properties...")myModel.Material(name=’Steel’,description=’Only Steel’)myModel.materials[’Steel’].Elastic(table=((EMod, nue),))# (5) Create a section <strong>of</strong> a pr<strong>of</strong>ilemyModel.HomogeneousShellSection(name=’Section-Web’,material=’Steel’, \thickness=ds)myModel.HomogeneousShellSection(name=’Section-Flanch’,material=’Steel’, \thickness=dt)# (6) Assign the section# - flangesfaces = myPart.faces.findAt(((dW/2.,-dH/2.,dL/2.),), ((dW/2.,+dH/2.,dL/2.),), )region = regionToolset.Region(faces=faces)myPart.SectionAssignment(region=region, sectionName=’Section-Flanch’)# - webfaces = myPart.faces.findAt(((0.,0.,dL/2.),))region = regionToolset.Region(faces=faces)myPart.SectionAssignment(region=region, sectionName=’Section-Web’)# (7) Create meshLogger.AppendLog("Create mesh...")# - seed an pr<strong>of</strong>ile linespickedEdges = myPart.edges.findAt(((dW/2.,-dH/2.,0.),), ((dW/2.,+dH/2.,0.),), \((0,0,0),))myPart.seedEdgeByNumber(edges=pickedEdges, number=nSecSeed)E. Baeck


5.2. U PROFILE SCRIPT Page 83# - seed in depth directionpickedEdges = myPart.edges.findAt(((dW/2.,-dH/2.,dL),), ((dW/2.,+dH/2.,dL),), \((0,0,dL),))myPart.seedEdgeByNumber(edges=pickedEdges, number=nSecSeed)# - seed in depth directionpickedEdges = myPart.edges.findAt(((dW,-dH/2.,dL/2.),), ((0.,-dH/2.,dL/2.),), \((0.,+dH/2.,dL/2.),), ((dW,+dH/2.,dL/2.),),)myPart.seedEdgeByNumber(edges=pickedEdges, number=nDepSeed)# - assign element type (optional)elemType1 = mesh.ElemType(elemCode=S4R)elemType2 = mesh.ElemType(elemCode=S3)pickedEdges = myPart.faces.findAt(((dW/2.,-dH/2.,dL/2.),), \((dW/2.,+dH/2.,dL/2.),), ((0.,0.,dL/2.),))pickedRegions =(faces, )myPart.setElementType(regions=pickedRegions, elemTypes=(elemType1, elemType2))# - and mesh itmyMesh = myPart.generateMesh()# overwritenodes = myPart.nodesn = len(nodes)Logger.SetTime(False)Logger.SetScreen(False)Logger.AppendLog(’\nNumber <strong>of</strong> mesh nodes: %d’ % n)Logger.AppendLog(’--no ----x----- ----y----- ----y-----’)for node in nodes:nodepos[node.label] = (node.coordinates[0],node.coordinates[1], \node.coordinates[2])Logger.AppendLog("%4d %10.3f %10.3f %10.3f" % (node.label, \node.coordinates[0], node.coordinates[1], \node.coordinates[2]));Logger.AppendLog(’--no ----x----- ----y----- ----y-----\n’)Logger.SetTime(True)Logger.SetScreen(True)# (8) Create instanceLogger.AppendLog("Create instance...")root = myModel.rootAssemblymyInst = root.Instance(name=’UPr<strong>of</strong>ile-Instance’, part=myPart, dependent=ON)# (9a) Buckling analysis stepstepname = ’linear step’2.12.2011


Page 84<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11if bBuckl:stepname = ’buckling step’Logger.AppendLog("Create step ’%s’..." % stepname)myModel.BuckleStep(name=stepname, previous=’Initial’,description=’Bucklung Calculation’,numEigen=numEigen, vectors=numEigen +8,maxIterations = numIterX)else:# (9b) Linear static calculation stepLogger.AppendLog("Create step ’%s’..." % stepname)myModel.StaticStep(name=stepname, previous=’Initial’,description=’UPr<strong>of</strong>ile-Step1’)# (10) Create a pressureLogger.AppendLog("Create loads...")side2Faces1 = myInst.faces.findAt(((dW/2.,+dH/2.,dL/2.),))region = regionToolset.Region(side2Faces=side2Faces1)myModel.Pressure(name=’TopLoad’, createStepName=stepname,region=region, magnitude=dPressur)# (10) Create boundary conditions# - vertical on both endsLogger.AppendLog("Create boundary conditions...")edges1 = myInst.edges.findAt((((dW/2.,-dH/2.,0.)),),((dW/2.,-dH/2.,dL),),)region = regionToolset.Region(edges=edges1)myModel.DisplacementBC(name=’BC-1’, createStepName=stepname,region=region, u1=UNSET, u2=0.0, u3=UNSET, ur1=UNSET, ur2=UNSET,ur3=UNSET, amplitude=UNSET, fixed=OFF, distributionType=UNIFORM,fieldName=’’, localCsys=None)# - fixed node on endverts1 = myInst.vertices.findAt((((0.,-dH/2.,0.)),),)region = regionToolset.Region(vertices=verts1)myModel.DisplacementBC(name=’BC-2’, createStepName=stepname,region=region, u1=0.0, u2=0.0, u3=0.0, ur1=UNSET, ur2=UNSET, ur3=UNSET,amplitude=UNSET, fixed=OFF, distributionType=UNIFORM, fieldName=’’,localCsys=None)# - fixed in vertical and transversal directionverts1 = myInst.vertices.findAt((((dW,-dH/2.,0.)),),)region = regionToolset.Region(vertices=verts1)myModel.DisplacementBC(name=’BC-3’, createStepName=stepname,region=region, u1=UNSET, u2=0.0, u3=0.0, ur1=UNSET, ur2=UNSET, ur3=UNSET,amplitude=UNSET, fixed=OFF, distributionType=UNIFORM, fieldName=’’,localCsys=None)E. Baeck


5.2. U PROFILE SCRIPT Page 85# set an abrivation for the viewport pointermyViewport = session.viewports[’Viewport: 1’]# - and show the mesh and optionally export as png filemyViewport.setValues(displayedObject=root)myViewport.assemblyDisplay.setValues(mesh=ON,loads=OFF,bcs=OFF)if bPNGFile:myViewport.view.fitView() # fit the plot to the viewpngfile = prjname +"-mesh"session.printOptions.setValues(vpBackground=ON)session.printToFile(fileName=pngfile, format=PNG,canvasObjects=(myViewport, ))# - and show the part and optionally export as png filemyViewport.setValues(displayedObject=root)myViewport.assemblyDisplay.setValues(mesh=OFF, loads=ON,bcs=ON)myViewport.assemblyDisplay.setValues(step=stepname)if bPNGFile:myViewport.view.fitView() # fit the plot to the viewpngfile = prjname +"-part"session.printOptions.setValues(vpBackground=ON)session.printToFile(fileName=pngfile, format=PNG,canvasObjects=(myViewport, ))# (12) Create a Jobjobname = prjname + ’-Job-1’Logger.AppendLog("Create job ’%s’..." % jobname)myJob = mdb.Job(name=jobname, model=prjname,description=’Calculate the UPr<strong>of</strong>ile Structure’)# (12) Submit the JobLogger.AppendLog("Submit job...")myJob.submit(consistencyChecking=OFF)myJob.waitForCompletion()# setup the result database nameodbname = jobname + ’.odb’ # set database namemySession = session.openOdb(name=odbname) # set session pointer# print data into the png fileif bPNGFile:# Analyzis <strong>of</strong> the resultsif bBuckl:2.12.2011


Page 86<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11# over all modes (eigenforms)for mode in range(1,numEigen+1):Logger.AppendLog("View buckling mode %d..." % mode)# create plotmyViewport.setValues(displayedObject=mySession)myViewport.odbDisplay.setFrame(step=0,frame=mode)myViewport.odbDisplay.display.setValues(plotState=(CONTOURS ON DEF, ))myViewport.view.fitView() # fit the plot to the view# ... and copy the plot into a png filepngfile = prjname + ("-mode-%2.2d" % mode)session.printOptions.setValues(vpBackground=ON)session.printToFile(fileName=pngfile, format=PNG,canvasObjects=(myViewport, ))# linear calculationelse:# plot misesLogger.AppendLog("View Results...")myViewport.setValues(displayedObject=mySession)myViewport.odbDisplay.display.setValues(plotState=(CONTOURS ON DEF, ))myViewport.view.fitView()# ... and print into pngpngfile = prjname + "-s"session.printOptions.setValues(vpBackground=ON)session.printToFile(fileName=pngfile, format=PNG,canvasObjects=(myViewport, ))# ... print displacements in U1, U2 and U3varlist = ("U1","U2","U3")for var in varlist:myViewport.odbDisplay.setPrimaryVariable( \variableLabel=’U’, outputPosition=NODAL, \refinement=(COMPONENT,var))myViewport.odbDisplay.display.setValues(plotState=(CONTOURS ON DEF, ))myViewport.view.fitView()pngfile = prjname +"-" + varsession.printOptions.setValues(vpBackground=ON)E. Baeck


5.2. U PROFILE SCRIPT Page 87session.printToFile(fileName=pngfile, format=PNG,canvasObjects=(myViewport, ))# Printing and analysis <strong>of</strong> the displacmentsLogger.AppendLog("Open database ’%s’..." % odbname)# open databasemyOdb = visualization.openOdb(odbname)# get number <strong>of</strong> framesstep = myOdb.steps[stepname]nFrames = len(step.frames)# print the displacements <strong>of</strong> every framefor nFrame in range(1,nFrames):# select the displacementsframe = step.frames[nFrame]data = frame.fieldOutputs[’U’]Logger.SetTime(False)Logger.SetScreen(False)# write a headerLogger.AppendLog("\nData <strong>of</strong> frame %d" % nFrame)header = "\n--no ---ux----- ---uy----- ---uz-----|"header += " ----x----- ----y----- ----z-----"Logger.AppendLog(header)# over all nodes and it’s displacementsfor value in data.values:nodedis[value.nodeLabel] = (value.data[0],value.data[1],value.data[2])Logger.AppendLog("%4d %10.3f %10.3f %10.3f| %10.3f %10.3f %10.3f " % \(value.nodeLabel,value.data[0],value.data[1],value.data[2], \nodepos[value.nodeLabel][0], \nodepos[value.nodeLabel][1], \nodepos[value.nodeLabel][2],))Logger.AppendLog(header)# maximum searchmax = [None, None, None]pos = [None, None, None]# over all directionsfor i in range(3):2.12.2011


Page 88<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11# over all nodesfor nodeLabel in nodedis:# get the node labeldisv = nodedis[nodeLabel]# initialize the max searchif max[i] is None:max[i] = disv[i]pos[i] = nodeLabel# if new max found, save it and it’s node labelelse:if math.fabs(disv[i]) > math.fabs(max[i]):max[i] = disv[i]pos[i] = nodeLabel# enable time stamp and screen outputLogger.SetTime(True)Logger.SetScreen(True)Logger.AppendLog("\nmaximum displacement <strong>of</strong> nodes in frame: %d" % nFrame)# over all directionslabels = ("x","y","z")ind = 0for label in labels:xyz = nodepos[pos[ind]]Logger.AppendLog(’ %s: node %3d : %10.3f > %10.3f %10.3f %10.3f’ % \(label,pos[ind],max[ind],xyz[0],xyz[1],xyz[2]))ind += 1# close database to avoid lockingmyOdb.close()# close LoggerLogger.AppendLog("----> end <strong>of</strong> script")del LoggerEnd <strong>of</strong> CodingFigure 5.4 shows the resulting Mieses stresses <strong>of</strong> a linear analysis. Figure 5.5 shows the resulting displacementsin 1(x), 2(y) and 3(z) direction <strong>of</strong> a linear analysis.The figures 5.6 to 5.15 show the first 10 buckling modes <strong>of</strong> the girder.E. Baeck


5.2. U PROFILE SCRIPT Page 89Figure 5.2: U pr<strong>of</strong>ile’s meshFigure 5.3: U pr<strong>of</strong>ile’s loads and boundary conditionsFigure 5.4: Mieses stresses <strong>of</strong> a linear analysis2.12.2011


Page 90<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Figure 5.5: Displacement in 1,2 and 3 direction <strong>of</strong> a linear analysisE. Baeck


5.2. U PROFILE SCRIPT Page 91Figure 5.6: Buckling mode 1Figure 5.7: Buckling mode 2Figure 5.8: Buckling mode 32.12.2011


Page 92<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Figure 5.9: Buckling mode 4Figure 5.10: Buckling mode 5Figure 5.11: Buckling mode 6E. Baeck


5.2. U PROFILE SCRIPT Page 93Figure 5.12: Buckling mode 7Figure 5.13: Buckling mode 8Figure 5.14: Buckling mode 92.12.2011


Page 94<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11Figure 5.15: Buckling mode 10E. Baeck


Part IIIAppendix95


Appendix ASome TheoryA.1 Section PropertiesWithin this chapter the formulas for the section properties <strong>of</strong> a thin walled model are given.A thin walled model for a pr<strong>of</strong>ile section consists <strong>of</strong> a set <strong>of</strong> lines which describes the pr<strong>of</strong>ile sectiongeometry at the centerline.A.1.1The Area <strong>of</strong> a Pr<strong>of</strong>ile SectionThe Area is approximately the sum <strong>of</strong> the areas <strong>of</strong> the lines <strong>of</strong> the thin walled model.∫A =Ae µ · dA ≈n∑e µ,i · L i · t ii=1(A.1)with: L i the length <strong>of</strong> line it ie µ,ithe thickness <strong>of</strong> line ithe relative elasticity <strong>of</strong> line i (1 for only one material)A.1.2First Moments <strong>of</strong> an AreaThe first moments <strong>of</strong> an area are the area integrals given below. The (y,z) values are related to an givencoordinate system.∫S y =∫S z =AAe µ · z · dA ≈e µ · y · dA ≈with: A i the area <strong>of</strong> a line iy iz in∑e µ,i · z i · A ii=1n∑e µ,i · y i · A ii=1the y coordinate <strong>of</strong> the center <strong>of</strong> line ithe z coordinate <strong>of</strong> the center <strong>of</strong> line i(A.2)97


Page 98<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11A.1.3Second Moments <strong>of</strong> an Area or Moments <strong>of</strong> InertiaThe moments <strong>of</strong> inertia can be calculated with the formulas below. If we have a given arbitrary coordinatesystem in general we have three values <strong>of</strong> inertia the I y , the I z and the mixed I yz . If we use the maincoordinate system, the mixed moment <strong>of</strong> inertia is vanishing, so we use the symbols I ξ and I η .∫I y =∫I z =∫I yz =AAAe µ · z 2 · dA ≈e µ · y 2 · dA ≈e µ · y · z · dA ≈with: A i the area <strong>of</strong> a line iy iz iy a,iz a,iy b,iz b,in∑i=1e µ,i · (( (z b,i − z a,i ) 2 /12) + z 2 ) )i · Ain∑e µ,i · (( (y b,i − y a,i ) 2 /12) + y 2 )i ·) A ii=1n∑e µ,i · (((y b,i − y a,i )(z b,i − z a,i )/12) + y i · z i ) · A i )i=1the y coordinate <strong>of</strong> the center <strong>of</strong> line ithe z coordinate <strong>of</strong> the center <strong>of</strong> line ithe y coordinate <strong>of</strong> the first point <strong>of</strong> line ithe z coordinate <strong>of</strong> the first point <strong>of</strong> line ithe y coordinate <strong>of</strong> the second point <strong>of</strong> line ithe z coordinate <strong>of</strong> the second point <strong>of</strong> line i(A.3)To solve an integral like I y = ∫ A z 2 · dA for a polyline we can split up the integral into the sum <strong>of</strong>integrals over the polyline segments.∫I y =Az 2 · dA =n∑∫i=1A iz 2 · dA(A.4)To solve an integral for a polyline segment we simple calculate it for the center <strong>of</strong> mass, because a simpleshift only will give us an additional term, the Steiner term. If we now want to calculate the polylineintegral at the center <strong>of</strong> mass we rotate the coordinate system by an angle ϕ into the line’s longitudinaldirection, because the transversal dimension, the thickness, is constant and so the respective integral willbe trivial.E. Baeck


A.1. SECTION PROPERTIES Page 99Thus we make the following substitution.(y, z) ⇒ (η, ξ)z = ξ/cos(ϕ)(A.5)(A.6)With this substitution we will get the following integral.I y,i =∫ η=+t ∫ ξ=+L/2= t ·η=−t ξ=−L/2∫ ξ=+L/2ξ=−L/2ξ 2· dη · dξcos(ϕ) 2ξ 2cos(ϕ) 2 · dξ∣= t · ξ33 · 1 ∣∣∣ξ=+L/2cos(ϕ) 2 ξ=−L/2= t · L312 · 1cos(ϕ) 2= (z b,i − z a,i ) 212· A i with t · L = A i (A.7)A.1.4Center <strong>of</strong> MassThe coordinates <strong>of</strong> the center <strong>of</strong> mass are calculated with the arithmetic mean. Because the numerator <strong>of</strong>the arithmetic mean is identical with the first moment <strong>of</strong> the area (see section A.1.2) and the denominatoris identical with the area <strong>of</strong> the pr<strong>of</strong>ile, which is calculated in section A.1.1 we can use this values.∫Ay c = ∫y · dAA dA = S zA∫z c =A∫z · dAA dA= S yA(A.8)A.1.5Moments <strong>of</strong> Inertia with Respect to the Center <strong>of</strong> MassIf we know the center <strong>of</strong> mass coordinates given in section A.1.4 we can calculate the moments <strong>of</strong> inertiawith respect to the center <strong>of</strong> mass using Steiner’s Theorem as follows.I y,c = I y − z 2 c · AI z ,c = I z − y 2 c · AI yz ,c = I yz − y c · z c · A(A.9)2.12.2011


Page 100<strong>Analysis</strong> <strong>of</strong> <strong>Structures</strong> - WS10/11A.1.6Main Axis TransformationTo get the moments <strong>of</strong> inertia I ξ and I η we have to transform the moments <strong>of</strong> inertia into the maincoordinate system. Using this coordinate system the mixed moment <strong>of</strong> inertia is vanishing.The main axis transformation is given with equation A.10. 1I del = I z ,c − I y,cI sum = I y,c + I z ,c√I sqr = IDel 2 + 4 · I yz 2 ,cϕ = 1 2 · arctan(2 · I yz ,cI del)I ξ = 1 2 · (I sum + I sqr )I η = 1 2 · (I sum − I sqr )(A.10)1 The rotation angle ϕ should be shifted into the intervall [−π/2... + π/2]. To avoid a zero division calculating the rotationangle ϕ a special version <strong>of</strong> the atan function should be used, which is able to handle the pole problem. In Python like in C thisfunction is called atan2(y, x), which calculates the atan( y ). xE. Baeck


Bibliography[1] H.P. Langtangen:A Primer on Scientific Programming with PythonSpringer-Verlag Berlin Heidelberg, 2009[2] NumPy Community:NumPy User GuideRelease 1.4.1, April 2010[3] SciPy Community:SciPy Reference GuideRelease 0.8.dev, February 2010[4] ISO/IEC 19501:2005<strong>Info</strong>rmation technology – Open Distributed Processing – Unified Modeling Language(UML) Version 1.4.2[5] D. G. TaggartUniversity <strong>of</strong> Rhode Island, 2009[6] O. LuegerLexikon der Technik, 1904101


Index:, 28AbaqusabaqusMacros, 73BaseWire, 74close, 76ConstrainedSketch, 74DisplacementBC, 75element typeT2D2, 75elemType, 75fieldOutputs, 76frame, 76generateMesh, 75getSequenceFromMask, 74instance, 74job, 75material, 74mesh, 75model, 73openOdb, 76part, 74regionToolset, 75rootAssembly, 74SectionAssignment, 74seedEdgeByNumber, 75session, 75setElementType, 75StaticStep, 75step, 76submit, 75TrussSection, 74values, 76vertices, 75viewport, 75visualization, 76waitForCompletion, 75append, 33Aptana, 8area, 97arithmetic mean, 99as, 14Basic, 20bit’s values , 16break, 23buckling analysis, 80buckling modes, 88C, 15, 19, 20, 22center <strong>of</strong> mass, 99chdir, 73classAList, 53, 58Base, 52Line, 58Point, 56Pr<strong>of</strong>DB, 64Pr<strong>of</strong>ile, 53Pr<strong>of</strong>iles, 51UPr<strong>of</strong>ile, 51code blocks, 21complement, 15ComTypes, 6continue, 23cos, 14count, 33datetime, 38day, 38def, 28derivative, 29dictionary, 34, 62e/E format, 20eigenforms, 88eigenvalues, 88extend, 33f format, 20102


INDEX Page 103factorial, 22factorial(170), 24factorial(400), 24fileclose, 41open, 40write, 40Finite Element Model, 69first moment, 97float, 20for, 22Fortran, 20g/G format, 20hour, 38IDE, 8if, 25import, 14indent, 22index, 33insert, 33int, 20Interactive window, 10iteration, 29Lib, 5LIFO, 34linear analysis, 80list, 32, 33long, 20main axis, 100map, 34microsecond, 38minute, 38moment <strong>of</strong> inertia, 98month, 38name, 21negative number, 15Newton’s Algorithm, 30now, 38NumPy, 7OOP, 41Parameters, 28pi, 14PNG export, 80pop, 33printf, 19push, 34PyDev, 8PyLab, 62PythonWin, 10random, 35remove, 33reserved words, 13return, 28reverse, 33SciPy, 7second, 38second moment, 98Setup, 5sin, 14site-packages, 5sort, 33stack, 34strings, 32The Beatles, 35timedelta, 38Tkinter, 53tuple, 32type, 21type checking, 28UML, 41aggregation, 42class diagram, 41composition, 42inheritance diagram, 42note diagram, 42note diagram assignment, 42version, 5while, 22year, 38package, 14, 522.12.2011

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!