1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2015 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 Interface de scripting pour une étude ADAO
26 __author__ = "Jean-Philippe ARGAUD"
30 from daCore import AssimilationStudy
34 Creation TUI d'un cas ADAO
36 def __init__(self, name = ""):
37 self.__adaoStudy = AssimilationStudy.AssimilationStudy(name)
38 self.__dumper = _DumpLogger(name)
40 # -----------------------------------------------------------
46 DiagonalSparseMatrix = None,
51 ScalarSparseMatrix = None,
56 ThreeFunctions = None,
60 "Interface unique de définition de variables d'entrées par argument"
61 self.__dumper.register("set",dir(),locals(),None,True)
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":
93 elif Concept == "NoDebug":
95 elif Concept == "Observer":
96 self.setObserver(Variable,Template,String,Script,Info)
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)
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))
104 # -----------------------------------------------------------
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
117 __PersistentVector = _ImportFromScript(Script).getvalue( "Background" )
119 __Vector = _ImportFromScript(Script).getvalue( "Background" )
121 __Vector, __PersistentVector = Vector, VectorSerie
123 self.__adaoStudy.setBackground(
125 asPersistentVector = __PersistentVector,
129 def setBackgroundError(
132 ScalarSparseMatrix = None,
133 DiagonalSparseMatrix = None,
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" )
145 __Covariance = _ImportFromScript(Script).getvalue( "BackgroundError" )
147 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
149 self.__adaoStudy.setBackgroundError(
150 asCovariance = __Covariance,
151 asEyeByScalar = __Scalar,
152 asEyeByVector = __Vector,
156 def setCheckingPoint(
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
167 __PersistentVector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
169 __Vector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
171 __Vector, __PersistentVector = Vector, VectorSerie
173 self.__adaoStudy.setBackground(
175 asPersistentVector = __PersistentVector,
183 ThreeFunctions = None,
187 "Définition d'une entrée de calcul"
188 self.__dumper.register("setControlModel", dir(), locals())
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
198 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
200 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
201 __Function.update({"useApproximatedDerivatives":True})
202 __Function.update(__Parameters)
205 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
206 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
207 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
209 __Function.update(__Parameters)
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)
227 self.__adaoStudy.setControlModel(
228 asFunction = __Function,
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
244 __PersistentVector = _ImportFromScript(Script).getvalue( "ControlInput" )
246 __Vector = _ImportFromScript(Script).getvalue( "ControlInput" )
248 __Vector, __PersistentVector = Vector, VectorSerie
250 self.__adaoStudy.setControlInput(
252 asPersistentVector = __PersistentVector,
256 def setEvolutionError(
259 ScalarSparseMatrix = None,
260 DiagonalSparseMatrix = None,
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" )
272 __Covariance = _ImportFromScript(Script).getvalue( "EvolutionError" )
274 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
276 self.__adaoStudy.setEvolutionError(
277 asCovariance = __Covariance,
278 asEyeByScalar = __Scalar,
279 asEyeByVector = __Vector,
283 def setEvolutionModel(
287 ThreeFunctions = None,
291 "Définition d'une entrée de calcul"
292 self.__dumper.register("setEvolutionModel", dir(), locals())
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
306 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
308 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
309 __Function.update({"useApproximatedDerivatives":True})
310 __Function.update(__Parameters)
313 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
314 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
315 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
317 __Function.update(__Parameters)
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)
335 self.__adaoStudy.setEvolutionModel(
336 asFunction = __Function,
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
352 __PersistentVector = _ImportFromScript(Script).getvalue( "Observation" )
354 __Vector = _ImportFromScript(Script).getvalue( "Observation" )
356 __Vector, __PersistentVector = Vector, VectorSerie
358 self.__adaoStudy.setObservation(
360 asPersistentVector = __PersistentVector,
364 def setObservationError(
367 ScalarSparseMatrix = None,
368 DiagonalSparseMatrix = None,
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" )
380 __Covariance = _ImportFromScript(Script).getvalue( "ObservationError" )
382 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
384 self.__adaoStudy.setObservationError(
385 asCovariance = __Covariance,
386 asEyeByScalar = __Scalar,
387 asEyeByVector = __Vector,
391 def setObservationOperator(
395 ThreeFunctions = None,
399 "Définition d'une entrée de calcul"
400 self.__dumper.register("setObservationOperator", dir(), locals())
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
414 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
416 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
417 __Function.update({"useApproximatedDerivatives":True})
418 __Function.update(__Parameters)
421 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
422 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
423 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
425 __Function.update(__Parameters)
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)
443 self.__adaoStudy.setObservationOperator(
444 asFunction = __Function,
449 # -----------------------------------------------------------
451 def setAlgorithmParameters(
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" )
462 __Algorithm = Algorithm
463 __Parameters = Parameters
464 self.__adaoStudy.setAlgorithm( choice = __Algorithm )
465 self.__adaoStudy.setAlgorithmParameters( asDico = __Parameters )
468 "Définition d'un paramétrage du calcul"
469 self.__dumper.register("setDebug",dir(),locals())
470 return self.__adaoStudy.setDebug()
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()
484 "Définition d'un paramétrage du calcul"
485 self.__dumper.register("setObserver", dir(), locals())
487 raise ValueError("setting an observer has to be done over a variable name, not over None.")
489 __Variable = str(Variable)
491 __Info = str(Variable)
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()
518 __Function = _ObserverF(__FunctionText)
520 self.__adaoStudy.setDataObserver(
521 VariableName = __Variable,
522 HookFunction = __Function.getfunc(),
523 HookParameters = __Info,
526 # -----------------------------------------------------------
528 def executePythonScheme(self):
529 "Lancement du calcul"
530 self.__dumper.register("executePythonScheme", dir(), locals())
532 self.__adaoStudy.analyze()
533 except Exception as e:
534 if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
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))
538 execute = executePythonScheme
540 def executeYACSScheme(self, File=None):
541 "Lancement du calcul"
542 self.__dumper.register("executeYACSScheme", dir(), locals())
543 raise NotImplementedError()
545 # -----------------------------------------------------------
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)
552 def dumpNormalizedCommands(self, filename=None):
553 "Récupération de la liste des commandes du cas"
554 return self.__dumper.dump(filename)
557 return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
559 class _DumpLogger(object):
561 Conservation des commandes de création d'un cas
563 def __init__(self, __name="", __objname="case"):
564 self.__name = str(__name)
565 self.__objname = str(__objname)
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:
576 if __pre is not None:
577 __text += "%s = "%__pre
578 __text += "%s.%s( "%(self.__objname,str(__command))
579 __keys.remove("self")
582 if __v is None: continue
583 __text += "%s=%s, "%(k,repr(__v))
585 self.__logSerie.append(__text)
587 self.__switchoff = True
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")
599 class _ObserverF(object):
601 Création d'une fonction d'observateur à partir de son texte
603 def __init__(self, corps=""):
605 def func(self,var,info):
606 "Fonction d'observation"
609 "Restitution du pointeur de fonction dans l'objet"
612 class _ImportFromScript(object):
614 Obtention d'une variable nommée depuis un fichier script importé
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)
635 return getattr(self.__scriptfile, __synonym)
637 return getattr(self.__scriptfile, __varname)
639 "Renvoie le script complet"
640 return self.__scriptstring
642 # ==============================================================================
643 if __name__ == "__main__":
644 print '\n AUTODIAGNOSTIC \n'