5. Use of python in command files#

You don’t need to know the Python language to use*Code_Aster*. In fact, with some basic rules to be respected concerning indentation and parenthesis, only knowledge of the command language described in order catalogs is necessary. And again, EFICAS makes it possible to avoid using the catalog or the « syntax » paragraph of commands by graphically offering the keywords to fill in.

However, the advanced user will be able to make good use of the power of the PYTHON language in his command file, since this one is already written in this language.

The four main uses can be: writing custom macro commands, using general Python instructions, importing useful python modules, retrieving information from Code_Aster data structures into variables PYTHON.

Note:

If you want to use accented French characters in the command file or imported modules, you must place the following instruction in the first or second line of the file:

# —— coding: iso—8859—1 —

In python 2.3, the absence of this line causes a warning which will become an error in python 2.4; in ASTER, it is always an error.

5.1. Custom macro controls#

See document [D5.01.02]: « Introducing a new macro command ».

Custom macro commands are very easy to program. They can be used to capitalize recurring calculation schemes and thus constitute a business tool. It is strongly recommended to use existing macro commands as an example: Macro package in the bibpyt directory.

5.2. General instructions PYTHON and useful modules#

Advanced users can take great advantage of using loops (for), tests (if), exceptions (try, except) and in general all the power of the PYTHON language directly in their command file. The list of uses is impossible to establish comprehensively. Numerous examples are present in the test cases in the test base. For example, we can do mesh adaptation by placing the calculation/remeshing sequence in a loop, establish a criterion for stopping iterations by a test on a calculated value.

Consult the following paragraph dedicated to « particularized » Aster exceptions.

In a loop, if you recreate an already existing concept, you must remember to destroy it first with the DETRUIRE command.

Other various Python features of interest to the Code_Aster user may be:

  • read-write to files,

  • numerical calculation (for example using Numerical Python),

  • the call via the os module to the scripting language, and in particular the launch of a third-party code (os.system)

  • the manipulation of character strings

  • the call to graphics modules (grace, gnuplot)

5.3. Aster module exceptions PYTHON#

The Python exception mechanism is very interesting, for example, it allows you to « try » a command and then regain control if it « crashes » by raising a particular exception:

Try:

instruction block

except error identified, message:

instruction block executed if IdentifiedError occurs...

In the command file, this mechanism can be used with any exception from standard Python modules.

<F>Exceptions specific to Code_Aster (to the aster module) are also available, divided into two categories, the exceptions associated with errors<S>, and the exception associated with errors.

5.3.1. Interception of errors <S>#

In the event of an error<S>, the error is identified by one of these exceptions:

aster.nonconvergenceError

in case of non-convergence of the calculation,

aster.echecBehaviorError

problem integrating the law of behavior,

aster.bandeFrequenceVideError

no mode found in the frequency band,

aster.matriceSinguliereError

singular matrix,

aster.ProcessContactError

problem processing the contact,

aster.matriceContactSingularyError

singular contact matrix,

aster.Stop CPUError

Stop due to lack of time CPU.

All of these exceptions derive from the <S>general exception which is aster.error. This means that exceptaster.error catches all of the exceptions listed below. However, it is always better to specify what error you expect!

Example of use:

Try:

resu = STAT_NON_LINE (...)

except aster.NonConvergenceError, message:

print 'Stopped for this reason: %s'% str (message)

# We know that it takes a lot more iterations to converge

print "We continue by increasing the number of iterations."

resu = STAT_NON_LINE (reuse = resu,

... ,

CONVERGENCE =_F (ITER_GLOB_MAXI =400,),)

except aster.error, message:

print "Another error has occurred: %s"% str (message)

Print "Stop"

from Utilitai.Utmess import UTMESS

UTMESS ('F', 'Example', <S>'Unexpected Error')

5.3.2. <F>Interception of fatal errors#

In the event of a fatal error, the behavior can be modified by the user.

By default, the code stops in error<F>, you can see the error feedback (calling the Fortran routines) in the output file.

If desired, the code can raise the aster.FatalError exception, and in this case (as for an error<S>), if the exception is caught by an except, the user takes control again, otherwise the code stops (no Fortran error report).

This choice is determined in the DEBUT/POURSUITE commands, keyword keyword factor ERREUR (cf. [U4.11.01] and [U4.11.03]) and at any time by the aster.onFatalError method.

