Metafor

ULiege - Aerospace & Mechanical Engineering

User Tools

Site Tools


doc:user:tutorials:tuto0

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
doc:user:tutorials:tuto0 [2015/02/12 11:43] – [Introduction] zianedoc:user:tutorials:tuto0 [2020/09/08 16:26] (current) – [Conclusions] boman
Line 1: Line 1:
- 
 ====== Python in a nutshell ====== ====== Python in a nutshell ======
- 
- 
-===== Introduction ===== 
  
 This section shows how to use [[doc:user:general:glossaire#Python]], the interpretor used by [[doc:user:general:glossaire#Metafor]], in a basic way. Ideally, [[http://www.python.org/|Python official website]] should be used. This section shows how to use [[doc:user:general:glossaire#Python]], the interpretor used by [[doc:user:general:glossaire#Metafor]], in a basic way. Ideally, [[http://www.python.org/|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. +Python is a powerful scripting language allowing the creation of input files in a very convenient way for the developer, but it might look a bit tedious for a new user.
-===== The interpreter =====+
  
  
- +===== Introduction =====
-==== Introduction ====+
  
 When Metafor is started, a window appears: When Metafor is started, a window appears:
Line 22: Line 16:
 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. 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".+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 root namespace.
  
-A Metafor [[doc:user:general:glossaire#data set]] is a series of Python commands. An obvious disadvantage is that this is quite far away from the user-friendly graphical interfaces [[doc:user:general:glossaire#samcef|Samcef Fields]] or [[doc:user:general:glossaire#abaqus|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.+A Metafor [[doc:user:general:glossaire#input file]] is a series of Python commands. An obvious disadvantage of a python script is that it is less user-friendly than graphical interfaces of [[doc:user:general:glossaire#samcef|Samcef]] or [[doc:user:general:glossaire#abaqus|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 [[doc:user:general:glossaire#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.+Another interesting aspect of Python is its ability to interface compiled [[doc:user:general:glossaire#C++]] code without the help of the programmer (the modules ''wrap'' are automatically created from the C++ 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 :+Python is quite simple. For example, it can be used as a calculator in interactive mode:
  
   >>> a=2   >>> a=2
Line 37: Line 31:
   >>>   >>>
  
-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''.+In a script, the correct syntax to get the value of ''c'' requires 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. \\+The definition of variables allows the parametrization of Metafor input files. 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()'' To display memory contents, use ''dir()''
Line 56: Line 50:
   'IndentationError', 'IndexError ...   'IndentationError', 'IndexError ...
  
-==== Types ====+===== 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 [[doc:user:general:glossaire#Fortran]] or C.+The type of a variable is obtained with the command ''type(var)''. Every variable has a type (also called a "class"), however in Python the type of a variable can change during the execution of the code, unlike in [[doc:user:general:glossaire#Fortran]] or C.
  
   >>> a=4   >>> a=4
   >>> type(a)   >>> type(a)
-  <type 'int'>+  <class 'int'>
   >>> a='text'   >>> a='text'
   >>> type(a)   >>> type(a)
-  <type 'str'>+  <class 'str'>
   >>>   >>>
  
-Metafor uses the basic types (float, string, integer, tuple, ...), but also its own types, which are defined with the use of classes. +Metafor uses the basic python types (float, string, integer, tuple, ...), but also its own types, which are defined by custom 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". 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".
Line 74: Line 68:
  
  
-==== Functions ====+===== 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 : +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   >>> def square(x): return x*x
Line 84: Line 78:
   >>>   >>>
  
-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 [[doc:user:general:glossaire#matrice de contact|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.+Functions are essential in the proper writing of an input file. This way, complex operations may be defined and called several times, from the same module or even from other ones. For example, if the numerical model contains several similar [[doc:user:general:glossaire#matrice de contact|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 :+Default values for the parameters of python functions may be set:
  
 <code python> <code python>
Line 103: Line 97:
   myfun = lambda x, a=1, b=1, c=0 : a*x*x+b*x+c   myfun = lambda x, a=1, b=1, c=0 : a*x*x+b*x+c
  
-==== Modules ====+===== Modules =====
  
 It is quite useful to gather several functions into a file, to form a [[doc:user:general:glossaire#module]] (one module is defined with one file). In Metafor, every [[doc:user:general:glossaire#test case]] is defined in a [[doc:user:general:glossaire#module]]. For example, the test case named ''cont2'' is located in ''Metafor/apps/qs/cont2.py'' and identified by ''apps.qs.cont2'' under Python. It is quite useful to gather several functions into a file, to form a [[doc:user:general:glossaire#module]] (one module is defined with one file). In Metafor, every [[doc:user:general:glossaire#test case]] is defined in a [[doc:user:general:glossaire#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 : +By default, Python already contains many modules. For example, the module called ''math'' defines all basic mathematical functions. To use a module, the statement ''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   >> import math
   >>> dir(math)   >>> dir(math)
-  ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', +  ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh',  
-  'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log' +  'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh',  
-  , 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']+  'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',  
 +  ... 
 +  'sqrt', 'tan', 'tanh', 'tau', 'trunc']
   >>> math.cos(0.1)   >>> math.cos(0.1)
   0.99500416527802582   0.99500416527802582
Line 121: Line 117:
  
   >>> help(math.cos)   >>> help(math.cos)
-  Help on built-in function cos in module math :+  Help on built-in function cos in module math:
      
   cos(...)   cos(...)
Line 130: Line 126:
 ''help(math)'' enumerates all functions found in the ''math'' module. The online help is quite useful and also available for all Metafor modules. ''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 :+It is also possible to import all functions found in ''math'' in the current namespace with the command:
  
   >>> from math import *   >>> from math import *
Line 139: Line 135:
 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''. 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 *''+To use mathematical functions, the module ''math'' must be imported. In the same way, the functions which are used to build an input file 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 ====+===== Objects =====
  
 Python is [[doc:user:general:glossaire#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 : Python is [[doc:user:general:glossaire#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 :
  
 <code python> <code python>
-def vectLength(x,y,z):+def vectLength(x, y, z):
     import math     import math
-    return math.sqrt(x*x+y*y+z*z)+    return math.sqrt(x*x + y*y + z*z)
 </code> </code>
  
Line 157: Line 151:
 </note> </note>
  
-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 :+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:
  
 <code python> <code python>
 class vector: class vector:
     def __init__(self,x,y,z):     def __init__(self,x,y,z):
-        self.x=x +        self.x = x 
-        self.y=y +        self.y = y 
-        self.z=z+        self.z = z
     def view(self):     def view(self):
-        print 'x=',self.x, ' y=',self.y, ' z=',self.z     +        print('x=', self.x, ' y=', self.y, ' z=', self.z    
     def length(self):     def length(self):
         import math         import math
-        return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)+        return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)
 </code> </code>
  
-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 classsee the indent.+Three methods (or member functions) have been 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 indentation).
  
 To compute the length of a vector, this vector is first created using the command To compute the length of a vector, this vector is first created using the command
  
-  >>> v=vector(1,1,1)+  >>> 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). 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(v)
-  <type 'instance'>+  <class '__main__.vector'>
   >>> v.view()   >>> v.view()
   x= 1  y= 1  z= 1   x= 1  y= 1  z= 1
Line 188: Line 182:
   >>>   >>>
  
-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. +When creating an input file in Metafor, the user manipulates classes defined in the modules found in the folder ''wrap''. Therefore, the user should understand basic object-oriented programming, even if an input file may be written without defining new objects.
-==== Loop - tuple - list ====+
  
-In a Metafor [[doc:user:general:glossaire#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 :+ 
 +===== Loop - tuples - lists ===== 
 + 
 +In a Metafor [[doc:user:general:glossaire#input file]], 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:
  
 <code python> <code python>
-for i in (1,6,8,12): +for i in (1, 6, 8, 12): 
-    print 'i=',i+    print('i=', i)
 </code> </code>
  
Line 202: Line 198:
 Instead of tuples, lists may also be used. To do so, brackets are used instead of parentheses. Unlike tuples, lists may be modified. 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 [[doc:user:general:glossaire#Bacon]] ([[doc:user:general:glossaire#Samcef]]).+To create a list, the function ''range(i, j, k)'' is quite often used. This function works as ''i:k:j'' in Matlab.
  
-  >>> range(1,10,2)+  >>> list(range(1, 10, 2))
   [1, 3, 5, 7, 9]   [1, 3, 5, 7, 9]
  
Line 214: Line 210:
  
  
-==== Conditional constructs  ====+===== Conditional statements =====
  
-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 : +It may be useful to parametrize an input file 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 input 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 : 
  
 <code python> <code python>
 if x>100: if x>100:
-    print "x>100"+    print ("x>100")
 elif x>10: elif x>10:
-    print "x>10"+    print ("x>10")
 else: else:
-    print "x<=10"+    print ("x<=10")
 </code> </code>
    
  
-==== Important notes ====+===== Important notes =====
  
  
-  * The ''True'' and ''False'' Booleans are noted with capital letter+  * 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, [[doc:user:general:glossaire#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.   * 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 command ''input('message')'' is used to ask the user to enter a value. This is useful to pause the input file, 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 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''.+  * The null command is named ''pass''.
  
   * Several commands may be written on the same line if separated by a semicolon, as in C.   * Several commands may be written on the same line if separated by a semicolon, as in C.
Line 248: Line 242:
  
    
 +===== Conclusions =====
  
 +In this page, the basic use of [[doc:user:general:glossaire#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 an input file. 
  
-===== Conclusions =====+After reading this introduction to Python, this language can be used to define a first input file in Metafor: 
  
-In this page, the basic use of [[doc:user:general:glossaire#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 [[r_boman@yahoo.fr|contact me]].+=> [[doc:user:tutorials:tuto1]]
  
-After reading this introduction to Python, this language can be used to define a first data set in Metafor :  
  
-=> [[doc:user:tutorials:tuto1]] 
doc/user/tutorials/tuto0.1423737830.txt.gz · Last modified: 2016/03/30 15:22 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki