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 sans lien avec YACS
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,
61 "Interface unique de définition de variables d'entrées par argument"
62 self.__dumper.register("set",dir(),locals(),None,True)
64 if Concept == "Background":
65 self.setBackground(Vector,VectorSerie,Script,Stored)
66 elif Concept == "BackgroundError":
67 self.setBackgroundError(Matrix,ScalarSparseMatrix,
68 DiagonalSparseMatrix,Script,Stored)
69 elif Concept == "CheckingPoint":
70 self.setCheckingPoint(Vector,VectorSerie,Script,Stored)
71 elif Concept == "ControlModel":
72 self.setControlModel(Matrix,OneFunction,ThreeFunctions,
73 Parameters,Script,Stored)
74 elif Concept == "ControlInput":
75 self.setControlInput(Vector,VectorSerie,Script,Stored)
76 elif Concept == "EvolutionError":
77 self.setEvolutionError(Matrix,ScalarSparseMatrix,
78 DiagonalSparseMatrix,Script,Stored)
79 elif Concept == "EvolutionModel":
80 self.setEvolutionModel(Matrix,OneFunction,ThreeFunctions,
81 Parameters,Script,Stored)
82 elif Concept == "Observation":
83 self.setObservation(Vector,VectorSerie,Script,Stored)
84 elif Concept == "ObservationError":
85 self.setObservationError(Matrix,ScalarSparseMatrix,
86 DiagonalSparseMatrix,Script,Stored)
87 elif Concept == "ObservationOperator":
88 self.setObservationOperator(Matrix,OneFunction,ThreeFunctions,
89 Parameters,Script,Stored)
90 elif Concept == "AlgorithmParameters":
91 self.setAlgorithmParameters(Algorithm,Parameters)
92 elif Concept == "Debug":
94 elif Concept == "NoDebug":
96 elif Concept == "Observer":
97 self.setObserver(Variable,Template,String,Info)
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)
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))
105 # -----------------------------------------------------------
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
118 __PersistentVector = _ImportFromScript(Script).getvalue( "Background" )
120 __Vector = _ImportFromScript(Script).getvalue( "Background" )
122 __Vector, __PersistentVector = Vector, VectorSerie
124 self.__adaoStudy.setBackground(
126 asPersistentVector = __PersistentVector,
130 def setBackgroundError(
133 ScalarSparseMatrix = None,
134 DiagonalSparseMatrix = None,
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" )
146 __Covariance = _ImportFromScript(Script).getvalue( "BackgroundError" )
148 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
150 self.__adaoStudy.setBackgroundError(
151 asCovariance = __Covariance,
152 asEyeByScalar = __Scalar,
153 asEyeByVector = __Vector,
157 def setCheckingPoint(
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
168 __PersistentVector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
170 __Vector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
172 __Vector, __PersistentVector = Vector, VectorSerie
174 self.__adaoStudy.setBackground(
176 asPersistentVector = __PersistentVector,
184 ThreeFunctions = None,
188 "Définition d'une entrée de calcul"
189 self.__dumper.register("setControlModel", dir(), locals())
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
199 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
201 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
202 __Function.update({"useApproximatedDerivatives":True})
203 __Function.update(__Parameters)
206 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
207 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
208 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
210 __Function.update(__Parameters)
214 if OneFunction is not None:
215 __Function = { "Direct":OneFunction }
216 __Function.update({"useApproximatedDerivatives":True})
217 __Function.update(__Parameters)
218 elif ThreeFunctions is not None:
219 if (type(ThreeFunctions) is not type({})) or \
220 not ThreeFunctions.has_key("Direct") or \
221 not ThreeFunctions.has_key("Tangent") or \
222 not ThreeFunctions.has_key("Adjoint"):
223 raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
224 __Function = ThreeFunctions
225 __Function.update(__Parameters)
229 self.__adaoStudy.setControlModel(
230 asFunction = __Function,
241 "Définition d'une entrée de calcul"
242 self.__dumper.register("setControlInput", dir(), locals())
243 if Script is not None:
244 __Vector, __PersistentVector = None, None
246 __PersistentVector = _ImportFromScript(Script).getvalue( "ControlInput" )
248 __Vector = _ImportFromScript(Script).getvalue( "ControlInput" )
250 __Vector, __PersistentVector = Vector, VectorSerie
252 self.__adaoStudy.setControlInput(
254 asPersistentVector = __PersistentVector,
258 def setEvolutionError(
261 ScalarSparseMatrix = None,
262 DiagonalSparseMatrix = None,
265 "Définition d'une entrée de calcul"
266 self.__dumper.register("setEvolutionError", dir(), locals())
267 if Script is not None:
268 __Covariance, __Scalar, __Vector = None, None, None
269 if ScalarSparseMatrix:
270 __Scalar = _ImportFromScript(Script).getvalue( "EvolutionError" )
271 elif DiagonalSparseMatrix:
272 __Vector = _ImportFromScript(Script).getvalue( "EvolutionError" )
274 __Covariance = _ImportFromScript(Script).getvalue( "EvolutionError" )
276 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
278 self.__adaoStudy.setEvolutionError(
279 asCovariance = __Covariance,
280 asEyeByScalar = __Scalar,
281 asEyeByVector = __Vector,
285 def setEvolutionModel(
289 ThreeFunctions = None,
293 "Définition d'une entrée de calcul"
294 self.__dumper.register("setEvolutionModel", dir(), locals())
296 if Parameters is not None and type(Parameters) == type({}):
297 if Parameters.has_key("DifferentialIncrement"):
298 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
299 if Parameters.has_key("CenteredFiniteDifference"):
300 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
301 if Parameters.has_key("EnableMultiProcessing"):
302 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
303 if Parameters.has_key("NumberOfProcesses"):
304 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
305 if Script is not None:
306 __Matrix, __Function = None, None
308 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
310 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
311 __Function.update({"useApproximatedDerivatives":True})
312 __Function.update(__Parameters)
315 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
316 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
317 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
319 __Function.update(__Parameters)
323 if OneFunction is not None:
324 __Function = { "Direct":OneFunction }
325 __Function.update({"useApproximatedDerivatives":True})
326 __Function.update(__Parameters)
327 elif ThreeFunctions is not None:
328 if (type(ThreeFunctions) is not type({})) or \
329 not ThreeFunctions.has_key("Direct") or \
330 not ThreeFunctions.has_key("Tangent") or \
331 not ThreeFunctions.has_key("Adjoint"):
332 raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
333 __Function = ThreeFunctions
334 __Function.update(__Parameters)
338 self.__adaoStudy.setEvolutionModel(
339 asFunction = __Function,
350 "Définition d'une entrée de calcul"
351 self.__dumper.register("setObservation", dir(), locals())
352 if Script is not None:
353 __Vector, __PersistentVector = None, None
355 __PersistentVector = _ImportFromScript(Script).getvalue( "Observation" )
357 __Vector = _ImportFromScript(Script).getvalue( "Observation" )
359 __Vector, __PersistentVector = Vector, VectorSerie
361 self.__adaoStudy.setObservation(
363 asPersistentVector = __PersistentVector,
367 def setObservationError(
370 ScalarSparseMatrix = None,
371 DiagonalSparseMatrix = None,
374 "Définition d'une entrée de calcul"
375 self.__dumper.register("setObservationError", dir(), locals())
376 if Script is not None:
377 __Covariance, __Scalar, __Vector = None, None, None
378 if ScalarSparseMatrix:
379 __Scalar = _ImportFromScript(Script).getvalue( "ObservationError" )
380 elif DiagonalSparseMatrix:
381 __Vector = _ImportFromScript(Script).getvalue( "ObservationError" )
383 __Covariance = _ImportFromScript(Script).getvalue( "ObservationError" )
385 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
387 self.__adaoStudy.setObservationError(
388 asCovariance = __Covariance,
389 asEyeByScalar = __Scalar,
390 asEyeByVector = __Vector,
394 def setObservationOperator(
398 ThreeFunctions = None,
402 "Définition d'une entrée de calcul"
403 self.__dumper.register("setObservationOperator", dir(), locals())
405 if Parameters is not None and type(Parameters) == type({}):
406 if Parameters.has_key("DifferentialIncrement"):
407 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
408 if Parameters.has_key("CenteredFiniteDifference"):
409 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
410 if Parameters.has_key("EnableMultiProcessing"):
411 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
412 if Parameters.has_key("NumberOfProcesses"):
413 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
414 if Script is not None:
415 __Matrix, __Function = None, None
417 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
419 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
420 __Function.update({"useApproximatedDerivatives":True})
421 __Function.update(__Parameters)
424 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
425 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
426 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
428 __Function.update(__Parameters)
432 if OneFunction is not None:
433 __Function = { "Direct":OneFunction }
434 __Function.update({"useApproximatedDerivatives":True})
435 __Function.update(__Parameters)
436 elif ThreeFunctions is not None:
437 if (type(ThreeFunctions) is not type({})) or \
438 not ThreeFunctions.has_key("Direct") or \
439 not ThreeFunctions.has_key("Tangent") or \
440 not ThreeFunctions.has_key("Adjoint"):
441 raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
442 __Function = ThreeFunctions
443 __Function.update(__Parameters)
447 self.__adaoStudy.setObservationOperator(
448 asFunction = __Function,
453 # -----------------------------------------------------------
455 def setAlgorithmParameters(
459 "Définition d'un paramétrage du calcul"
460 self.__dumper.register("setAlgorithmParameters", dir(), locals())
461 self.__adaoStudy.setAlgorithm( choice = Algorithm )
462 self.__adaoStudy.setAlgorithmParameters( asDico = Parameters )
465 "Définition d'un paramétrage du calcul"
466 self.__dumper.register("setDebug",dir(),locals())
467 return self.__adaoStudy.setDebug()
469 def setNoDebug(self):
470 "Définition d'un paramétrage du calcul"
471 self.__dumper.register("setNoDebug",dir(),locals())
472 return self.__adaoStudy.unsetDebug()
480 "Définition d'un paramétrage du calcul"
481 self.__dumper.register("setObserver", dir(), locals())
483 raise ValueError("setting an observer has to be done over a variable name, not over None.")
485 __Variable = str(Variable)
487 __Info = str(Variable)
491 if String is not None:
492 __FunctionText = String
493 elif Template is not None:
494 if Template == "ValuePrinter":
495 __FunctionText = "print info,var[-1]"
496 if Template == "ValueSeriePrinter":
497 __FunctionText = "print info,var[:]"
498 if Template == "ValueSaver":
499 __FunctionText = r"import numpy,re\nv=numpy.array((var[-1]))\nglobal istep\ntry:\n istep += 1\nexcept:\n istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
500 if Template == "ValueSerieSaver":
501 __FunctionText = r"import numpy,re\nv=numpy.array((var[:])) \nglobal istep\ntry:\n istep += 1\nexcept:\n istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
502 if Template == "ValuePrinterAndSaver":
503 __FunctionText = r"import numpy,re\nv=numpy.array((var[-1]))\nprint info,v\nglobal istep\ntry:\n istep += 1\nexcept:\n istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
504 if Template == "ValueSeriePrinterAndSaver":
505 __FunctionText = r"import numpy,re\nv=numpy.array((var[:])) \nprint info,v\nglobal istep\ntry:\n istep += 1\nexcept:\n istep = 0\nf='/tmp/value_%s_%05i.txt'%(info,istep)\nf=re.sub('\s','_',f)\nprint 'Value saved in \"%s\"'%f\nnumpy.savetxt(f,v)"
506 if Template == "ValueGnuPlotter":
507 __FunctionText = r"import Gnuplot\nglobal ifig,gp\ntry:\n ifig += 1\n gp('set style data lines')\nexcept:\n ifig = 0\n gp = Gnuplot.Gnuplot(persist=1)\n gp('set style data lines')\ngp('set title \"%s (Figure %i)\"'%(info,ifig))\ngp.plot( Gnuplot.Data( var[-1], with_='lines lw 2' ) )"
508 if Template == "ValueSerieGnuPlotter":
509 __FunctionText = r"import Gnuplot\nglobal ifig,gp\ntry:\n ifig += 1\n gp('set style data lines')\nexcept:\n ifig = 0\n gp = Gnuplot.Gnuplot(persist=1)\n gp('set style data lines')\ngp('set title \"%s (Figure %i)\"'%(info,ifig))\ngp.plot( Gnuplot.Data( var[:], with_='lines lw 2' ) )"
512 __Function = _ObserverF(__FunctionText)
514 self.__adaoStudy.setDataObserver(
515 VariableName = __Variable,
516 HookFunction = __Function.getfunc(),
517 HookParameters = __Info,
520 # -----------------------------------------------------------
522 def executePythonScheme(self):
523 "Lancement du calcul"
524 self.__dumper.register("executePythonScheme", dir(), locals())
526 self.__adaoStudy.analyze()
527 except Exception as e:
528 if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
530 raise ValueError("during execution, the following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the launching terminal."%(str(e),msg))
532 execute = executePythonScheme
534 def executeYACSScheme(self, File=None):
535 "Lancement du calcul"
536 self.__dumper.register("executeYACSScheme", dir(), locals())
537 raise NotImplementedError()
539 # -----------------------------------------------------------
541 def get(self, Concept=None):
542 "Récupération d'une sortie du calcul"
543 self.__dumper.register("get",dir(),locals(),Concept)
544 return self.__adaoStudy.get(Concept)
546 def dumpNormalizedCommands(self):
547 "Récupération de la liste des commandes de création d'un cas"
548 return self.__dumper.dump()
550 # def UserPostAnalysis(self):
551 # raise NotImplementedError()
553 # def StudyRepertory(self):
554 # raise NotImplementedError()
556 class _DumpLogger(object):
558 Conservation des commandes de création d'un cas
560 def __init__(self,__name="",__objname="case"):
562 # self.__logSerie.append("#-*-coding:iso-8859-1-*-\n#")
563 # self.__logSerie.append("# Copyright (C) 2008-2015 EDF R&D\n#")
564 self.__logSerie.append("#\n# Python script for ADAO\n#")
565 self.__logSerie.append("from numpy import *")
566 self.__logSerie.append("import adaoBuilder")
567 self.__logSerie.append("%s = adaoBuilder.New('%s')"%(__objname,__name))
568 self.__switchoff = False
569 def register(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
570 "Enregistrement d'une commande individuelle"
571 if __command is not None and __keys is not None and __local is not None and not self.__switchoff:
573 if __pre is not None:
574 __text += "%s = "%__pre
575 __text += "case.%s( "%str(__command)
576 __keys.remove("self")
579 if __v is None: continue
580 __text += "%s=%s, "%(k,repr(__v))
582 self.__logSerie.append(__text)
584 self.__switchoff = True
586 self.__switchoff = False
587 def dump(self,__filename=None):
588 "Restitution de la liste des commandes de création d'un cas"
589 if __filename is None:
590 return "\n".join(self.__logSerie)
592 fid = open(__filename,"w")
593 fid.writelines(self.__logSerie)
596 class _ObserverF(object):
598 Création d'une fonction d'observateur à partir de son texte
600 def __init__(self, corps=""):
602 def func(self,var,info):
603 "Fonction d'observation"
606 "Restitution du pointeur de fonction dans l'objet"
609 class _ImportFromScript(object):
611 Obtention d'une variable nommée depuis un fichier script importé
613 def __init__(self, __filename=None):
614 "Verifie l'existence et importe le script"
615 __filename = __filename.rstrip(".py")
616 if __filename is None:
617 raise ValueError("The name of the file containing the variable to be imported has to be specified.")
618 if not os.path.isfile(str(__filename)+".py"):
619 raise ValueError("The file containing the variable to be imported doesn't seem to exist. The given file name is:\n \"%s\""%__filename)
620 self.__scriptfile = __import__(__filename, globals(), locals(), [])
621 def getvalue(self, __varname=None ):
622 "Renvoie la variable demandee"
623 if __varname is None:
624 raise ValueError("The name of the variable to be imported has to be specified.")
625 if not hasattr(self.__scriptfile, __varname):
626 raise ValueError("The imported script file doesn't contain the specified variable \"%s\"."%__varname)
628 return getattr(self.__scriptfile, __varname)
630 # ==============================================================================
631 if __name__ == "__main__":
632 print '\n AUTODIAGNOSTIC \n'