This last one, called with no arguments, returns the current behavior in case of a fatal error:

count = aster.onFatalError ()

print « Common behavior in case of a fatal error: %s »% comport

and allows you to define the behavior you want:

aster.onFatalError (“EXCEPTION”) # we raise the FatalError exception

or

aster.onFatalError (“ABORT”) # we stop with error feedback.

5.3.3. Validity of concepts in the event of an exception being withdrawn#

When an exception is raised and caught (by except), the concept produced by the command in which the error occurred is rendered as it is, the command having not completed normally.

In some cases, especially after a fatal error, the product concept may not be usable; then use DETRUIRE to remove it.

Likewise, if you want to reuse the name of the concept to create a new one, you must DETRUIRE the one obtained in the try.

In case of errors <S>raised in STAT/DYNA_NON_LINE, the concept is generally valid, and can be reused (reuse keyword) to continue the calculation with another strategy (as in the example mentioned above).

Finally, before handing over to the user, the objects in the volatile database are removed by a call to JEDETV, and the Jeveux mark is repositioned to 1 (with JEDEMA) to release the objects brought back into memory.

5.3.4. Precautions for using exceptions#

<S><F>The two exceptions aster.error and aster.FatalError are independent (neither derives from the other), which means that if you want to take control in case of error and error:

  • Exception throwing must be activated in case of error <F>with aster.FatalError (“EXCEPTION”) or in DEBUT/POURSUITE.

  • you have to catch both exceptions:

except (aster.fatalError, aster.error), message:…

It is not recommended to use « except: » without specifying what exception is expected (this is a general rule in Python regardless of Aster exceptions). Indeed, the processing performed under the EXCEPT is unlikely to be valid in all cases of error.

Likewise, as in the example given above, it is better to use the particularized exceptions NonConvergenceError, Stop CPUError,… than the higher-level exception aster.error; always in the idea of knowing exactly what happened.

5.4. Retrieving values calculated in variables PYTHON#

Exploiting the PYTHON language in your command file is only interesting if you can conditionally launch actions based on what the code has calculated.

Some bridges exist between Python and the data structures calculated by the code and present in memory JEVEUX. Others remain to be programmed; this is an evolving field and future developments are expected.

It is essential to understand that recovering calculated data requires that the instructions for obtaining it have been executed in advance. In other words, it is essential to execute the code in mode PAR_LOT =” NON “(key word for the DEBUT command). Indeed, in this case, there is no global analysis of the command file, but each instruction is executed sequentially. When we arrive at an instruction, all the concepts preceding it have therefore already been calculated.

Here are some methods for accessing data structures. The list is not exhaustive, refer to the documentation [U1.03.02].

Data structure

Method

Python type returned

Information returned

listr8

LIST_VALEURS

list

List of values

mesh

LIST_GROUP_NO

list

List of node groups

LIST_GROUP_MA

list

List of mesh groups

table

[…]

real

Table content

function

LISTE_VALEURS

list

List of values

result

LIST_CHAMPS

list

List of calculated fields

LIST_NOM_CMP

list

List of components

LIST_VARI_ACCES

list

List of access variables

LIST_PARA

list

Parameter list

cham_no

EXTR_COMP

post_comp_cham_no

Contents of the field in a table

cham_elem

EXTR_COMP

post_comp_cham_el

Contents of the field in a table

Any object JEVEUX

getvectjev

list

List of objects in the vector I want

5.5. Example of dynamic construction of keywords (factors)#

In the case of a keyword factor that is very repetitive to write, the user may want to compose his content by script, in a list or a dictionary, which he will then provide to the keyword factor. The example below shows three ways to write the same factor keyword.

DEBUT (PAR_LOT =” NON “)

ooo= [_F (JUSQU_A =1. , PAS =0.1),

_F (JUSQU_A =2. , PAS =0.1),

_F (JUSQU_A =3. , PAS =0.1)]

ppp= [_F (JUSQU_A =float (i), PAS =0.1) for i in range (1,4)]

qqq= [{“JUSQU_A “:float (i),” PAS “:0.1} for i in range (1,4)]

rrr= [_F (**args) for args in qqq]

li1= DEFI_LIST_REEL (DEBUT =0. ,

INTERVALLE =ooo

/or

INTERVALLE =ppp

/or

INTERVALLE =rrr

)

FIN ()