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