]> SALOME platform Git repositories - modules/adao.git/blob - src/daSalome/adaoBuilder.py
Salome HOME
Minor documentation and source improvements
[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
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,Script)
92             elif Concept == "Debug":
93                 self.setDebug()
94             elif Concept == "NoDebug":
95                 self.setNoDebug()
96             elif Concept == "Observer":
97                 self.setObserver(Variable,Template,String,Script,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         else:
212             __Matrix = Matrix
213             if OneFunction is not None:
214                 __Function = { "Direct":OneFunction }
215                 __Function.update({"useApproximatedDerivatives":True})
216                 __Function.update(__Parameters)
217             elif ThreeFunctions is not None:
218                 if (type(ThreeFunctions) is not type({})) or \
219                     not ThreeFunctions.has_key("Direct") or \
220                     not ThreeFunctions.has_key("Tangent") or \
221                     not ThreeFunctions.has_key("Adjoint"):
222                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
223                 __Function = ThreeFunctions
224                 __Function.update(__Parameters)
225             else:
226                 __Function = None
227         #
228         self.__adaoStudy.setControlModel(
229             asFunction = __Function,
230             asMatrix   = __Matrix,
231             toBeStored = Stored,
232             )
233
234     def setControlInput(
235             self,
236             Vector         = None,
237             VectorSerie    = None,
238             Script         = None,
239             Stored         = False):
240         "Définition d'une entrée de calcul"
241         self.__dumper.register("setControlInput", dir(), locals())
242         if Script is not None:
243             __Vector, __PersistentVector = None, None
244             if VectorSerie:
245                 __PersistentVector = _ImportFromScript(Script).getvalue( "ControlInput" )
246             else:
247                 __Vector = _ImportFromScript(Script).getvalue( "ControlInput" )
248         else:
249             __Vector, __PersistentVector = Vector, VectorSerie
250         #
251         self.__adaoStudy.setControlInput(
252             asVector           = __Vector,
253             asPersistentVector = __PersistentVector,
254             toBeStored         = Stored,
255             )
256
257     def setEvolutionError(
258             self,
259             Matrix               = None,
260             ScalarSparseMatrix   = None,
261             DiagonalSparseMatrix = None,
262             Script               = None,
263             Stored               = False):
264         "Définition d'une entrée de calcul"
265         self.__dumper.register("setEvolutionError", dir(), locals())
266         if Script is not None:
267             __Covariance, __Scalar, __Vector = None, None, None
268             if ScalarSparseMatrix:
269                 __Scalar = _ImportFromScript(Script).getvalue( "EvolutionError" )
270             elif DiagonalSparseMatrix:
271                 __Vector = _ImportFromScript(Script).getvalue( "EvolutionError" )
272             else:
273                 __Covariance = _ImportFromScript(Script).getvalue( "EvolutionError" )
274         else:
275             __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
276         #
277         self.__adaoStudy.setEvolutionError(
278             asCovariance  = __Covariance,
279             asEyeByScalar = __Scalar,
280             asEyeByVector = __Vector,
281             toBeStored    = Stored,
282             )
283
284     def setEvolutionModel(
285             self,
286             Matrix         = None,
287             OneFunction    = None,
288             ThreeFunctions = None,
289             Parameters     = None,
290             Script         = None,
291             Stored         = False):
292         "Définition d'une entrée de calcul"
293         self.__dumper.register("setEvolutionModel", dir(), locals())
294         __Parameters = {}
295         if Parameters is not None and type(Parameters) == type({}):
296             if Parameters.has_key("DifferentialIncrement"):
297                 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
298             if Parameters.has_key("CenteredFiniteDifference"):
299                 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
300             if Parameters.has_key("EnableMultiProcessing"):
301                 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
302             if Parameters.has_key("NumberOfProcesses"):
303                 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
304         if Script is not None:
305             __Matrix, __Function = None, None
306             if Matrix:
307                 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
308             elif OneFunction:
309                 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
310                 __Function.update({"useApproximatedDerivatives":True})
311                 __Function.update(__Parameters)
312             elif ThreeFunctions:
313                 __Function = {
314                     "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
315                     "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
316                     "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
317                     }
318                 __Function.update(__Parameters)
319         else:
320             __Matrix = Matrix
321             if OneFunction is not None:
322                 __Function = { "Direct":OneFunction }
323                 __Function.update({"useApproximatedDerivatives":True})
324                 __Function.update(__Parameters)
325             elif ThreeFunctions is not None:
326                 if (type(ThreeFunctions) is not type({})) or \
327                     not ThreeFunctions.has_key("Direct") or \
328                     not ThreeFunctions.has_key("Tangent") or \
329                     not ThreeFunctions.has_key("Adjoint"):
330                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
331                 __Function = ThreeFunctions
332                 __Function.update(__Parameters)
333             else:
334                 __Function = None
335         #
336         self.__adaoStudy.setEvolutionModel(
337             asFunction = __Function,
338             asMatrix   = __Matrix,
339             toBeStored = Stored,
340             )
341
342     def setObservation(
343             self,
344             Vector         = None,
345             VectorSerie    = None,
346             Script         = None,
347             Stored         = False):
348         "Définition d'une entrée de calcul"
349         self.__dumper.register("setObservation", dir(), locals())
350         if Script is not None:
351             __Vector, __PersistentVector = None, None
352             if VectorSerie:
353                 __PersistentVector = _ImportFromScript(Script).getvalue( "Observation" )
354             else:
355                 __Vector = _ImportFromScript(Script).getvalue( "Observation" )
356         else:
357             __Vector, __PersistentVector = Vector, VectorSerie
358         #
359         self.__adaoStudy.setObservation(
360             asVector           = __Vector,
361             asPersistentVector = __PersistentVector,
362             toBeStored         = Stored,
363             )
364
365     def setObservationError(
366             self,
367             Matrix               = None,
368             ScalarSparseMatrix   = None,
369             DiagonalSparseMatrix = None,
370             Script               = None,
371             Stored               = False):
372         "Définition d'une entrée de calcul"
373         self.__dumper.register("setObservationError", dir(), locals())
374         if Script is not None:
375             __Covariance, __Scalar, __Vector = None, None, None
376             if ScalarSparseMatrix:
377                 __Scalar = _ImportFromScript(Script).getvalue( "ObservationError" )
378             elif DiagonalSparseMatrix:
379                 __Vector = _ImportFromScript(Script).getvalue( "ObservationError" )
380             else:
381                 __Covariance = _ImportFromScript(Script).getvalue( "ObservationError" )
382         else:
383             __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
384         #
385         self.__adaoStudy.setObservationError(
386             asCovariance  = __Covariance,
387             asEyeByScalar = __Scalar,
388             asEyeByVector = __Vector,
389             toBeStored    = Stored,
390             )
391
392     def setObservationOperator(
393             self,
394             Matrix         = None,
395             OneFunction    = None,
396             ThreeFunctions = None,
397             Parameters     = None,
398             Script         = None,
399             Stored         = False):
400         "Définition d'une entrée de calcul"
401         self.__dumper.register("setObservationOperator", dir(), locals())
402         __Parameters = {}
403         if Parameters is not None and type(Parameters) == type({}):
404             if Parameters.has_key("DifferentialIncrement"):
405                 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
406             if Parameters.has_key("CenteredFiniteDifference"):
407                 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
408             if Parameters.has_key("EnableMultiProcessing"):
409                 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
410             if Parameters.has_key("NumberOfProcesses"):
411                 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
412         if Script is not None:
413             __Matrix, __Function = None, None
414             if Matrix:
415                 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
416             elif OneFunction:
417                 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
418                 __Function.update({"useApproximatedDerivatives":True})
419                 __Function.update(__Parameters)
420             elif ThreeFunctions:
421                 __Function = {
422                     "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
423                     "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
424                     "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
425                     }
426                 __Function.update(__Parameters)
427         else:
428             __Matrix = Matrix
429             if OneFunction is not None:
430                 __Function = { "Direct":OneFunction }
431                 __Function.update({"useApproximatedDerivatives":True})
432                 __Function.update(__Parameters)
433             elif ThreeFunctions is not None:
434                 if (type(ThreeFunctions) is not type({})) or \
435                     not ThreeFunctions.has_key("Direct") or \
436                     not ThreeFunctions.has_key("Tangent") or \
437                     not ThreeFunctions.has_key("Adjoint"):
438                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint") 
439                 __Function = ThreeFunctions
440                 __Function.update(__Parameters)
441             else:
442                 __Function = None
443         #
444         self.__adaoStudy.setObservationOperator(
445             asFunction = __Function,
446             asMatrix   = __Matrix,
447             toBeStored = Stored,
448             )
449
450     # -----------------------------------------------------------
451
452     def setAlgorithmParameters(
453             self,
454             Algorithm  = None,
455             Parameters = None,
456             Script     = None):
457         "Définition d'un paramétrage du calcul"
458         self.__dumper.register("setAlgorithmParameters", dir(), locals())
459         if Script is not None:
460             __Algorithm  = _ImportFromScript(Script).getvalue( "Algorithm" )
461             __Parameters = _ImportFromScript(Script).getvalue( "AlgorithmParameters", "Parameters" )
462         else:
463             __Algorithm  = Algorithm
464             __Parameters = Parameters
465         self.__adaoStudy.setAlgorithm( choice = __Algorithm )
466         self.__adaoStudy.setAlgorithmParameters( asDico = __Parameters )
467
468     def setDebug(self):
469         "Définition d'un paramétrage du calcul"
470         self.__dumper.register("setDebug",dir(),locals())
471         return self.__adaoStudy.setDebug()
472
473     def setNoDebug(self):
474         "Définition d'un paramétrage du calcul"
475         self.__dumper.register("setNoDebug",dir(),locals())
476         return self.__adaoStudy.unsetDebug()
477
478     def setObserver(
479             self,
480             Variable = None,
481             Template = None,
482             String   = None,
483             Script   = None,
484             Info     = None):
485         "Définition d'un paramétrage du calcul"
486         self.__dumper.register("setObserver", dir(), locals())
487         if Variable is None:
488             raise ValueError("setting an observer has to be done over a variable name, not over None.")
489         else:
490             __Variable = str(Variable)
491             if Info is None:
492                 __Info = str(Variable)
493             else:
494                 __Info = str(Info)
495         #
496         if String is not None:
497             __FunctionText = String
498         elif Template is not None:
499             if Template == "ValuePrinter":
500                 __FunctionText = "print info,var[-1]"
501             if Template == "ValueSeriePrinter":
502                 __FunctionText = "print info,var[:]"
503             if Template == "ValueSaver":
504                 __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)"
505             if Template == "ValueSerieSaver":
506                 __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)"
507             if Template == "ValuePrinterAndSaver":
508                 __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)"
509             if Template == "ValueSeriePrinterAndSaver":
510                 __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)"
511             if Template == "ValueGnuPlotter":
512                 __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' ) )"
513             if Template == "ValueSerieGnuPlotter":
514                 __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' ) )"
515         elif Script is not None:
516             __FunctionText = _ImportFromScript(Script).getstring()
517         else:
518             __FunctionText = ""
519         __Function = _ObserverF(__FunctionText)
520         #
521         self.__adaoStudy.setDataObserver(
522             VariableName   = __Variable,
523             HookFunction   = __Function.getfunc(),
524             HookParameters = __Info,
525             )
526
527     # -----------------------------------------------------------
528
529     def executePythonScheme(self):
530         "Lancement du calcul"
531         self.__dumper.register("executePythonScheme", dir(), locals())
532         try:
533             self.__adaoStudy.analyze()
534         except Exception as e:
535             if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
536             else: msg = ""
537             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))
538
539     execute = executePythonScheme
540
541     def executeYACSScheme(self, File=None):
542         "Lancement du calcul"
543         self.__dumper.register("executeYACSScheme", dir(), locals())
544         raise NotImplementedError()
545
546     # -----------------------------------------------------------
547
548     def get(self, Concept=None):
549         "Récupération d'une sortie du calcul"
550         self.__dumper.register("get",dir(),locals(),Concept)
551         return self.__adaoStudy.get(Concept)
552
553     def dumpNormalizedCommands(self, filename=None):
554         "Récupération de la liste des commandes du cas"
555         return self.__dumper.dump(filename)
556
557     def __dir__(self):
558         return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
559
560 class _DumpLogger(object):
561     """
562     Conservation des commandes de création d'un cas
563     """
564     def __init__(self, __name="", __objname="case"):
565         self.__name     = str(__name)
566         self.__objname  = str(__objname)
567         self.__logSerie = []
568         self.__switchoff = False
569         self.__logSerie.append("#\n# Python script for ADAO TUI\n#")
570         self.__logSerie.append("from numpy import array, matrix")
571         self.__logSerie.append("import adaoBuilder")
572         self.__logSerie.append("%s = adaoBuilder.New('%s')"%(self.__objname, self.__name))
573     def register(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
574         "Enregistrement d'une commande individuelle"
575         if __command is not None and __keys is not None and __local is not None and not self.__switchoff:
576             __text  = ""
577             if __pre is not None:
578                 __text += "%s = "%__pre
579             __text += "%s.%s( "%(self.__objname,str(__command))
580             __keys.remove("self")
581             for k in __keys:
582                 __v = __local[k]
583                 if __v is None: continue
584                 __text += "%s=%s, "%(k,repr(__v))
585             __text += ")"
586             self.__logSerie.append(__text)
587             if __switchoff:
588                 self.__switchoff = True
589         if not __switchoff:
590             self.__switchoff = False
591     def dump(self, __filename=None):
592         "Restitution de la liste des commandes de création d'un cas"
593         __text = "\n".join(self.__logSerie)
594         if __filename is not None:
595             fid = open(__filename,"w")
596             fid.write(__text)
597             fid.close()
598         return __text
599
600 class _ObserverF(object):
601     """
602     Création d'une fonction d'observateur à partir de son texte
603     """
604     def __init__(self, corps=""):
605         self.__corps = corps
606     def func(self,var,info):
607         "Fonction d'observation"
608         exec(self.__corps)
609     def getfunc(self):
610         "Restitution du pointeur de fonction dans l'objet"
611         return self.func
612
613 class _ImportFromScript(object):
614     """
615     Obtention d'une variable nommée depuis un fichier script importé
616     """
617     def __init__(self, __filename=None):
618         "Verifie l'existence et importe le script"
619         __filename = __filename.rstrip(".py")
620         if __filename is None:
621             raise ValueError("The name of the file containing the variable to be imported has to be specified.")
622         if not os.path.isfile(str(__filename)+".py"):
623             raise ValueError("The file containing the variable to be imported doesn't seem to exist. The given file name is:\n  \"%s\""%__filename)
624         self.__scriptfile = __import__(__filename, globals(), locals(), [])
625         self.__scriptstring = open(__filename+".py",'r').read()
626     def getvalue(self, __varname=None, __synonym=None ):
627         "Renvoie la variable demandee"
628         if __varname is None:
629             raise ValueError("The name of the variable to be imported has to be specified.")
630         if not hasattr(self.__scriptfile, __varname):
631             if __synonym is None:
632                 raise ValueError("The imported script file doesn't contain the specified variable \"%s\"."%__varname)
633             elif not hasattr(self.__scriptfile, __synonym):
634                 raise ValueError("The imported script file doesn't contain the specified variable \"%s\"."%__synonym)
635             else:
636                 return getattr(self.__scriptfile, __synonym)
637         else:
638             return getattr(self.__scriptfile, __varname)
639     def getstring(self):
640         return self.__scriptstring
641
642 # ==============================================================================
643 if __name__ == "__main__":
644     print '\n AUTODIAGNOSTIC \n'