====== Python in a nutshell ====== 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 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. ===== Introduction ===== When Metafor is started, a window appears: {{ doc:user:metafor-console.png |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 [[http://www.mathworks.com/|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 root namespace. 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 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 in interactive mode: >>> a=2 >>> b=3 >>> c=a+b >>> c 5 >>> 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 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()'' >>>> 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 (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 >>> type(a) >>> a='text' >>> type(a) >>> 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". ===== 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 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 the parameters of python functions 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 [[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 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 >>> dir(math) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', ... 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] >>> 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 an input file in Metafor must be imported from the module ''wrap'', using the command ''from wrap import *''. ===== 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 : 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) 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 >>> 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) >>> v.view() x= 1 y= 1 z= 1 >>> v.length() 1.7320508075688772 >>> 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 - 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: 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. >>> list(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 statements ===== 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 : 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. * 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 ''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 null command is named ''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 [[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. After reading this introduction to Python, this language can be used to define a first input file in Metafor: => [[doc:user:tutorials:tuto1]]