]> SALOME platform Git repositories - tools/eficas.git/blob - Noyau/N_ENTITE.py
Salome HOME
reindent + copyright + merge manuel avec la V9_dev sauf repertoires metier
[tools/eficas.git] / Noyau / N_ENTITE.py
1 # coding=utf-8
2 # ======================================================================
3 # COPYRIGHT (C) 2007-2021  EDF R&D                  
4 # THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
5 # IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
6 # THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
7 # (AT YOUR OPTION) ANY LATER VERSION.
8 #
9 # THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
10 # WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
11 # MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
12 # GENERAL PUBLIC LICENSE FOR MORE DETAILS.
13 #
14 # YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
15 # ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
16 #    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
17 #
18 #
19 # ======================================================================
20
21
22 """
23     Ce module contient la classe ENTITE qui est la classe de base
24     de toutes les classes de definition d'EFICAS.
25 """
26
27 from __future__ import absolute_import
28 from __future__ import print_function
29 try :
30     from builtins import str
31     from builtins import object
32 except :
33     pass
34 import re
35 from . import N_CR
36 from . import N_OPS
37 from . import N_VALIDATOR
38
39 import six
40 stringTypes = (str, six.text_type)
41
42
43 class ENTITE(object):
44
45     """
46        Classe de base pour tous les objets de definition : mots cles et commandes
47        Cette classe ne contient que des methodes utilitaires
48        Elle ne peut être instanciee et doit d abord être specialisee
49     """
50     CR = N_CR.CR
51     factories = {'validator': N_VALIDATOR.validatorFactory}
52
53     def __init__(self, validators=None):
54         """
55            Initialise les deux attributs regles et entites d'une classe dérivée
56            à : pas de règles et pas de sous-entités.
57
58            L'attribut regles doit contenir la liste des regles qui s'appliquent
59            sur ses sous-entités
60
61            L'attribut entités doit contenir le dictionnaires des sous-entités
62            (clé = nom, valeur=objet)
63         """
64         self.regles = ()
65         self.entites = {}
66         if validators:
67             self.validators = self.factories['validator'](validators)
68         else:
69             self.validators = validators
70         #self.doitSenregistrerComme = None
71         self.txtNomComplet=''
72         self.redefinit=False
73         self.dejaPrepareDump=False
74
75     def affecter_parente(self):
76         """
77             Cette methode a pour fonction de donner un nom et un pere aux
78             sous entités qui n'ont aucun moyen pour atteindre leur parent
79             directement
80             Il s'agit principalement des mots cles
81         """
82         for k, v in list(self.entites.items()):
83             #print( k,v)
84             v.pere = self
85             v.nom = k
86
87     def verifCata(self):
88         """
89             Cette methode sert à valider les attributs de l'objet de définition
90         """
91         raise NotImplementedError("La méthode verifCata de la classe %s doit être implémentée"
92                                   % self.__class__.__name__)
93
94     def __call__(self):
95         """
96             Cette methode doit retourner un objet dérivé de la classe OBJECT
97         """
98
99         raise NotImplementedError("La méthode __call__ de la classe %s doit être implémentée"
100                                   % self.__class__.__name__)
101
102     def report(self):
103         """
104            Cette méthode construit pour tous les objets dérivés de ENTITE un
105            rapport de validation de la définition portée par cet objet
106         """
107         self.cr = self.CR()
108         self.verifCata()
109         for k, v in list(self.entites.items()):
110             try:
111                 cr = v.report()
112                 cr.debut = u"Début " + v.__class__.__name__ + ' : ' + k
113                 cr.fin = u"Fin " + v.__class__.__name__ + ' : ' + k
114                 self.cr.add(cr)
115             except:
116                 self.cr.fatal("Impossible d'obtenir le rapport de %s %s" % (k, repr(v)))
117                 print(("Impossible d'obtenir le rapport de %s %s" % (k, repr(v))))
118                 print(("père =", self))
119         return self.cr
120
121     def verifCataRegles(self):
122         """
123            Cette méthode vérifie pour tous les objets dérivés de ENTITE que
124            les objets REGLES associés ne portent que sur des sous-entités
125            existantes
126         """
127         for regle in self.regles:
128             l = []
129             for mc in regle.mcs:
130                 if not mc in  self.entites :
131                     l.append(mc)
132             if l != []:
133                 txt = str(regle)
134                 self.cr.fatal(
135                     _(u"Argument(s) non permis : %r pour la règle : %s"), l, txt)
136
137     def checkDefinition(self, parent):
138         """Verifie la definition d'un objet composite (commande, fact, bloc)."""
139         args = self.entites.copy()
140         mcs = set()
141         for nom, val in list(args.items()):
142             if val.label == 'SIMP':
143                 mcs.add(nom)
144                 # XXX
145                 # if val.max != 1 and val.type == 'TXM':
146                     # print "#CMD", parent, nom
147             elif val.label == 'FACT':
148                 val.checkDefinition(parent)
149                 # CALC_SPEC !
150                 # assert self.label != 'FACT', \
151                    #'Commande %s : Mot-clef facteur present sous un mot-clef facteur : interdit !' \
152                    #% parent
153             else:
154                 continue
155             del args[nom]
156         # seuls les blocs peuvent entrer en conflit avec les mcs du plus haut
157         # niveau
158         for nom, val in list(args.items()):
159             if val.label == 'BLOC':
160                 mcbloc = val.checkDefinition(parent)
161                 # XXX
162                 # print "#BLOC", parent, re.sub('\s+', ' ', val.condition)
163                 assert mcs.isdisjoint(mcbloc), "Commande %s : Mot(s)-clef(s) vu(s) plusieurs fois : %s" \
164                     % (parent, tuple(mcs.intersection(mcbloc)))
165         return mcs
166
167     def checkOp(self, valmin=-9999, valmax=9999):
168         """Vérifie l'attribut op."""
169         if self.op is not None and \
170            (type(self.op) is not int or self.op < valmin or self.op > valmax):
171             self.cr.fatal(_(u"L'attribut 'op' doit être un entier "
172                             u"compris entre %d et %d : %r"), valmin, valmax, self.op)
173
174     def checkProc(self):
175         """Vérifie l'attribut proc."""
176         if self.proc is not None and not isinstance(self.proc, N_OPS.OPS):
177             self.cr.fatal(
178                 _(u"L'attribut op doit être une instance d'OPS : %r"), self.proc)
179
180     def checkRegles(self):
181         """Vérifie l'attribut regles."""
182         if type(self.regles) is not tuple:
183             self.cr.fatal(_(u"L'attribut 'regles' doit être un tuple : %r"),
184                           self.regles)
185
186     def checkFr(self):
187         """Vérifie l'attribut fr."""
188         if type(self.fr) not in stringTypes:
189             self.cr.fatal(
190                 _(u"L'attribut 'fr' doit être une chaine de caractères : %r"),
191                 self.fr)
192
193     def checkDocu(self):
194         """Vérifie l'attribut docu."""
195         if type(self.docu) not in stringTypes:
196             self.cr.fatal(
197                 _(u"L'attribut 'docu' doit être une chaine de caractères : %r"),
198                 self.docu)
199
200     def checkNom(self):
201         """Vérifie l'attribut proc."""
202         if type(self.nom) is not str:
203             self.cr.fatal(
204                 _(u"L'attribut 'nom' doit être une chaine de caractères : %r"),
205                 self.nom)
206
207     def checkReentrant(self):
208         """Vérifie l'attribut reentrant."""
209         if self.reentrant not in ('o', 'n', 'f'):
210             self.cr.fatal(
211                 _(u"L'attribut 'reentrant' doit valoir 'o','n' ou 'f' : %r"),
212                 self.reentrant)
213
214     def checkStatut(self, into=('o', 'f', 'c', 'd')):
215         """Vérifie l'attribut statut."""
216         if self.statut not in into:
217             self.cr.fatal(_(u"L'attribut 'statut' doit être parmi %s : %r"),
218                           into, self.statut)
219
220     def checkCondition(self):
221         """Vérifie l'attribut condition."""
222         if self.condition != None:
223             if type(self.condition) is not str:
224                 self.cr.fatal(
225                     _(u"L'attribut 'condition' doit être une chaine de caractères : %r"),
226                     self.condition)
227         else:
228             self.cr.fatal(_(u"La condition ne doit pas valoir None !"))
229
230     def checkMinMax(self):
231         """Vérifie les attributs min/max."""
232         if type(self.min) != int:
233             if self.min != '**'and self.min != float('-inf'):
234                 self.cr.fatal(
235                     _(u"L'attribut 'min' doit être un entier : %r"), self.min)
236         if type(self.max) != int:
237             if self.max != '**' and self.max != float('inf'):
238                 self.cr.fatal(
239                     _(u"L'attribut 'max' doit être un entier : %r"), self.max)
240         if self.min > self.max:
241             self.cr.fatal(
242                 _(u"Nombres d'occurrence min et max invalides : %r %r"),
243                 self.min, self.max)
244
245     def checkValidators(self):
246         """Vérifie les validateurs supplémentaires"""
247         if self.validators and not self.validators.verifCata():
248             self.cr.fatal(_(u"Un des validateurs est incorrect. Raison : %s"),
249                           self.validators.cata_info)
250
251     def checkHomo(self):
252         """Vérifie l'attribut homo."""
253         if self.homo != 0 and self.homo != 1:
254             self.cr.fatal(
255                 _(u"L'attribut 'homo' doit valoir 0 ou 1 : %r"), self.homo)
256
257     def checkInto(self):
258         """Vérifie l'attribut into."""
259         if self.into != None:
260             if (type(self.into) not in (list, tuple)) and (type(self.into) != types.FunctionType) :
261                 self.cr.fatal(
262                     _(u"L'attribut 'into' doit être un tuple : %r"), self.into)
263
264     def checkPosition(self):
265         """Vérifie l'attribut position."""
266         if self.position not in ('local', 'global', 'global_jdc', 'inGetAttribut', 'reCalculeEtape'):
267             self.cr.fatal(_(u"L'attribut 'position' doit valoir 'local', 'global' ,'global_jdc', 'inGetAttribut', 'reCalculeEtape' "
268                             u"ou 'global_jdc' : %r"), self.position)
269
270     def nomComplet(self):
271         if self.txtNomComplet  != '' : return self.txtNomComplet
272         qui=self
273         while hasattr(qui, 'pere' ):
274             self.txtNomComplet+='_'+qui.nom
275             qui=qui.pere
276         self.txtNomComplet+='_'+qui.nom
277         return self.txtNomComplet
278
279     def geneaCompleteSousFormeDeListe(self):
280         geneaCompleteSousFormeDeListe=[]
281         qui=self
282         while hasattr(qui, 'pere' ):
283             geneaCompleteSousFormeDeListe.append(qui)
284             qui=qui.pere
285         geneaCompleteSousFormeDeListe.append(qui)
286         return geneaCompleteSousFormeDeListe
287
288     def addDefinitionMC(self,listeMCAvant,**args):
289         ouChercher=self
290         for mot in listeMCAvant:
291             try :
292                 ouChercher=ouChercher.entites[mot]
293             except :
294                 print ('impossible de trouver : ',mot,' ',listeMCAvant)
295         (nomMC,defMC)=args.items()[0]
296         defMC.pere = ouChercher
297         defMC.pere.propageRedefinit()
298         defMC.nom = nomMC
299         cata = CONTEXT.getCurrentCata()
300         #print (cata)
301         ouChercher.entites[nomMC]=defMC
302
303     def changeDefinitionMC(self,listeMCAvant,**args):
304         ouChercher=self
305         for mot in listeMCAvant:
306             try :
307                 ouChercher=ouChercher.entites[mot]
308             except :
309                 print ('impossible de trouver : ',mot,' ',listeMCAvant)
310         monSIMP=ouChercher
311         for (nomAttributDef,valeurAttributDef) in args.items():
312             if hasattr(monSIMP, nomAttributDef) :
313                 setattr(monSIMP, nomAttributDef, valeurAttributDef)
314             else :
315                 print ('pb avec ', nomAttributdef,valeurAttributMC)
316         monSIMP.propageRedefinit()
317
318     def propageRedefinit(self):
319     # a reflechir
320         self.redefinit=True
321         # PNPN il faut remonter a l etape
322
323
324
325     def makeObjetPourVerifSignature(self,*args,**kwargs):
326         etape = self.class_instance(oper=self, args=kwargs)
327         etape.MCBuild()
328         return etape
329
330
331     def dumpStructure(self,decal=0):
332         if self.label == 'SIMP':
333             texte = decal * '   ' + self.nom + ' \n'
334             return texte
335         texte = decal * '   ' + self.nom
336         if self.label == 'BLOC' : texte+= " " + self.condition
337         if self.label == 'OPER' : texte+ " " + str(self.sd_prod) + "\n"
338         texte+=' \n'
339         for c in self.entites.values():
340             texte+=c.dumpStructure(decal+1)
341         texte += decal * '   ' + 'fin pour   ' + self.nom + ' \n'
342         return texte