]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daCore/Interfaces.py
Salome HOME
Minor pending corrections on documentation and messages
[modules/adao.git] / src / daComposant / daCore / Interfaces.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2018 EDF R&D
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 """
24     Définit les outils d'interfaces normalisées de cas.
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27 __all__ = []
28
29 import os
30 import sys
31 import logging
32 import copy
33 import numpy
34 from daCore import Persistence
35 from daCore import PlatformInfo
36 from daCore import Templates
37
38 # ==============================================================================
39 class GenericCaseViewer(object):
40     """
41     Gestion des commandes de creation d'une vue de cas
42     """
43     def __init__(self, __name="", __objname="case", __content=None, __object=None):
44         "Initialisation et enregistrement de l'entete"
45         self._name         = str(__name)
46         self._objname      = str(__objname)
47         self._lineSerie    = []
48         self._switchoff    = False
49         self._numobservers = 2
50         self._content      = __content
51         self._object       = __object
52         self._missing = """raise ValueError("This case requires beforehand to import or define the variable named <%s>. When corrected, remove this command, correct and uncomment the following one.")\n# """
53     def _append(self, *args):
54         "Transformation de commande individuelle en enregistrement"
55         raise NotImplementedError()
56     def _extract(self, *args):
57         "Transformation d'enregistrement en commande individuelle"
58         raise NotImplementedError()
59     def _finalize(self, __upa=None):
60         "Enregistrement du final"
61         if __upa is not None and len(__upa)>0:
62             self._lineSerie.append("%s.execute()"%(self._objname,))
63             self._lineSerie.append(__upa)
64     def _addLine(self, line=""):
65         "Ajoute un enregistrement individuel"
66         self._lineSerie.append(line)
67     def _get_objname(self):
68         return self._objname
69     def dump(self, __filename=None, __upa=None):
70         "Restitution normalisée des commandes"
71         self._finalize(__upa)
72         __text = "\n".join(self._lineSerie)
73         __text +="\n"
74         if __filename is not None:
75             __file = os.path.abspath(__filename)
76             __fid = open(__file,"w")
77             __fid.write(__text)
78             __fid.close()
79         return __text
80     def load(self, __filename=None, __content=None, __object=None):
81         "Chargement normalisé des commandes"
82         if __filename is not None and os.path.exists(__filename):
83             self._content = open(__filename, 'r').read()
84         elif __content is not None and type(__content) is str:
85             self._content = __content
86         elif __object is not None and type(__object) is dict:
87             self._object = copy.deepcopy(__object)
88         else:
89             pass # use "self._content" from initialization
90         __commands = self._extract(self._content, self._object)
91         return __commands
92
93 class _TUIViewer(GenericCaseViewer):
94     """
95     Etablissement des commandes d'un cas ADAO TUI (Cas<->TUI)
96     """
97     def __init__(self, __name="", __objname="case", __content=None, __object=None):
98         "Initialisation et enregistrement de l'entete"
99         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
100         self._addLine("# -*- coding: utf-8 -*-")
101         self._addLine("#\n# Python script using ADAO TUI\n#")
102         self._addLine("from numpy import array, matrix")
103         self._addLine("import adaoBuilder")
104         self._addLine("%s = adaoBuilder.New('%s')"%(self._objname, self._name))
105         if self._content is not None:
106             for command in self._content:
107                 self._append(*command)
108     def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
109         "Transformation d'une commande individuelle en un enregistrement"
110         if __command is not None and __keys is not None and __local is not None:
111             __text  = ""
112             if __pre is not None:
113                 __text += "%s = "%__pre
114             __text += "%s.%s( "%(self._objname,str(__command))
115             if "self" in __keys: __keys.remove("self")
116             if __command not in ("set","get") and "Concept" in __keys: __keys.remove("Concept")
117             for k in __keys:
118                 __v = __local[k]
119                 if __v is None: continue
120                 if   k == "Checked" and not __v: continue
121                 if   k == "Stored"  and not __v: continue
122                 if   k == "AvoidRC" and __v: continue
123                 if   k == "noDetails": continue
124                 if isinstance(__v,Persistence.Persistence): __v = __v.values()
125                 if callable(__v): __text = self._missing%__v.__name__+__text
126                 if isinstance(__v,dict):
127                     for val in __v.values():
128                         if callable(val): __text = self._missing%val.__name__+__text
129                 numpy.set_printoptions(precision=15,threshold=1000000,linewidth=1000*15)
130                 __text += "%s=%s, "%(k,repr(__v))
131                 numpy.set_printoptions(precision=8,threshold=1000,linewidth=75)
132             __text.rstrip(", ")
133             __text += ")"
134             self._addLine(__text)
135     def _extract(self, __multilines="", __object=None):
136         "Transformation un enregistrement en une commande individuelle"
137         __is_case = False
138         __commands = []
139         __multilines = __multilines.replace("\r\n","\n")
140         for line in __multilines.split("\n"):
141             if "adaoBuilder.New" in line and "=" in line:
142                 self._objname = line.split("=")[0].strip()
143                 __is_case = True
144                 logging.debug("TUI Extracting commands of '%s' object..."%(self._objname,))
145             if not __is_case:
146                 continue
147             else:
148                 if self._objname+".set" in line:
149                     __commands.append( line.replace(self._objname+".","",1) )
150                     logging.debug("TUI Extracted command: %s"%(__commands[-1],))
151         return __commands
152
153 class _EPDViewer(GenericCaseViewer):
154     """
155     Etablissement des commandes d'un cas EPD (Eficas Python Dictionnary/Cas<-EPD)
156     """
157     def __init__(self, __name="", __objname="case", __content=None, __object=None):
158         "Initialisation et enregistrement de l'entete"
159         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
160         self._observerIndex = 0
161         self._addLine("# -*- coding: utf-8 -*-")
162         self._addLine("#\n# Python script using ADAO EPD\n#")
163         self._addLine("from numpy import array, matrix")
164         self._addLine("#")
165         self._addLine("%s = {}"%__objname)
166         if self._content is not None:
167             for command in self._content:
168                 self._append(*command)
169     def _extract(self, __multilines=None, __object=None):
170         "Transformation un enregistrement en une commande individuelle"
171         if __multilines is not None:
172             __multilines = __multilines.replace("\r\n","\n")
173             exec(__multilines)
174             self._objdata = None
175             __getlocals = locals()
176             for k in __getlocals:
177                 try:
178                     if type(__getlocals[k]) is dict:
179                         if 'ASSIMILATION_STUDY' in __getlocals[k]:
180                             self._objname = k
181                             self._objdata = __getlocals[k]['ASSIMILATION_STUDY']
182                         if 'CHECKING_STUDY' in __getlocals[k]:
183                             self._objname = k
184                             self._objdata = __getlocals[k]['CHECKING_STUDY']
185                 except:
186                     continue
187         elif __multilines is None and __object is not None and type(__object) is dict:
188             self._objname = "case"
189             self._objdata = None
190             if 'ASSIMILATION_STUDY' in __object:
191                 self._objdata = __object['ASSIMILATION_STUDY']
192             if 'CHECKING_STUDY' in __object:
193                 self._objdata = __object['CHECKING_STUDY']
194         else:
195             self._objdata = None
196         #
197         if self._objdata is None or not(type(self._objdata) is dict) or not('AlgorithmParameters' in self._objdata):
198             raise ValueError("Impossible to load given content as an ADAO EPD one (no dictionnary or no 'AlgorithmParameters' key found).")
199         # ----------------------------------------------------------------------
200         logging.debug("EPD Extracting commands of '%s' object..."%(self._objname,))
201         __commands = []
202         __UserPostAnalysis = ""
203         for k,r in self._objdata.items():
204             __command = k
205             logging.debug("EPD Extracted command: %s:%s"%(k, r))
206             if   __command == "StudyName" and len(str(r))>0:
207                 __commands.append( "set( Concept='Name', String='%s')"%(str(r),) )
208             elif   __command == "StudyRepertory":
209                 __commands.append( "set( Concept='Directory', String='%s')"%(str(r),) )
210             #
211             elif __command == "UserPostAnalysis" and type(r) is dict:
212                 if 'STRING_DATA' in r:
213                     __UserPostAnalysis = r['STRING_DATA']['STRING']
214                 elif 'SCRIPT_DATA' in r and os.path.exists(r['SCRIPT_DATA']['SCRIPT_FILE']):
215                     __UserPostAnalysis = open(r['SCRIPT_DATA']['SCRIPT_FILE'],'r').read()
216                 elif 'TEMPLATE_DATA' in r:
217                     # AnalysisPrinter...
218                     __itempl = r['TEMPLATE_DATA']['Template']
219                     __UserPostAnalysis = r['TEMPLATE_DATA'][__itempl]['ValueTemplate']
220                 else:
221                     __UserPostAnalysis = ""
222                 __UserPostAnalysis = __UserPostAnalysis.replace("ADD",self._objname)
223             #
224             elif __command == "AlgorithmParameters" and type(r) is dict and 'Algorithm' in r:
225                 if 'Parameters%s'%(r['Algorithm'],) in r and r['Parameters'] == 'Defaults':
226                     __Dict = r['Parameters%s'%(r['Algorithm'],)]
227                     if 'SetSeed' in __Dict:__Dict['SetSeed'] = int(__Dict['SetSeed'])
228                     if 'BoxBounds' in __Dict and type(__Dict['BoxBounds']) is str:
229                         __Dict['BoxBounds'] = eval(__Dict['BoxBounds'])
230                     __parameters = ', Parameters=%s'%(repr(__Dict),)
231                 elif 'Dict' in r and r['Parameters'] == 'Dict':
232                     __from = r['Dict']['data']
233                     if 'STRING_DATA' in __from:
234                         __parameters = ", Parameters=%s"%(repr(eval(__from['STRING_DATA']['STRING'])),)
235                     elif 'SCRIPT_DATA' in __from and os.path.exists(__from['SCRIPT_DATA']['SCRIPT_FILE']):
236                         __parameters = ", Script='%s'"%(__from['SCRIPT_DATA']['SCRIPT_FILE'],)
237                 else:
238                     __parameters = ""
239                 __commands.append( "set( Concept='AlgorithmParameters', Algorithm='%s'%s )"%(r['Algorithm'],__parameters) )
240             #
241             elif __command == "Observers" and type(r) is dict and 'SELECTION' in r:
242                 if type(r['SELECTION']) is str:
243                     __selection = (r['SELECTION'],)
244                 else:
245                     __selection = tuple(r['SELECTION'])
246                 for sk in __selection:
247                     __idata = r[sk]['%s_data'%sk]
248                     if __idata['NodeType'] == 'Template' and 'Template' in __idata['ObserverTemplate']:
249                         __template =__idata['ObserverTemplate']['Template']
250                         __commands.append( "set( Concept='Observer', Variable='%s', Template='%s' )"%(sk,__template) )
251                     if __idata['NodeType'] == 'String' and 'Value' in __idata:
252                         __value =__idata['Value']
253                         __commands.append( "set( Concept='Observer', Variable='%s', String='%s' )"%(sk,__value) )
254             #
255             # Background, ObservationError, ObservationOperator...
256             elif type(r) is dict:
257                 __argumentsList = []
258                 if 'Stored' in r and bool(r['Stored']):
259                     __argumentsList.append(['Stored',True])
260                 if 'INPUT_TYPE' in r and r['INPUT_TYPE'] in r:
261                     # Vector, Matrix, ScalarSparseMatrix, DiagonalSparseMatrix, Function
262                     __itype = r['INPUT_TYPE']
263                     __idata = r[__itype]['data']
264                     if 'FROM' in __idata and __idata['FROM'].upper()+'_DATA' in __idata:
265                         # String, Script, Template, ScriptWithOneFunction, ScriptWithFunctions
266                         __ifrom = __idata['FROM']
267                         if __ifrom == 'String' or __ifrom == 'Template':
268                             __argumentsList.append([__itype,__idata['STRING_DATA']['STRING']])
269                         if __ifrom == 'Script':
270                             __argumentsList.append([__itype,True])
271                             __argumentsList.append(['Script',__idata['SCRIPT_DATA']['SCRIPT_FILE']])
272                         if __ifrom == 'ScriptWithOneFunction':
273                             __argumentsList.append(['OneFunction',True])
274                             __argumentsList.append(['Script',__idata['SCRIPTWITHONEFUNCTION_DATA'].pop('SCRIPTWITHONEFUNCTION_FILE')])
275                             if len(__idata['SCRIPTWITHONEFUNCTION_DATA'])>0:
276                                 __argumentsList.append(['Parameters',__idata['SCRIPTWITHONEFUNCTION_DATA']])
277                         if __ifrom == 'ScriptWithFunctions':
278                             __argumentsList.append(['ThreeFunctions',True])
279                             __argumentsList.append(['Script',__idata['SCRIPTWITHFUNCTIONS_DATA'].pop('SCRIPTWITHFUNCTIONS_FILE')])
280                             if len(__idata['SCRIPTWITHFUNCTIONS_DATA'])>0:
281                                 __argumentsList.append(['Parameters',__idata['SCRIPTWITHFUNCTIONS_DATA']])
282                 __arguments = ["%s = %s"%(k,repr(v)) for k,v in __argumentsList]
283                 __commands.append( "set( Concept='%s', %s )"%(__command, ", ".join(__arguments)))
284         #
285         # ----------------------------------------------------------------------
286         __commands.sort() # Pour commencer par 'AlgorithmParameters'
287         __commands.append(__UserPostAnalysis)
288         return __commands
289
290 class _DCTViewer(GenericCaseViewer):
291     """
292     Etablissement des commandes d'un cas DCT (Cas<->DCT)
293     """
294     def __init__(self, __name="", __objname="case", __content=None, __object=None):
295         "Initialisation et enregistrement de l'entete"
296         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
297         self._observerIndex = 0
298         self._addLine("# -*- coding: utf-8 -*-")
299         self._addLine("#\n# Python script using ADAO DCT\n#")
300         self._addLine("from numpy import array, matrix")
301         self._addLine("#")
302         self._addLine("%s = {}"%__objname)
303         if self._content is not None:
304             for command in self._content:
305                 self._append(*command)
306     def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
307         "Transformation d'une commande individuelle en un enregistrement"
308         if __command is not None and __keys is not None and __local is not None:
309             __text  = ""
310             if "execute" in __command: return
311             if "self" in __keys: __keys.remove("self")
312             if __command in ("set","get") and "Concept" in __keys:
313                 __key = __local["Concept"]
314                 __keys.remove("Concept")
315             else:
316                 __key = __command.replace("set","").replace("get","")
317             if "Observer" in __key and 'Variable' in __keys:
318                 self._observerIndex += 1
319                 __key += "_%i"%self._observerIndex
320             __text += "%s['%s'] = {"%(self._objname,str(__key))
321             for k in __keys:
322                 __v = __local[k]
323                 if __v is None: continue
324                 if   k == "Checked" and not __v: continue
325                 if   k == "Stored"  and not __v: continue
326                 if   k == "AvoidRC" and __v: continue
327                 if   k == "noDetails": continue
328                 if isinstance(__v,Persistence.Persistence): __v = __v.values()
329                 if callable(__v): __text = self._missing%__v.__name__+__text
330                 if isinstance(__v,dict):
331                     for val in __v.values():
332                         if callable(val): __text = self._missing%val.__name__+__text
333                 numpy.set_printoptions(precision=15,threshold=1000000,linewidth=1000*15)
334                 __text += "'%s':%s, "%(k,repr(__v))
335                 numpy.set_printoptions(precision=8,threshold=1000,linewidth=75)
336             __text.rstrip(", ").rstrip()
337             __text += "}"
338             if __text[-2:] == "{}": return # Supprime les *Debug et les variables
339             self._addLine(__text)
340     def _extract(self, __multilines="", __object=None):
341         "Transformation un enregistrement en une commande individuelle"
342         __multilines = __multilines.replace("\r\n","\n")
343         exec(__multilines)
344         self._objdata = None
345         __getlocals = locals()
346         for k in __getlocals:
347             try:
348                 if 'AlgorithmParameters' in __getlocals[k] and type(__getlocals[k]) is dict:
349                     self._objname = k
350                     self._objdata = __getlocals[k]
351             except:
352                 continue
353         if self._objdata is None:
354             raise ValueError("Impossible to load given content as an ADAO DCT one (no 'AlgorithmParameters' key found).")
355         # ----------------------------------------------------------------------
356         logging.debug("DCT Extracting commands of '%s' object..."%(self._objname,))
357         __commands = []
358         for k in self._objdata:
359             if 'Observer_' in k:
360                 __command = k.split('_',1)[0]
361             else:
362                 __command = k
363             __arguments = ["%s = %s"%(k,repr(v)) for k,v in self._objdata[k].items()]
364             __commands.append( "set( Concept='%s', %s )"%(__command, ", ".join(__arguments)))
365         __commands.sort() # Pour commencer par 'AlgorithmParameters'
366         return __commands
367
368 class _SCDViewer(GenericCaseViewer):
369     """
370     Etablissement des commandes d'un cas SCD (Study Config Dictionary/Cas->SCD)
371     """
372     def __init__(self, __name="", __objname="case", __content=None, __object=None):
373         "Initialisation et enregistrement de l'entete"
374         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
375         self._addLine("# -*- coding: utf-8 -*-")
376         self._addLine("#\n# Input for ADAO converter to YACS\n#")
377         self._addLine("from numpy import array, matrix")
378         self._addLine("#")
379         self._addLine("study_config = {}")
380         self._addLine("study_config['StudyType'] = 'ASSIMILATION_STUDY'")
381         self._addLine("study_config['Name'] = '%s'"%self._name)
382         self._addLine("observers = {}")
383         self._addLine("study_config['Observers'] = observers")
384         self._addLine("#")
385         self._addLine("inputvariables_config = {}")
386         self._addLine("inputvariables_config['Order'] =['adao_default']")
387         self._addLine("inputvariables_config['adao_default'] = -1")
388         self._addLine("study_config['InputVariables'] = inputvariables_config")
389         self._addLine("#")
390         self._addLine("outputvariables_config = {}")
391         self._addLine("outputvariables_config['Order'] = ['adao_default']")
392         self._addLine("outputvariables_config['adao_default'] = -1")
393         self._addLine("study_config['OutputVariables'] = outputvariables_config")
394         if __content is not None:
395             for command in __content:
396                 self._append(*command)
397     def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
398         "Transformation d'une commande individuelle en un enregistrement"
399         if __command == "set": __command = __local["Concept"]
400         else:                  __command = __command.replace("set", "", 1)
401         #
402         __text  = None
403         if __command in (None, 'execute', 'executePythonScheme', 'executeYACSScheme', 'get', 'Name'):
404             return
405         elif __command in ['Debug', 'setDebug']:
406             __text  = "#\nstudy_config['Debug'] = '1'"
407         elif __command in ['NoDebug', 'setNoDebug']:
408             __text  = "#\nstudy_config['Debug'] = '0'"
409         elif __command in ['Observer', 'setObserver']:
410             __obs   = __local['Variable']
411             self._numobservers += 1
412             __text  = "#\n"
413             __text += "observers['%s'] = {}\n"%__obs
414             if __local['String'] is not None:
415                 __text += "observers['%s']['nodetype'] = '%s'\n"%(__obs, 'String')
416                 __text += "observers['%s']['String'] = \"\"\"%s\"\"\"\n"%(__obs, __local['String'])
417             if __local['Script'] is not None:
418                 __text += "observers['%s']['nodetype'] = '%s'\n"%(__obs, 'Script')
419                 __text += "observers['%s']['Script'] = \"%s\"\n"%(__obs, __local['Script'])
420             if __local['Template'] is not None and __local['Template'] in Templates.ObserverTemplates:
421                 __text += "observers['%s']['nodetype'] = '%s'\n"%(__obs, 'String')
422                 __text += "observers['%s']['String'] = \"\"\"%s\"\"\"\n"%(__obs, Templates.ObserverTemplates[__local['Template']])
423             if __local['Info'] is not None:
424                 __text += "observers['%s']['info'] = \"\"\"%s\"\"\"\n"%(__obs, __local['Info'])
425             else:
426                 __text += "observers['%s']['info'] = \"\"\"%s\"\"\"\n"%(__obs, __obs)
427             __text += "observers['%s']['number'] = %s"%(__obs, self._numobservers)
428         elif __local is not None: # __keys is not None and
429             numpy.set_printoptions(precision=15,threshold=1000000,linewidth=1000*15)
430             __text  = "#\n"
431             __text += "%s_config = {}\n"%__command
432             if 'self' in __local: __local.pop('self')
433             __to_be_removed = []
434             for __k,__v in __local.items():
435                 if __v is None: __to_be_removed.append(__k)
436             for __k in __to_be_removed:
437                 __local.pop(__k)
438             for __k,__v in __local.items():
439                 if __k == "Concept": continue
440                 if __k in ['ScalarSparseMatrix','DiagonalSparseMatrix','Matrix','OneFunction','ThreeFunctions'] and 'Script' in __local: continue
441                 if __k == 'Algorithm':
442                     __text += "study_config['Algorithm'] = %s\n"%(repr(__v))
443                 elif __k == 'Script':
444                     __k = 'Vector'
445                     __f = 'Script'
446                     __v = "'"+repr(__v)+"'"
447                     for __lk in ['ScalarSparseMatrix','DiagonalSparseMatrix','Matrix']:
448                         if __lk in __local and __local[__lk]: __k = __lk
449                     if __command == "AlgorithmParameters": __k = "Dict"
450                     if 'OneFunction' in __local and __local['OneFunction']:
451                         __text += "%s_ScriptWithOneFunction = {}\n"%(__command,)
452                         __text += "%s_ScriptWithOneFunction['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"%(__command,)
453                         __text += "%s_ScriptWithOneFunction['Script'] = {}\n"%(__command,)
454                         __text += "%s_ScriptWithOneFunction['Script']['Direct'] = %s\n"%(__command,__v)
455                         __text += "%s_ScriptWithOneFunction['Script']['Tangent'] = %s\n"%(__command,__v)
456                         __text += "%s_ScriptWithOneFunction['Script']['Adjoint'] = %s\n"%(__command,__v)
457                         __text += "%s_ScriptWithOneFunction['DifferentialIncrement'] = 1e-06\n"%(__command,)
458                         __text += "%s_ScriptWithOneFunction['CenteredFiniteDifference'] = 0\n"%(__command,)
459                         __k = 'Function'
460                         __f = 'ScriptWithOneFunction'
461                         __v = '%s_ScriptWithOneFunction'%(__command,)
462                     if 'ThreeFunctions' in __local and __local['ThreeFunctions']:
463                         __text += "%s_ScriptWithFunctions = {}\n"%(__command,)
464                         __text += "%s_ScriptWithFunctions['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"%(__command,)
465                         __text += "%s_ScriptWithFunctions['Script'] = {}\n"%(__command,)
466                         __text += "%s_ScriptWithFunctions['Script']['Direct'] = %s\n"%(__command,__v)
467                         __text += "%s_ScriptWithFunctions['Script']['Tangent'] = %s\n"%(__command,__v)
468                         __text += "%s_ScriptWithFunctions['Script']['Adjoint'] = %s\n"%(__command,__v)
469                         __k = 'Function'
470                         __f = 'ScriptWithFunctions'
471                         __v = '%s_ScriptWithFunctions'%(__command,)
472                     __text += "%s_config['Type'] = '%s'\n"%(__command,__k)
473                     __text += "%s_config['From'] = '%s'\n"%(__command,__f)
474                     __text += "%s_config['Data'] = %s\n"%(__command,__v)
475                     __text = __text.replace("''","'")
476                 elif __k in ('Stored', 'Checked'):
477                     if bool(__v):
478                         __text += "%s_config['%s'] = '%s'\n"%(__command,__k,int(bool(__v)))
479                 elif __k in ('AvoidRC', 'noDetails'):
480                     if not bool(__v):
481                         __text += "%s_config['%s'] = '%s'\n"%(__command,__k,int(bool(__v)))
482                 else:
483                     if __k == 'Parameters': __k = "Dict"
484                     if isinstance(__v,Persistence.Persistence): __v = __v.values()
485                     if callable(__v): __text = self._missing%__v.__name__+__text
486                     if isinstance(__v,dict):
487                         for val in __v.values():
488                             if callable(val): __text = self._missing%val.__name__+__text
489                     __text += "%s_config['Type'] = '%s'\n"%(__command,__k)
490                     __text += "%s_config['From'] = '%s'\n"%(__command,'String')
491                     __text += "%s_config['Data'] = \"\"\"%s\"\"\"\n"%(__command,repr(__v))
492             __text += "study_config['%s'] = %s_config"%(__command,__command)
493             numpy.set_printoptions(precision=8,threshold=1000,linewidth=75)
494             if __switchoff:
495                 self._switchoff = True
496         if __text is not None: self._addLine(__text)
497         if not __switchoff:
498             self._switchoff = False
499     def _finalize(self, *__args):
500         self.__loadVariablesByScript()
501         self._addLine("#")
502         self._addLine("Analysis_config = {}")
503         self._addLine("Analysis_config['From'] = 'String'")
504         self._addLine("Analysis_config['Data'] = \"\"\"import numpy")
505         self._addLine("xa=numpy.ravel(ADD.get('Analysis')[-1])")
506         self._addLine("print 'Analysis:',xa\"\"\"")
507         self._addLine("study_config['UserPostAnalysis'] = Analysis_config")
508     def __loadVariablesByScript(self):
509         __ExecVariables = {} # Necessaire pour recuperer la variable
510         exec("\n".join(self._lineSerie), __ExecVariables)
511         study_config = __ExecVariables['study_config']
512         # Pour Python 3 : self.__hasAlgorithm = bool(study_config['Algorithm'])
513         if 'Algorithm' in study_config:
514             self.__hasAlgorithm = True
515         else:
516             self.__hasAlgorithm = False
517         if not self.__hasAlgorithm and \
518                 "AlgorithmParameters" in study_config and \
519                 isinstance(study_config['AlgorithmParameters'], dict) and \
520                 "From" in study_config['AlgorithmParameters'] and \
521                 "Data" in study_config['AlgorithmParameters'] and \
522                 study_config['AlgorithmParameters']['From'] == 'Script':
523             __asScript = study_config['AlgorithmParameters']['Data']
524             __var = ImportFromScript(__asScript).getvalue( "Algorithm" )
525             __text = "#\nstudy_config['Algorithm'] = '%s'"%(__var,)
526             self._addLine(__text)
527         if self.__hasAlgorithm and \
528                 "AlgorithmParameters" in study_config and \
529                 isinstance(study_config['AlgorithmParameters'], dict) and \
530                 "From" not in study_config['AlgorithmParameters'] and \
531                 "Data" not in study_config['AlgorithmParameters']:
532             __text  = "#\n"
533             __text += "AlgorithmParameters_config['Type'] = 'Dict'\n"
534             __text += "AlgorithmParameters_config['From'] = 'String'\n"
535             __text += "AlgorithmParameters_config['Data'] = '{}'\n"
536             self._addLine(__text)
537         del study_config
538
539 class _XMLViewer(GenericCaseViewer):
540     """
541     Etablissement des commandes d'un cas XML
542     """
543     def __init__(self, __name="", __objname="case", __content=None, __object=None):
544         "Initialisation et enregistrement de l'entete"
545         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
546         raise NotImplementedError()
547
548 class _YACSViewer(GenericCaseViewer):
549     """
550     Etablissement des commandes d'un cas YACS (Cas->SCD->YACS)
551     """
552     def __init__(self, __name="", __objname="case", __content=None, __object=None):
553         "Initialisation et enregistrement de l'entete"
554         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
555         self.__internalSCD = _SCDViewer(__name, __objname, __content, __object)
556         self._append       = self.__internalSCD._append
557     def dump(self, __filename=None, __convertSCDinMemory=True):
558         "Restitution normalisée des commandes"
559         self.__internalSCD._finalize()
560         # -----
561         if __filename is None:
562             raise ValueError("A file name has to be given for YACS XML output.")
563         # -----
564         if not PlatformInfo.has_salome or \
565             not PlatformInfo.has_adao:
566             raise ImportError("\n\n"+\
567                 "Unable to get SALOME or ADAO environnement variables.\n"+\
568                 "Please load the right environnement before trying to use it.\n")
569         elif __convertSCDinMemory:
570             __file    = os.path.abspath(__filename)
571             __SCDdump = self.__internalSCD.dump()
572             if os.path.isfile(__file) or os.path.islink(__file):
573                 os.remove(__file)
574             from daYacsSchemaCreator.run import create_schema_from_content
575             create_schema_from_content(__SCDdump, __file)
576         else:
577             __file    = os.path.abspath(__filename)
578             __SCDfile = __file[:__file.rfind(".")] + '_SCD.py'
579             __SCDdump = self.__internalSCD.dump(__SCDfile)
580             if os.path.isfile(__file) or os.path.islink(__file):
581                 os.remove(__file)
582             __converterExe = os.path.join(os.environ["ADAO_ROOT_DIR"], "bin/salome", "AdaoYacsSchemaCreator.py")
583             __args = ["python", __converterExe, __SCDfile, __file]
584             import subprocess
585             __p = subprocess.Popen(__args)
586             (__stdoutdata, __stderrdata) = __p.communicate()
587             __p.terminate()
588             os.remove(__SCDfile)
589         # -----
590         if not os.path.exists(__file):
591             __msg  = "An error occured during the ADAO YACS Schema build for\n"
592             __msg += "the target output file:\n"
593             __msg += "  %s\n"%__file
594             __msg += "See errors details in your launching terminal log.\n"
595             raise ValueError(__msg)
596         # -----
597         __fid = open(__file,"r")
598         __text = __fid.read()
599         __fid.close()
600         return __text
601
602 class ImportFromScript(object):
603     """
604     Obtention d'une variable nommee depuis un fichier script importe
605     """
606     def __init__(self, __filename=None):
607         "Verifie l'existence et importe le script"
608         if __filename is None:
609             raise ValueError("The name of the file, containing the variable to be read, has to be specified.")
610         if not os.path.isfile(__filename):
611             raise ValueError("The file containing the variable to be imported doesn't seem to exist. Please check the file. The given file name is:\n  \"%s\""%__filename)
612         if os.path.dirname(__filename) != '':
613             sys.path.insert(0, os.path.dirname(__filename))
614             __basename = os.path.basename(__filename).rstrip(".py")
615         else:
616             __basename = __filename.rstrip(".py")
617         self.__basename = __basename
618         self.__scriptfile = __import__(__basename, globals(), locals(), [])
619         self.__scriptstring = open(__filename,'r').read()
620     def getvalue(self, __varname=None, __synonym=None ):
621         "Renvoie la variable demandee"
622         if __varname is None:
623             raise ValueError("The name of the variable to be read has to be specified. Please check the content of the file and the syntax.")
624         if not hasattr(self.__scriptfile, __varname):
625             if __synonym is None:
626                 raise ValueError("The imported script file \"%s\" doesn't contain the mandatory variable \"%s\" to be read. Please check the content of the file and the syntax."%(str(self.__basename)+".py",__varname))
627             elif not hasattr(self.__scriptfile, __synonym):
628                 raise ValueError("The imported script file \"%s\" doesn't contain the mandatory variable \"%s\" to be read. Please check the content of the file and the syntax."%(str(self.__basename)+".py",__synonym))
629             else:
630                 return getattr(self.__scriptfile, __synonym)
631         else:
632             return getattr(self.__scriptfile, __varname)
633     def getstring(self):
634         "Renvoie le script complet"
635         return self.__scriptstring
636
637 # ==============================================================================
638 if __name__ == "__main__":
639     print('\n AUTODIAGNOSTIC \n')