]> SALOME platform Git repositories - modules/adao.git/blob - src/daSalome/adaoBuilder.py
Salome HOME
Correction of observer
[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["EnableMultiProcessing"] = Parameters["EnableMultiProcessing"]
409                 __Parameters["withmpEnabled"]         = Parameters["EnableMultiProcessing"]
410             if Parameters.has_key("NumberOfProcesses"):
411                 __Parameters["NumberOfProcesses"] = Parameters["NumberOfProcesses"]
412                 __Parameters["withmpWorkers"]     = Parameters["NumberOfProcesses"]
413         if Script is not None:
414             __Matrix, __Function = None, None
415             if Matrix:
416                 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
417             elif OneFunction:
418                 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
419                 __Function.update({"useApproximatedDerivatives":True})
420                 __Function.update(__Parameters)
421             elif ThreeFunctions:
422                 __Function = {
423                     "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
424                     "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
425                     "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
426                     }
427                 __Function.update(__Parameters)
428         else:
429             __Matrix = Matrix
430             if OneFunction is not None:
431                 __Function = { "Direct":OneFunction }
432                 __Function.update({"useApproximatedDerivatives":True})
433                 __Function.update(__Parameters)
434             elif ThreeFunctions is not None:
435                 if (type(ThreeFunctions) is not type({})) or \
436                     not ThreeFunctions.has_key("Direct") or \
437                     not ThreeFunctions.has_key("Tangent") or \
438                     not ThreeFunctions.has_key("Adjoint"):
439                     raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
440                 __Function = ThreeFunctions
441                 __Function.update(__Parameters)
442             else:
443                 __Function = None
444         #
445         self.__adaoStudy.setObservationOperator(
446             asFunction = __Function,
447             asMatrix   = __Matrix,
448             toBeStored = Stored,
449             )
450
451     # -----------------------------------------------------------
452
453     def setAlgorithmParameters(
454             self,
455             Algorithm  = None,
456             Parameters = None,
457             Script     = None):
458         "Définition d'un paramétrage du calcul"
459         self.__dumper.register("setAlgorithmParameters", dir(), locals())
460         if Script is not None:
461             __Algorithm  = _ImportFromScript(Script).getvalue( "Algorithm" )
462             __Parameters = _ImportFromScript(Script).getvalue( "AlgorithmParameters", "Parameters" )
463         else:
464             __Algorithm  = Algorithm
465             __Parameters = Parameters
466         self.__adaoStudy.setAlgorithm( choice = __Algorithm )
467         self.__adaoStudy.setAlgorithmParameters( asDico = __Parameters )
468
469     def setDebug(self):
470         "Définition d'un paramétrage du calcul"
471         self.__dumper.register("setDebug",dir(),locals())
472         return self.__adaoStudy.setDebug()
473
474     def setNoDebug(self):
475         "Définition d'un paramétrage du calcul"
476         self.__dumper.register("setNoDebug",dir(),locals())
477         return self.__adaoStudy.unsetDebug()
478
479     def setObserver(
480             self,
481             Variable = None,
482             Template = None,
483             String   = None,
484             Script   = None,
485             Info     = None):
486         "Définition d'un paramétrage du calcul"
487         self.__dumper.register("setObserver", dir(), locals())
488         if Variable is None:
489             raise ValueError("setting an observer has to be done over a variable name, not over None.")
490         else:
491             __Variable = str(Variable)
492             if Info is None:
493                 __Info = str(Variable)
494             else:
495                 __Info = str(Info)
496         #
497         if String is not None:
498             __FunctionText = String
499         elif Template is not None:
500             if Template == "ValuePrinter":
501                 __FunctionText = """print info, var[-1]"""
502             if Template == "ValueSeriePrinter":
503                 __FunctionText = """print info, var[:]"""
504             if Template == "ValueSaver":
505                 __FunctionText = """import numpy, re\nv=numpy.array(var[-1], ndmin=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)"""
506             if Template == "ValueSerieSaver":
507                 __FunctionText = """import numpy, re\nv=numpy.array(var[:],  ndmin=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)"""
508             if Template == "ValuePrinterAndSaver":
509                 __FunctionText = """import numpy, re\nv=numpy.array(var[-1], ndmin=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)"""
510             if Template == "ValueSeriePrinterAndSaver":
511                 __FunctionText = """import numpy, re\nv=numpy.array(var[:],  ndmin=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)"""
512             if Template == "ValueGnuPlotter":
513                 __FunctionText = """import numpy, Gnuplot\nv=numpy.array(var[-1], ndmin=1)\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( v, with_='lines lw 2' ) )"""
514             if Template == "ValueSerieGnuPlotter":
515                 __FunctionText = """import numpy, Gnuplot\nv=numpy.array(var[:],  ndmin=1)\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( v, with_='lines lw 2' ) )"""
516             if Template == "ValuePrinterAndGnuPlotter":
517                 __FunctionText = """print info, var[-1]\nimport numpy, Gnuplot\nv=numpy.array(var[-1], ndmin=1)\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( v, with_='lines lw 2' ) )"""
518             if Template == "ValueSeriePrinterAndGnuPlotter":
519                 __FunctionText = """print info, var[:] \nimport numpy, Gnuplot\nv=numpy.array(var[:],  ndmin=1)\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( v, with_='lines lw 2' ) )"""
520             if Template == "ValuePrinterSaverAndGnuPlotter":
521                 __FunctionText = """print info, var[-1]\nimport numpy, re\nv=numpy.array(var[-1], ndmin=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)\nimport 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( v, with_='lines lw 2' ) )"""
522             if Template == "ValueSeriePrinterSaverAndGnuPlotter":
523                 __FunctionText = """print info, var[:] \nimport numpy, re\nv=numpy.array(var[:],  ndmin=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)\nimport 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( v, with_='lines lw 2' ) )"""
524         elif Script is not None:
525             __FunctionText = _ImportFromScript(Script).getstring()
526         else:
527             __FunctionText = ""
528         __Function = _ObserverF(__FunctionText)
529         #
530         self.__adaoStudy.setDataObserver(
531             VariableName   = __Variable,
532             HookFunction   = __Function.getfunc(),
533             HookParameters = __Info,
534             )
535
536     # -----------------------------------------------------------
537
538     def executePythonScheme(self):
539         "Lancement du calcul"
540         self.__dumper.register("executePythonScheme", dir(), locals())
541         try:
542             self.__adaoStudy.analyze()
543         except Exception as e:
544             if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
545             else: msg = ""
546             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))
547
548     execute = executePythonScheme
549
550     def executeYACSScheme(self, File=None):
551         "Lancement du calcul"
552         self.__dumper.register("executeYACSScheme", dir(), locals())
553         raise NotImplementedError()
554
555     # -----------------------------------------------------------
556
557     def get(self, Concept=None):
558         "Récupération d'une sortie du calcul"
559         self.__dumper.register("get",dir(),locals(),Concept)
560         return self.__adaoStudy.get(Concept)
561
562     def dumpNormalizedCommands(self, filename=None):
563         "Récupération de la liste des commandes du cas"
564         return self.__dumper.dump(filename)
565
566     def __dir__(self):
567         return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
568
569 class _DumpLogger(object):
570     """
571     Conservation des commandes de création d'un cas
572     """
573     def __init__(self, __name="", __objname="case"):
574         self.__name     = str(__name)
575         self.__objname  = str(__objname)
576         self.__logSerie = []
577         self.__switchoff = False
578         self.__logSerie.append("#\n# Python script for ADAO TUI\n#")
579         self.__logSerie.append("from numpy import array, matrix")
580         self.__logSerie.append("import adaoBuilder")
581         self.__logSerie.append("%s = adaoBuilder.New('%s')"%(self.__objname, self.__name))
582     def register(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
583         "Enregistrement d'une commande individuelle"
584         if __command is not None and __keys is not None and __local is not None and not self.__switchoff:
585             __text  = ""
586             if __pre is not None:
587                 __text += "%s = "%__pre
588             __text += "%s.%s( "%(self.__objname,str(__command))
589             __keys.remove("self")
590             for k in __keys:
591                 __v = __local[k]
592                 if __v is None: continue
593                 __text += "%s=%s, "%(k,repr(__v))
594             __text += ")"
595             self.__logSerie.append(__text)
596             if __switchoff:
597                 self.__switchoff = True
598         if not __switchoff:
599             self.__switchoff = False
600     def dump(self, __filename=None):
601         "Restitution de la liste des commandes de création d'un cas"
602         __text = "\n".join(self.__logSerie)
603         if __filename is not None:
604             fid = open(__filename,"w")
605             fid.write(__text)
606             fid.close()
607         return __text
608
609 class _ObserverF(object):
610     """
611     Création d'une fonction d'observateur à partir de son texte
612     """
613     def __init__(self, corps=""):
614         self.__corps = corps
615     def func(self,var,info):
616         "Fonction d'observation"
617         exec(self.__corps)
618     def getfunc(self):
619         "Restitution du pointeur de fonction dans l'objet"
620         return self.func
621
622 class _ImportFromScript(object):
623     """
624     Obtention d'une variable nommée depuis un fichier script importé
625     """
626     def __init__(self, __filename=None):
627         "Verifie l'existence et importe le script"
628         __filename = __filename.rstrip(".py")
629         if __filename is None:
630             raise ValueError("The name of the file containing the variable to be imported has to be specified.")
631         if not os.path.isfile(str(__filename)+".py"):
632             raise ValueError("The file containing the variable to be imported doesn't seem to exist. The given file name is:\n  \"%s\""%__filename)
633         self.__scriptfile = __import__(__filename, globals(), locals(), [])
634         self.__scriptstring = open(__filename+".py",'r').read()
635     def getvalue(self, __varname=None, __synonym=None ):
636         "Renvoie la variable demandee"
637         if __varname is None:
638             raise ValueError("The name of the variable to be imported has to be specified.")
639         if not hasattr(self.__scriptfile, __varname):
640             if __synonym is None:
641                 raise ValueError("The imported script file doesn't contain the specified variable \"%s\"."%__varname)
642             elif not hasattr(self.__scriptfile, __synonym):
643                 raise ValueError("The imported script file doesn't contain the specified variable \"%s\"."%__synonym)
644             else:
645                 return getattr(self.__scriptfile, __synonym)
646         else:
647             return getattr(self.__scriptfile, __varname)
648     def getstring(self):
649         "Renvoie le script complet"
650         return self.__scriptstring
651
652 # ==============================================================================
653 if __name__ == "__main__":
654     print '\n AUTODIAGNOSTIC \n'