Metafor

ULiege - Aerospace & Mechanical Engineering

User Tools

Site Tools


doc:user:tutorials:tuto0

This is an old revision of the document!




Python in a nutshell

Introduction

This section shows how to use Python, the interpretor used by Metafor, in a basic way. Ideally, Python official website should be used.

Python is a powerful language allowing the creation of data sets in a way very convenient for the developer, but it might look a bit tedious for the code user.

The interpreter

Introduction

When Metafor is started, a window appears:

L'interface graphique de Metafor

This window displays the command-line interpreter. This is a Python interpreter integrated within Metafor, allowing the user to type commands, in a similar way as in MATLAB.

Above the interpreter, a list of all the restrictions associated with the executable is shown (time limit, maximal number of nodes, …). The figure above corresponds to a full version associated to a specific computer.

Once Python is initialized, Metafor automatically loads the module toolbox.utilities, which contains a set of useful commands. To be more accurate, only the most useful functions of this module are loaded, to avoid using too much space in the namespace named “roots”.

A Metafor data set is a series of Python commands. An obvious disadvantage is that this is quite far away from the user-friendly graphical interfaces Samcef Fields or Abaqus CAE. However, in this context all Python tools (functions, objects, loops, conditional structures, …) can be used to easily create and parametrize a problem, leading to a very efficient way of developing numerical models.

Another interesting aspect of Python is its ability to interface compiled C++ code without the help of the programmer (the modules wrap are automatically created from the source code). Therefore, Python is ideal for both the developer and the (well-informed) user.

Python is quite simple. For example, it can be used as a calculator :

>>> a=2
>>> b=3
>>> c=a+b
>>> c
5
>>>

Careful : this sequence is only correct when using Metafor without its graphical interface. With Metafor GUI, the correct syntax to get the value of c is with the command print c.

The definition of variables allows the parametrization of Metafor data sets. Therefore, as with every other piece of software, it is important to first define a set of variables and then work with these algebraic variables.

To display memory contents, use dir()

>>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'getDomain', 'getPath', 
'loadFac', 'makeAnimation', 'meta', 'quit', 'restart', 'vizu']
>>>

The three variables that were just created can be seen, and so can the toolbox.utilities functions that were automatically imported (meta, vizu, …). Finally, __builtins__ is a module containing basic Python functions. To see them, the function dir() is used again.

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 
'FloatingPointError',    'FutureWarning', 'IOError', 'ImportError', 
'IndentationError', 'IndexError ...

Types

The type of a variable is obtained with the command type(var). Every variable has a type, however in Python the type of a variable can change during the execution of the code, unlike in Fortran or C.

>>> a=4
>>> type(a)
<type 'int'>
>>> a='text'
>>> type(a)
<type 'str'>
>>>

Metafor uses the basic types (float, string, integer, tuple, …), but also its own types, which are defined with the use of classes.

Finally, variables can be converted from one type to another. For example, int(2.3) is 2, when str(2.3) gives the string “2.3”.

Functions

Simple functions can be created using the interpreter. This is quite useful to avoid any cut and paste, or simply to write algorithms as scripts. For example :

>>> def square(x): return x*x
...
>>> square(6)
36
>>>

Functions are essential in the proper writing of a data set. This way, complex operations may be defined and called several times, from the same module or even from other ones. For example, if the test case contains several similar contact matrices, it is worth parametrizing the creation of a matrix (definition of its points, lines, …), and then calling it several times with different arguments. Materials may also be assigned using functions.

Default values for these parameters may be set :

def myfun(x, a=1, b=1, c=0):
    return a*x*x+b*x+c

where a, b and c are optional parameters. For instance, this function may be called with the command :

y = myfun(3, b=2)

Here, x=3, a=1, b=2 and c=0.

This function may be written in another way, using the lambda functions :

myfun = lambda x, a=1, b=1, c=0 : a*x*x+b*x+c

Modules

It is quite useful to gather several functions into a file, to form a module (one module is defined with one file). In Metafor, every test case is defined in a module. For example, the test case named cont2 is located in Metafor/apps/qs/cont2.py and identified by apps.qs.cont2 under Python.

By default, Python already contains many modules. For example, the module called math defines all basic mathematical functions. To use a module, the function import must be used (for example, import math). Then, to use a function of the math module, the point is used. For example, math.cos is the command used to compute a cosine :

>> import math
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log'
, 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> math.cos(0.1)
0.99500416527802582
>>>

The online help is accessed with the command help():

>>> help(math.cos)
Help on built-in function cos in module math :

cos(...)
    cos(x)
    
    Return the cosine of x (measured in radians).

help(math) enumerates all functions found in the math module. The online help is quite useful and also available for all Metafor modules.

It is also possible to import all functions found in math in the current namespace with the command :

