Salome HOME
bug
[tools/eficas.git] / Noyau / N_FONCTION.py
1 # coding=utf-8
2 # Copyright (C) 2007-2017   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19
20 # Attention : cet import permet d'avoir, en Python, le comportement
21 # de la division réelle pour les entiers, et non la division entière
22 # 1/2=0.5 (et non 0). Comportement par défaut dans Python 3.0.
23 from __future__ import division
24 from __future__ import absolute_import
25 try :
26    from builtins import zip
27    from builtins import str
28 except :
29    pass
30 from math import sin, cos, tan, asin, acos, atan2, atan, sinh, cosh, tanh
31 from math import pi, exp, log, log10, sqrt
32
33 from .N_ASSD import ASSD
34 from six.moves import zip
35
36
37 class FONCTION(ASSD):
38     pass
39
40
41 class formule(ASSD):
42
43     def __init__(self, *args, **kwargs):
44         ASSD.__init__(self, *args, **kwargs)
45         self.nompar = None
46         self.expression = None
47         ctxt = {}
48         ctxt.update(getattr(self.parent, 'const_context', {}))
49         ctxt.update(getattr(self.parent, 'macro_const_context', {}))
50         self.parent_context = self.filter_context(ctxt)
51
52     def __call__(self, *val):
53         """Evaluation de la formule"""
54         # en POURSUITE, self.parent_context is None, on essaie de reprendre
55         # const_context
56         context = getattr(self, 'parent_context') or getattr(
57             self.parent, 'const_context', {})
58         for param, value in zip(self.nompar, val):
59             context[param] = value
60         try:
61             # globals() pour math.*
62             res = eval(self.code, context, globals())
63         except Exception as exc:
64             mes = "ERREUR LORS DE L EVALUATION DE LA FORMULE %s" %self.nom
65             print (mes)
66             raise
67         return res
68
69     def setFormule(self, nom_para, texte):
70         """Cette methode sert a initialiser les attributs
71         nompar, expression et code qui sont utilisés
72         dans l'évaluation de la formule."""
73         self.nompar = nom_para
74         self.expression = texte
75         try:
76             self.code = compile(texte, texte, 'eval')
77         except SyntaxError as exc:
78             mes = "ERREUR LORS DE LA CREATION  DE LA FORMULE %s" %self.nom
79             print (mes)
80             raise
81
82     def __setstate__(self, state):
83         """Cette methode sert a restaurer l'attribut code lors d'un unpickle."""
84         self.__dict__.update(state)                   # update attributes
85         self.setFormule(self.nompar, self.expression)  # restore code attribute
86
87     def __getstate__(self):
88         """Pour les formules, il faut enlever l'attribut code qui n'est
89         pas picklable."""
90         d = ASSD.__getstate__(self)
91         del d['code']
92         return d
93
94     def supprime(self, force=False):
95         """
96         Cassage des boucles de références pour destruction du JDC.
97         'force' est utilisée pour faire des suppressions complémentaires.
98
99         Pour être évaluées, les formules ont besoin du contexte des "constantes"
100         (objets autres que les concepts) qui sont soit dans (jdc).const_context,
101         soit dans (macro).macro_const_context.
102         On le stocke dans 'parent_context'.
103         Deux précautions valent mieux qu'une : on retire tous les concepts.
104
105         Lors de la suppression du concept, 'supprime' est appelée par
106         'build_detruire' avec force=True afin de supprimer le "const_context"
107         conservé.
108         """
109         if force:
110             for ctxt in ('parent_context', 'g_context'):
111                 if hasattr(self, ctxt):
112                     setattr(self, ctxt, None)
113         ASSD.supprime(self, force)
114
115     def Parametres(self):
116         """Equivalent de fonction.Parametres pour pouvoir utiliser des formules
117         à la place de fonctions dans certaines macro-commandes.
118         """
119         from SD.sd_fonction import sd_formule
120         from Utilitai.Utmess import UTMESS
121         if self.accessible():
122             TypeProl = {
123                 'E': 'EXCLU', 'L': 'LINEAIRE', 'C': 'CONSTANT', 'I': 'INTERPRE'}
124             sd = sd_formule(self.getName())
125             prol = sd.PROL.get()
126             nova = sd.NOVA.get()
127             if prol is None or nova is None:
128                 UTMESS('F', 'SDVERI_2', valk=[objev])
129             dico = {
130                 'INTERPOL': ['LIN', 'LIN'],
131                 'NOM_PARA': [s.strip() for s in nova],
132                 'NOM_RESU': prol[3][0:16].strip(),
133                 'PROL_DROITE': TypeProl['E'],
134                 'PROL_GAUCHE': TypeProl['E'],
135             }
136         else:
137             raise Accas.AsException(
138                 "Erreur dans fonction.Parametres en PAR_LOT='OUI'")
139         return dico
140
141
142 class formule_c(formule):
143     pass