]> SALOME platform Git repositories - modules/adao.git/blob - src/daSalome/adaoBuilder.py
Salome HOME
Adding documentation for TUI (examples) and script entries
[modules/adao.git] / src / daSalome / adaoBuilder.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2015 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     Interface de scripting pour une étude ADAO
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27 __all__ = ["New"]
28
29 import os
30 from daCore import AssimilationStudy
31
32 class New(object):
33     """
34     Creation TUI d'un cas ADAO sans lien avec YACS
35     """
36     def __init__(self, name = ""):
37         self.__adaoStudy = AssimilationStudy.AssimilationStudy( name )
38         self.__dumper = _DumpLogger(name)
39
40     # -----------------------------------------------------------
41
42     def set(
43             self,
44             Concept              = None,
45             Algorithm            = None,
46             DiagonalSparseMatrix = None,
47             Info                 = None,
48             Matrix               = None,
49             OneFunction          = None,
50             Parameters           = None,
51             ScalarSparseMatrix   = None,
52             Script               = None,
53             Stored               = False,
54             String               = None,
55             Template             = None,
56             ThreeFunctions       = None,
57             Variable             = None,
58             Vector               = None,
59             VectorSerie          = None
60             ):
61         "Interface unique de définition de variables d'entrées par argument"
62         self.__dumper.register("set",dir(),locals(),None,True)
63         try:
64             if   Concept == "Background":
65                 self.setBackground(Vector,VectorSerie,Script,Stored)
66             elif Concept == "BackgroundError":
67                 self.setBackgroundError(Matrix,ScalarSparseMatrix,
68                                         DiagonalSparseMatrix,Script,Stored)
69             elif Concept == "CheckingPoint":
70                 self.setCheckingPoint(Vector,VectorSerie,Script,Stored)
71             elif Concept == "ControlModel":
72                 self.setControlModel(Matrix,OneFunction,ThreeFunctions,
73                                      Parameters,Script,Stored)
74             elif Concept == "ControlInput":
75                 self.setControlInput(Vector,VectorSerie,Script,Stored)
76             elif Concept == "EvolutionError":
77                 self.setEvolutionError(Matrix,ScalarSparseMatrix,
78                                        DiagonalSparseMatrix,Script,Stored)
79             elif Concept == "EvolutionModel":
80                 self.setEvolutionModel(Matrix,OneFunction,ThreeFunctions,
81                                        Parameters,Script,Stored)
82             elif Concept == "Observation":
83                 self.setObservation(Vector,VectorSerie,Script,Stored)
84             elif Concept == "ObservationError":
85                 self.setObservationError(Matrix,ScalarSparseMatrix,
86                                          DiagonalSparseMatrix,Script,Stored)
87             elif Concept == "ObservationOperator":
88                 self.setObservationOperator(Matrix,OneFunction,ThreeFunctions,
89                                             Parameters,Script,Stored)
90             elif Concept == "AlgorithmParameters":
91                 self.setAlgorithmParameters(Algorithm,Parameters)
92             elif Concept == "Debug":
93                 self.setDebug()
94             elif Concept == "NoDebug":
95                 self.setNoDebug()
96             elif Concept == "Observer":
97                 self.setObserver(Variable,Template,String,Info)
98             else:
99                 raise ValueError("the variable named '%s' is not allowed."%str(Concept))
100         except Exception as e:
101             if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
102             else: msg = ""
103             raise ValueError("during settings, the following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the launching terminal."%(str(e),msg))
104
105     # -----------------------------------------------------------
106
107     def setBackground(
108             self,
109             Vector         = None,
110             VectorSerie    = None,
111             Script         = None,
112             Stored         = False):
113         "Définition d'une entrée de calcul"
114         self.__dumper.register("setBackground", dir(), locals())
115         if Script is not None:
116             __Vector, __PersistentVector = None, None
117             if VectorSerie:
118                 __PersistentVector = _ImportFromScript(Script).getvalue( "Background" )
119             else:
120                 __Vector = _ImportFromScript(Script).getvalue( "Background" )
121         else:
122             __Vector, __PersistentVector = Vector, VectorSerie
123         #
124         self.__adaoStudy.setBackground(
125             asVector           = __Vector,
126             asPersistentVector = __PersistentVector,
127             toBeStored         = Stored,
128             )
129
130     def setBackgroundError(
131             self,
132             Matrix               = None,
133             ScalarSparseMatrix   = None,
134             DiagonalSparseMatrix = None,
135             Script               = None,
136             Stored               = False):
137         "Définition d'une entrée de calcul"
138         self.__dumper.register("setBackgroundError", dir(), locals())
139         if Script is not None:
140             __Covariance, __Scalar, __Vector = None, None, None
141             if ScalarSparseMatrix:
142                 __Scalar = _ImportFromScript(Script).getvalue( "BackgroundError" )
143             elif DiagonalSparseMatrix:
144                 __Vector = _ImportFromScript(Script).getvalue( "BackgroundError" )
145             else:
146                 __Covariance = _ImportFromScript(Script).getvalue( "BackgroundError" )
147         else:
148             __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
149         #
150         self.__adaoStudy.setBackgroundError(
151             asCovariance  = __Covariance,
152             asEyeByScalar = __Scalar,
153             asEyeByVector = __Vector,
154             toBeStored    = Stored,
155             )
156
157     def setCheckingPoint(
158             self,
159             Vector         = None,
160             VectorSerie    = None,
161             Script         = None,
162             Stored         = False):
163         "Définition d'une entrée de vérification"
164         self.__dumper.register("setCheckingPoint", dir(), locals())
165         if Script is not None:
166             __Vector, __PersistentVector = None, None
167             if VectorSerie:
168                 __PersistentVector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
169             else:
170                 __Vector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
171         else:
172             __Vector, __PersistentVector = Vector, VectorSerie
173         #
174         self.__adaoStudy.setBackground(
175             asVector           = __Vector,
176             asPersistentVector = __PersistentVector,
177             toBeStored         = Stored,
178             )
179
180     def setControlModel(
181             self,
182             Matrix         = None,
183             OneFunction    = None,
184             ThreeFunctions = None,
185             Parameters     = None,
186             Script         = None,
187             Stored         = False):
188         "Définition d'une entrée de calcul"
189         self.__dumper.register("setControlModel", dir(), locals())
190         __Parameters = {}
191         if Parameters is not None and type(Parameters) == type({}):
192             if Parameters.has_key("DifferentialIncrement"):
193                 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
194             if Parameters.has_key("CenteredFiniteDifference"):
195                 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
196         if Script is not None:
197             __Matrix, __Function = None, None
198             if Matrix:
199                 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
200             elif OneFunction:
201                 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
202                 __Function.update({"useApproximatedDerivatives":True})
203                 __Function.update(__Parameters)
204             elif ThreeFunctions:
205                 __Function = {
206                     "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
207                     "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
208                     "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
209                     }
210                 __Function.update(__Parameters)
211         
212         else:
213             __Matrix = Matrix
214             if OneFunction is not None:
215                 __Function = { "Direct":OneFunction }
216                 __Function.update({"useApproximatedDerivatives":True})
217                 __Function.update(__Parameters)
218             elif ThreeFunctions is not None:
219                 if (type(ThreeFunctions) is not type({})) or \
220                     not ThreeFunctions.has_key("Direct") or \
221                     not ThreeFunctions.has_key("Tangent") or \
222                     not ThreeFunctions.has_key("Adjoint"):
223                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
224                 __Function = ThreeFunctions
225                 __Function.update(__Parameters)
226             else:
227                 __Function = None
228         #
229         self.__adaoStudy.setControlModel(
230             asFunction = __Function,
231             asMatrix   = __Matrix,
232             toBeStored = Stored,
233             )
234
235     def setControlInput(
236             self,
237             Vector         = None,
238             VectorSerie    = None,
239             Script         = None,
240             Stored         = False):
241         "Définition d'une entrée de calcul"
242         self.__dumper.register("setControlInput", dir(), locals())
243         if Script is not None:
244             __Vector, __PersistentVector = None, None
245             if VectorSerie:
246                 __PersistentVector = _ImportFromScript(Script).getvalue( "ControlInput" )
247             else:
248                 __Vector = _ImportFromScript(Script).getvalue( "ControlInput" )
249         else:
250             __Vector, __PersistentVector = Vector, VectorSerie
251         #
252         self.__adaoStudy.setControlInput(
253             asVector           = __Vector,
254             asPersistentVector = __PersistentVector,
255             toBeStored         = Stored,
256             )
257
258     def setEvolutionError(
259             self,
260             Matrix               = None,
261             ScalarSparseMatrix   = None,
262             DiagonalSparseMatrix = None,
263             Script               = None,
264             Stored               = False):
265         "Définition d'une entrée de calcul"
266         self.__dumper.register("setEvolutionError", dir(), locals())
267         if Script is not None:
268             __Covariance, __Scalar, __Vector = None, None, None
269             if ScalarSparseMatrix:
270                 __Scalar = _ImportFromScript(Script).getvalue( "EvolutionError" )
271             elif DiagonalSparseMatrix:
272                 __Vector = _ImportFromScript(Script).getvalue( "EvolutionError" )
273             else:
274                 __Covariance = _ImportFromScript(Script).getvalue( "EvolutionError" )
275         else:
276             __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
277         #
278         self.__adaoStudy.setEvolutionError(
279             asCovariance  = __Covariance,
280             asEyeByScalar = __Scalar,
281             asEyeByVector = __Vector,
282             toBeStored    = Stored,
283             )
284
285     def setEvolutionModel(
286             self,
287             Matrix         = None,
288             OneFunction    = None,
289             ThreeFunctions = None,
290             Parameters     = None,
291             Script         = None,
292             Stored         = False):
293         "Définition d'une entrée de calcul"
294         self.__dumper.register("setEvolutionModel", dir(), locals())
295         __Parameters = {}
296         if Parameters is not None and type(Parameters) == type({}):
297             if Parameters.has_key("DifferentialIncrement"):
298                 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
299             if Parameters.has_key("CenteredFiniteDifference"):
300                 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
301             if Parameters.has_key("EnableMultiProcessing"):
302                 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
303             if Parameters.has_key("NumberOfProcesses"):
304                 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
305         if Script is not None:
306             __Matrix, __Function = None, None
307             if Matrix:
308                 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
309             elif OneFunction:
310                 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
311                 __Function.update({"useApproximatedDerivatives":True})
312                 __Function.update(__Parameters)
313             elif ThreeFunctions:
314                 __Function = {
315                     "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
316                     "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
317                     "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
318                     }
319                 __Function.update(__Parameters)
320         
321         else:
322             __Matrix = Matrix
323             if OneFunction is not None:
324                 __Function = { "Direct":OneFunction }
325                 __Function.update({"useApproximatedDerivatives":True})
326                 __Function.update(__Parameters)
327             elif ThreeFunctions is not None:
328                 if (type(ThreeFunctions) is not type({})) or \
329                     not ThreeFunctions.has_key("Direct") or \
330                     not ThreeFunctions.has_key("Tangent") or \
331                     not ThreeFunctions.has_key("Adjoint"):
332                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
333                 __Function = ThreeFunctions
334                 __Function.update(__Parameters)
335             else:
336                 __Function = None
337         #
338         self.__adaoStudy.setEvolutionModel(
339             asFunction = __Function,
340             asMatrix   = __Matrix,
341             toBeStored = Stored,
342             )
343
344     def setObservation(
345             self,
346             Vector         = None,
347             VectorSerie    = None,
348             Script         = None,
349             Stored         = False):
350         "Définition d'une entrée de calcul"
351         self.__dumper.register("setObservation", dir(), locals())
352         if Script is not None:
353             __Vector, __PersistentVector = None, None
354             if VectorSerie:
355                 __PersistentVector = _ImportFromScript(Script).getvalue( "Observation" )
356             else:
357                 __Vector = _ImportFromScript(Script).getvalue( "Observation" )
358         else:
359             __Vector, __PersistentVector = Vector, VectorSerie
360         #
361         self.__adaoStudy.setObservation(
362             asVector           = __Vector,
363             asPersistentVector = __PersistentVector,
364             toBeStored         = Stored,
365             )
366
367     def setObservationError(
368             self,
369             Matrix               = None,
370             ScalarSparseMatrix   = None,
371             DiagonalSparseMatrix = None,
372             Script               = None,
373             Stored               = False):
374         "Définition d'une entrée de calcul"
375         self.__dumper.register("setObservationError", dir(), locals())
376         if Script is not None:
377             __Covariance, __Scalar, __Vector = None, None, None
378             if ScalarSparseMatrix:
379                 __Scalar = _ImportFromScript(Script).getvalue( "ObservationError" )
380             elif DiagonalSparseMatrix:
381                 __Vector = _ImportFromScript(Script).getvalue( "ObservationError" )
382             else:
383                 __Covariance = _ImportFromScript(Script).getvalue( "ObservationError" )
384         else:
385             __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
386         #
387         self.__adaoStudy.setObservationError(
388             asCovariance  = __Covariance,
389             asEyeByScalar = __Scalar,
390             asEyeByVector = __Vector,
391             toBeStored    = Stored,
392             )
393
394     def setObservationOperator(
395             self,
396             Matrix         = None,
397             OneFunction    = None,
398             ThreeFunctions = None,
399             Parameters     = None,
400             Script         = None,
401             Stored         = False):
402         "Définition d'une entrée de calcul"
403         self.__dumper.register("setObservationOperator", dir(), locals())
404         __Parameters = {}
405         if Parameters is not None and type(Parameters) == type({}):
406             if Parameters.has_key("DifferentialIncrement"):
407                 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
408             if Parameters.has_key("CenteredFiniteDifference"):
409                 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
410             if Parameters.has_key("EnableMultiProcessing"):
411                 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
412             if Parameters.has_key("NumberOfProcesses"):
413                 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
414         if Script is not None:
415             __Matrix, __Function = None, None
416             if Matrix:
417                 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
418             elif OneFunction:
419                 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
420                 __Function.update({"useApproximatedDerivatives":True})
421                 __Function.update(__Parameters)
422             elif ThreeFunctions:
423                 __Function = {
424                     "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
425                     "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
426                     "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
427                     }
428                 __Function.update(__Parameters)
429         
430         else:
431             __Matrix = Matrix
432             if OneFunction is not None:
433                 __Function = { "Direct":OneFunction }
434                 __Function.update({"useApproximatedDerivatives":True})
435                 __Function.update(__Parameters)
436             elif ThreeFunctions is not None:
437                 if (type(ThreeFunctions) is not type({})) or \
438                     not ThreeFunctions.has_key("Direct") or \
439                     not ThreeFunctions.has_key("Tangent") or \
440                     not ThreeFunctions.has_key("Adjoint"):
441                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint") 
442                 __Function = ThreeFunctions
443                 __Function.update(__Parameters)
444             else:
445                 __Function = None
446         #
447         self.__adaoStudy.setObservationOperator(
448             asFunction = __Function,
449             asMatrix   = __Matrix,
450             toBeStored = Stored,
451             )
452
453     # -----------------------------------------------------------
454
455     def setAlgorithmParameters(
456             self,
457             Algorithm  = None,
458             Parameters = None):
459         "Définition d'un paramétrage du calcul"
460         self.__dumper.register("setAlgorithmParameters", dir(), locals())
461         self.__adaoStudy.setAlgorithm( choice = Algorithm )
462         self.__adaoStudy.setAlgorithmParameters( asDico = Parameters )
463
464     def setDebug(self):
465         "Définition d'un paramétrage du calcul"
466         self.__dumper.register("setDebug",dir(),locals())
467         return self.__adaoStudy.setDebug()
468
469     def setNoDebug(self):
470         "Définition d'un paramétrage du calcul"
471         self.__dumper.register("setNoDebug",dir(),locals())
472         return self.__adaoStudy.unsetDebug()
473
474     def setObserver(
475             self,
476             Variable = None,
477             Template = None,
478             String   = None,
479             Info     = None):
480         "Définition d'un paramétrage du calcul"
481         self.__dumper.register("setObserver", dir(), locals())
482         if Variable is None:
483             raise ValueError("setting an observer has to be done over a variable name, not over None.")
484         else:
485             __Variable = str(Variable)
486             if Info is None:
487                 __Info = str(Variable)
488             else:
489                 __Info = str(Info)
490         #
491         if String is not None:
492             __FunctionText = String
493         elif Template is not None:
494             if Template == "ValuePrinter":
495                 __FunctionText = "print info,var[-1]"
496             if Template == "ValueSeriePrinter":
497                 __FunctionText = "print info,var[:]"
498             if Template == "ValueSaver":
499                 __FunctionText = r"import numpy,re\nv=numpy.array((var[-1]))\nglobal istep\ntry:\n    istep += 1\nexcept:\n    istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
500             if Template == "ValueSerieSaver":
501                 __FunctionText = r"import numpy,re\nv=numpy.array((var[:])) \nglobal istep\ntry:\n    istep += 1\nexcept:\n    istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
502             if Template == "ValuePrinterAndSaver":
503                 __FunctionText = r"import numpy,re\nv=numpy.array((var[-1]))\nprint info,v\nglobal istep\ntry:\n    istep += 1\nexcept:\n    istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
504             if Template == "ValueSeriePrinterAndSaver":
505                 __FunctionText = r"import numpy,re\nv=numpy.array((var[:])) \nprint info,v\nglobal istep\ntry:\n    istep += 1\nexcept:\n    istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
506             if Template == "ValueGnuPlotter":
507                 __FunctionText = r"import Gnuplot\nglobal ifig,gp\ntry:\n    ifig += 1\n    gp('set style data lines')\nexcept:\n    ifig = 0\n    gp = Gnuplot.Gnuplot(persist=1)\n    gp('set style data lines')\ngp('set title  \"%s (Figure %i)\"'%(info,ifig))\ngp.plot( Gnuplot.Data( var[-1], with_='lines lw 2' ) )"
508             if Template == "ValueSerieGnuPlotter":
509                 __FunctionText = r"import Gnuplot\nglobal ifig,gp\ntry:\n    ifig += 1\n    gp('set style data lines')\nexcept:\n    ifig = 0\n    gp = Gnuplot.Gnuplot(persist=1)\n    gp('set style data lines')\ngp('set title  \"%s (Figure %i)\"'%(info,ifig))\ngp.plot( Gnuplot.Data( var[:], with_='lines lw 2' ) )"
510         else:
511             __FunctionText = ""
512         __Function = _ObserverF(__FunctionText)
513         #
514         self.__adaoStudy.setDataObserver(
515             VariableName   = __Variable,
516             HookFunction   = __Function.getfunc(),
517             HookParameters = __Info,
518             )
519
520     # -----------------------------------------------------------
521
522     def executePythonScheme(self):
523         "Lancement du calcul"
524         self.__dumper.register("executePythonScheme", dir(), locals())
525         try:
526             self.__adaoStudy.analyze()
527         except Exception as e:
528             if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
529             else: msg = ""
530             raise ValueError("during execution, the following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the launching terminal."%(str(e),msg))
531
532     execute = executePythonScheme
533
534     def executeYACSScheme(self, File=None):
535         "Lancement du calcul"
536         self.__dumper.register("executeYACSScheme", dir(), locals())
537         raise NotImplementedError()
538
539     # -----------------------------------------------------------
540
541     def get(self, Concept=None):
542         "Récupération d'une sortie du calcul"
543         self.__dumper.register("get",dir(),locals(),Concept)
544         return self.__adaoStudy.get(Concept)
545
546     def dumpNormalizedCommands(self):
547         "Récupération de la liste des commandes de création d'un cas"
548         return self.__dumper.dump()
549
550 #     def UserPostAnalysis(self):
551 #         raise NotImplementedError()
552 #
553 #     def StudyRepertory(self):
554 #         raise NotImplementedError()
555
556 class _DumpLogger(object):
557     """
558     Conservation des commandes de création d'un cas
559     """
560     def __init__(self,__name="",__objname="case"):
561         self.__logSerie = []
562         # self.__logSerie.append("#-*-coding:iso-8859-1-*-\n#")
563         # self.__logSerie.append("# Copyright (C) 2008-2015 EDF R&D\n#")
564         self.__logSerie.append("#\n# Python script for ADAO\n#")
565         self.__logSerie.append("from numpy import *")
566         self.__logSerie.append("import adaoBuilder")
567         self.__logSerie.append("%s = adaoBuilder.New('%s')"%(__objname,__name))
568         self.__switchoff = False
569     def register(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
570         "Enregistrement d'une commande individuelle"
571         if __command is not None and __keys is not None and __local is not None and not self.__switchoff:
572             __text  = ""
573             if __pre is not None:
574                 __text += "%s = "%__pre
575             __text += "case.%s( "%str(__command)
576             __keys.remove("self")
577             for k in __keys:
578                 __v = __local[k]
579                 if __v is None: continue
580                 __text += "%s=%s, "%(k,repr(__v))
581             __text += ")"
582             self.__logSerie.append(__text)
583             if __switchoff:
584                 self.__switchoff = True
585         if not __switchoff:
586             self.__switchoff = False
587     def dump(self,__filename=None):
588         "Restitution de la liste des commandes de création d'un cas"
589         if __filename is None:
590             return "\n".join(self.__logSerie)
591         else:
592             fid = open(__filename,"w")
593             fid.writelines(self.__logSerie)
594             fid.close()
595
596 class _ObserverF(object):
597     """
598     Création d'une fonction d'observateur à partir de son texte
599     """
600     def __init__(self, corps=""):
601         self.__corps = corps
602     def func(self,var,info):
603         "Fonction d'observation"
604         exec(self.__corps)
605     def getfunc(self):
606         "Restitution du pointeur de fonction dans l'objet"
607         return self.func
608
609 class _ImportFromScript(object):
610     """
611     Obtention d'une variable nommée depuis un fichier script importé
612     """
613     def __init__(self, __filename=None):
614         "Verifie l'existence et importe le script"
615         __filename = __filename.rstrip(".py")
616         if __filename is None:
617             raise ValueError("The name of the file containing the variable to be imported has to be specified.")
618         if not os.path.isfile(str(__filename)+".py"):
619             raise ValueError("The file containing the variable to be imported doesn't seem to exist. The given file name is:\n  \"%s\""%__filename)
620         self.__scriptfile = __import__(__filename, globals(), locals(), [])
621     def getvalue(self, __varname=None ):
622         "Renvoie la variable demandee"
623         if __varname is None:
624             raise ValueError("The name of the variable to be imported has to be specified.")
625         if not hasattr(self.__scriptfile, __varname):
626             raise ValueError("The imported script file doesn't contain the specified variable \"%s\"."%__varname)
627         else:
628             return getattr(self.__scriptfile, __varname)
629
630 # ==============================================================================
631 if __name__ == "__main__":
632     print '\n AUTODIAGNOSTIC \n'