>>> from math import *
>>> cos(0.1)
0.99500416527802582
>>>

With this syntax, the math prefix is no longer necessary. However, conflicts could occur with other modules if they also contain a function named cos.

To use mathematical functions, the module math must be imported. In the same way, the functions which are used to build a data set in Metafor must be imported from the module wrap, using the command from wrap import *. A list of materials can also be imported using the command import toolbox.createMaterial. In this case, the module no longer contains functions but objects.

Objects

Python is object-oriented. This means that classes can be created. To make it short, a class is a structure containing data, to which methods can be associated. For example, to compute the length of a vector, a function can be defined :

def vectLength(x,y,z):
    import math
    return math.sqrt(x*x+y*y+z*z)
At this point, it should be noted that a block of several instructions is defined with the indentation, in opposition to C which uses braces. Ending a block is done by decreasing the indentation. It may sounds complicated at first, however this way Python users are forced to indent their code, making it more readable.

The function called vectLength computes the length of the vector (x,y,z). However, this is not object-oriented, because the encapsulation principle is violated (the user is directly manipulating the components). In order to have an object oriented code, a class (so a new type) representing this vector is created :

class vector:
    def __init__(self,x,y,z):
        self.x=x
        self.y=y
        self.z=z
    def view(self):
        print 'x=',self.x, ' y=',self.y, ' z=',self.z     
    def length(self):
        import math
        return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)

Three methods (or member functions) were defined : __init__, the constructor (see below) ; view(), displaying the vector using the function print ; and length, returning the length. Each method is defined within the class, see the indent.

To compute the length of a vector, this vector is first created using the command

>>> v=vector(1,1,1)

This command calls the constructor (method __init__) of the class named vector. It should be noted that this function is defined with four parameters, the first one being self (equivalent to the pointer this in C++), but called with only three parameters (the self pointer is passed implicitly).

>>> type(v)
<type 'instance'>
>>> v.view()
x= 1  y= 1  z= 1
>>> v.length()   
1.7320508075688772
>>>

When creating a data set in Metafor, the user handles classes defined in the modules found in the folder wrap. Therefore, the user should understand basic object-oriented programming, even if a data set may be written without defining new objects.

Loop - tuple - list

In a Metafor data set, the same operation may be used several times in a row (for example, meshing the curves numbered from 1 to 10). In such a case, loops are used. A loop is written as :

for i in (1,6,8,12):
    print 'i=',i

where the values in parentheses constitute a “tuple”. In this example, “i” will successfully take the values 1, 6, 8 and 12, leading to four executions of the command print.

Instead of tuples, lists may also be used. To do so, brackets are used instead of parentheses. Unlike tuples, lists may be modified.

To create a list, the function range(i,j,k) is quite often used. This function works as i:k:j in Matlab and i j k in Bacon (Samcef).

>>> range(1,10,2)
[1, 3, 5, 7, 9]

A list may also be defined as :

[ x for x in range(100) if x%3==0 ]

leading to all numbers from 0 to 99 which can be divided by 3.

Conditional constructs

It may be useful to parametrize a data set in a complex way using conditional statements. For example, a Boolean useLinearMaterial can be defined, to choose whether the material behaves in an linear way. This parameter, defined in the beginning of the data file, is easy to modify and leads to a conditional definition of a linear material. Such a construct requires the command if, which is used as :

if x>100:
    print "x>100"
elif x>10:
    print "x>10"
else:
    print "x<=10"

Important notes

  • The True and False Booleans are noted with capital letter.
  • If two integers are divided, Python will do an INTERGER division, as most compiled languages (C, Fortran). This means that 2/3 = 0 :!:, for example. If a float number is desired, a float number must be used in the division, either 2.0/3 or 2/3.0.
  • A number starting with 0 corresponds to a number defined using the octal numeral system. For example, 012 corresponds to 10 in decimal.
  • The command raw_input('message') is used to ask the user to enter a value. This is useful to pause the data set, for example to view an intermediate mesh.
  • The function print a,b,c prints the objects a, b et c on the same line, which can be quite useful for Metafor objects.
  • The null command is called pass.
  • Several commands may be written on the same line if separated by a semicolon, as in C.
  • Strings are defined with simple ('), double (“) or triple quotation marks (”“”).

Conclusions

In this page, the basic use of Python in a Metafor context was shown. However, it is useful to read others sources in order to understand the language better. More complex objects and commands exist (dictionaries, I/O commands, …) and can be used to improve the efficiency and clarity of a data set. If you are interested by these aspects, please contact me.

After reading this introduction to Python, this language can be used to define a first data set in Metafor :

How to build my own FE model?

doc/user/tutorials/tuto0.1507648729.txt.gz · Last modified: 2017/10/10 17:18 by boman

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki