1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2017 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 Normalized interface for ADAO scripting (full version API)
26 __author__ = "Jean-Philippe ARGAUD"
30 from daCore.AssimilationStudy import AssimilationStudy as _AssimilationStudy
31 from daCore.Templates import ObserverTemplates as _ObserverTemplates
32 from daCore.BasicObjects import ImportFromScript as _ImportFromScript
33 from daCore.BasicObjects import ObserverF as _ObserverF
35 # ==============================================================================
38 Creation TUI d'un cas ADAO
40 def __init__(self, name = ""):
41 self.__adaoStudy = _AssimilationStudy(name)
42 self.__case = _CaseLogger(name)
44 # -----------------------------------------------------------
50 DiagonalSparseMatrix = None,
55 ScalarSparseMatrix = None,
60 ThreeFunctions = None,
65 "Interface unique de definition de variables d'entrees par argument"
66 self.__case.register("set",dir(),locals(),None,True)
68 if Concept == "Background":
69 self.setBackground(Vector,VectorSerie,Script,Stored)
70 elif Concept == "BackgroundError":
71 self.setBackgroundError(Matrix,ScalarSparseMatrix,
72 DiagonalSparseMatrix,Script,Stored)
73 elif Concept == "CheckingPoint":
74 self.setCheckingPoint(Vector,VectorSerie,Script,Stored)
75 elif Concept == "ControlModel":
76 self.setControlModel(Matrix,OneFunction,ThreeFunctions,
77 Parameters,Script,Stored)
78 elif Concept == "ControlInput":
79 self.setControlInput(Vector,VectorSerie,Script,Stored)
80 elif Concept == "EvolutionError":
81 self.setEvolutionError(Matrix,ScalarSparseMatrix,
82 DiagonalSparseMatrix,Script,Stored)
83 elif Concept == "EvolutionModel":
84 self.setEvolutionModel(Matrix,OneFunction,ThreeFunctions,
85 Parameters,Script,Stored)
86 elif Concept == "Observation":
87 self.setObservation(Vector,VectorSerie,Script,Stored)
88 elif Concept == "ObservationError":
89 self.setObservationError(Matrix,ScalarSparseMatrix,
90 DiagonalSparseMatrix,Script,Stored)
91 elif Concept == "ObservationOperator":
92 self.setObservationOperator(Matrix,OneFunction,ThreeFunctions,
93 AppliedInXb, Parameters,Script,Stored)
94 elif Concept == "AlgorithmParameters":
95 self.setAlgorithmParameters(Algorithm,Parameters,Script)
96 elif Concept == "Debug":
98 elif Concept == "NoDebug":
100 elif Concept == "Observer":
101 self.setObserver(Variable,Template,String,Script,Info)
103 raise ValueError("the variable named '%s' is not allowed."%str(Concept))
104 except Exception as e:
105 if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
107 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))
109 # -----------------------------------------------------------
117 "Definition d'une entree de calcul"
118 self.__case.register("setBackground", dir(), locals())
119 if Script is not None:
120 __Vector, __PersistentVector = None, None
122 __PersistentVector = _ImportFromScript(Script).getvalue( "Background" )
124 __Vector = _ImportFromScript(Script).getvalue( "Background" )
126 __Vector, __PersistentVector = Vector, VectorSerie
128 self.__adaoStudy.setBackground(
130 asPersistentVector = __PersistentVector,
134 def setBackgroundError(
137 ScalarSparseMatrix = None,
138 DiagonalSparseMatrix = None,
141 "Definition d'une entree de calcul"
142 self.__case.register("setBackgroundError", dir(), locals())
143 if Script is not None:
144 __Covariance, __Scalar, __Vector = None, None, None
145 if ScalarSparseMatrix:
146 __Scalar = _ImportFromScript(Script).getvalue( "BackgroundError" )
147 elif DiagonalSparseMatrix:
148 __Vector = _ImportFromScript(Script).getvalue( "BackgroundError" )
150 __Covariance = _ImportFromScript(Script).getvalue( "BackgroundError" )
152 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
154 self.__adaoStudy.setBackgroundError(
155 asCovariance = __Covariance,
156 asEyeByScalar = __Scalar,
157 asEyeByVector = __Vector,
161 def setCheckingPoint(
167 "Definition d'une entree de verification"
168 self.__case.register("setCheckingPoint", dir(), locals())
169 if Script is not None:
170 __Vector, __PersistentVector = None, None
172 __PersistentVector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
174 __Vector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
176 __Vector, __PersistentVector = Vector, VectorSerie
178 self.__adaoStudy.setBackground(
180 asPersistentVector = __PersistentVector,
188 ThreeFunctions = None,
192 "Definition d'une entree de calcul"
193 self.__case.register("setControlModel", dir(), locals())
195 if (Parameters is not None) and isinstance(Parameters, dict):
196 if "DifferentialIncrement" in Parameters:
197 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
198 if "CenteredFiniteDifference" in Parameters:
199 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
200 if Script is not None:
201 __Matrix, __Function = None, None
203 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
205 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
206 __Function.update({"useApproximatedDerivatives":True})
207 __Function.update(__Parameters)
210 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
211 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
212 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
214 __Function.update(__Parameters)
217 if OneFunction is not None:
218 __Function = { "Direct":OneFunction }
219 __Function.update({"useApproximatedDerivatives":True})
220 __Function.update(__Parameters)
221 elif ThreeFunctions is not None:
222 if (not isinstance(ThreeFunctions, dict)) or \
223 "Direct" not in ThreeFunctions or \
224 "Tangent" not in ThreeFunctions or \
225 "Adjoint" not in ThreeFunctions:
226 raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
227 __Function = ThreeFunctions
228 __Function.update(__Parameters)
232 self.__adaoStudy.setControlModel(
233 asFunction = __Function,
244 "Definition d'une entree de calcul"
245 self.__case.register("setControlInput", dir(), locals())
246 if Script is not None:
247 __Vector, __PersistentVector = None, None
249 __PersistentVector = _ImportFromScript(Script).getvalue( "ControlInput" )
251 __Vector = _ImportFromScript(Script).getvalue( "ControlInput" )
253 __Vector, __PersistentVector = Vector, VectorSerie
255 self.__adaoStudy.setControlInput(
257 asPersistentVector = __PersistentVector,
261 def setEvolutionError(
264 ScalarSparseMatrix = None,
265 DiagonalSparseMatrix = None,
268 "Definition d'une entree de calcul"
269 self.__case.register("setEvolutionError", dir(), locals())
270 if Script is not None:
271 __Covariance, __Scalar, __Vector = None, None, None
272 if ScalarSparseMatrix:
273 __Scalar = _ImportFromScript(Script).getvalue( "EvolutionError" )
274 elif DiagonalSparseMatrix:
275 __Vector = _ImportFromScript(Script).getvalue( "EvolutionError" )
277 __Covariance = _ImportFromScript(Script).getvalue( "EvolutionError" )
279 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
281 self.__adaoStudy.setEvolutionError(
282 asCovariance = __Covariance,
283 asEyeByScalar = __Scalar,
284 asEyeByVector = __Vector,
288 def setEvolutionModel(
292 ThreeFunctions = None,
296 "Definition d'une entree de calcul"
297 self.__case.register("setEvolutionModel", dir(), locals())
299 if (Parameters is not None) and isinstance(Parameters, dict):
300 if "DifferentialIncrement" in Parameters:
301 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
302 if "CenteredFiniteDifference" in Parameters:
303 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
304 if "EnableMultiProcessing" in Parameters:
305 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
306 if "NumberOfProcesses" in Parameters:
307 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
308 if Script is not None:
309 __Matrix, __Function = None, None
311 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
313 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
314 __Function.update({"useApproximatedDerivatives":True})
315 __Function.update(__Parameters)
318 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
319 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
320 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
322 __Function.update(__Parameters)
325 if OneFunction is not None:
326 __Function = { "Direct":OneFunction }
327 __Function.update({"useApproximatedDerivatives":True})
328 __Function.update(__Parameters)
329 elif ThreeFunctions is not None:
330 if (not isinstance(ThreeFunctions, dict)) or \
331 "Direct" not in ThreeFunctions or \
332 "Tangent" not in ThreeFunctions or \
333 "Adjoint" not in ThreeFunctions:
334 raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
335 __Function = ThreeFunctions
336 __Function.update(__Parameters)
340 self.__adaoStudy.setEvolutionModel(
341 asFunction = __Function,
352 "Definition d'une entree de calcul"
353 self.__case.register("setObservation", dir(), locals())
354 if Script is not None:
355 __Vector, __PersistentVector = None, None
357 __PersistentVector = _ImportFromScript(Script).getvalue( "Observation" )
359 __Vector = _ImportFromScript(Script).getvalue( "Observation" )
361 __Vector, __PersistentVector = Vector, VectorSerie
363 self.__adaoStudy.setObservation(
365 asPersistentVector = __PersistentVector,
369 def setObservationError(
372 ScalarSparseMatrix = None,
373 DiagonalSparseMatrix = None,
376 "Definition d'une entree de calcul"
377 self.__case.register("setObservationError", dir(), locals())
378 if Script is not None:
379 __Covariance, __Scalar, __Vector = None, None, None
380 if ScalarSparseMatrix:
381 __Scalar = _ImportFromScript(Script).getvalue( "ObservationError" )
382 elif DiagonalSparseMatrix:
383 __Vector = _ImportFromScript(Script).getvalue( "ObservationError" )
385 __Covariance = _ImportFromScript(Script).getvalue( "ObservationError" )
387 __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
389 self.__adaoStudy.setObservationError(
390 asCovariance = __Covariance,
391 asEyeByScalar = __Scalar,
392 asEyeByVector = __Vector,
396 def setObservationOperator(
400 ThreeFunctions = None,
405 "Definition d'une entree de calcul"
406 self.__case.register("setObservationOperator", dir(), locals())
408 if (Parameters is not None) and isinstance(Parameters, dict):
409 if "DifferentialIncrement" in Parameters:
410 __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
411 if "CenteredFiniteDifference" in Parameters:
412 __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
413 if "EnableMultiProcessing" in Parameters:
414 __Parameters["EnableMultiProcessing"] = Parameters["EnableMultiProcessing"]
415 __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
416 if "NumberOfProcesses" in Parameters:
417 __Parameters["NumberOfProcesses"] = Parameters["NumberOfProcesses"]
418 __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
419 if Script is not None:
420 __Matrix, __Function = None, None
422 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
424 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
425 __Function.update({"useApproximatedDerivatives":True})
426 __Function.update(__Parameters)
429 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
430 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
431 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
433 __Function.update(__Parameters)
436 if OneFunction is not None:
437 __Function = { "Direct":OneFunction }
438 __Function.update({"useApproximatedDerivatives":True})
439 __Function.update(__Parameters)
440 elif ThreeFunctions is not None:
441 if (not isinstance(ThreeFunctions, dict)) or \
442 "Direct" not in ThreeFunctions or \
443 "Tangent" not in ThreeFunctions or \
444 "Adjoint" not in ThreeFunctions:
445 raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
446 __Function = ThreeFunctions
447 __Function.update(__Parameters)
450 if AppliedInXb is not None:
451 __appliedToX = {"HXb":AppliedInXb}
455 self.__adaoStudy.setObservationOperator(
456 asFunction = __Function,
458 appliedToX = __appliedToX,
462 # -----------------------------------------------------------
464 def setAlgorithmParameters(
469 "Definition d'un parametrage du calcul"
470 self.__case.register("setAlgorithmParameters", dir(), locals())
471 if Script is not None:
472 __Algorithm = _ImportFromScript(Script).getvalue( "Algorithm" )
473 __Parameters = _ImportFromScript(Script).getvalue( "AlgorithmParameters", "Parameters" )
475 __Algorithm = Algorithm
476 __Parameters = Parameters
477 self.__adaoStudy.setAlgorithm( choice = __Algorithm )
478 self.__adaoStudy.setAlgorithmParameters( asDico = __Parameters )
481 "Definition d'un parametrage du calcul"
482 self.__case.register("setDebug",dir(),locals())
483 return self.__adaoStudy.setDebug()
485 def setNoDebug(self):
486 "Definition d'un parametrage du calcul"
487 self.__case.register("setNoDebug",dir(),locals())
488 return self.__adaoStudy.unsetDebug()
497 "Definition d'un parametrage du calcul"
498 self.__case.register("setObserver", dir(), locals())
500 raise ValueError("setting an observer has to be done over a variable name, not over None.")
502 __Variable = str(Variable)
504 __Info = str(Variable)
508 if String is not None:
509 __FunctionText = String
510 elif (Template is not None) and (Template in _ObserverTemplates):
511 __FunctionText = _ObserverTemplates[Template]
512 elif Script is not None:
513 __FunctionText = _ImportFromScript(Script).getstring()
516 __Function = _ObserverF(__FunctionText)
518 self.__adaoStudy.setDataObserver(
519 VariableName = __Variable,
520 HookFunction = __Function.getfunc(),
521 HookParameters = __Info,
524 # -----------------------------------------------------------
526 def executePythonScheme(self):
527 "Lancement du calcul"
528 self.__case.register("executePythonScheme", dir(), locals())
530 self.__adaoStudy.analyze()
531 except Exception as e:
532 if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
534 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))
536 execute = executePythonScheme
538 def executeYACSScheme(self, File=None):
539 "Lancement du calcul"
540 self.__case.register("executeYACSScheme", dir(), locals())
541 raise NotImplementedError()
543 # -----------------------------------------------------------
545 def get(self, Concept=None):
546 "Recuperation d'une sortie du calcul"
547 self.__case.register("get",dir(),locals(),Concept)
548 return self.__adaoStudy.get(Concept)
550 def dumpNormalizedCommands(self, filename=None):
551 "Recuperation de la liste des commandes du cas TUI"
552 return self.__case.dump(filename, "TUI")
555 return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
557 # ==============================================================================
558 class _CaseLogger(object):
560 Conservation des commandes de creation d'un cas
562 def __init__(self, __name="", __objname="case"):
563 self.__name = str(__name)
564 self.__objname = str(__objname)
566 self.__switchoff = False
567 def register(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
568 "Enregistrement d'une commande individuelle"
569 if __command is not None and __keys is not None and __local is not None and not self.__switchoff:
570 if "self" in __keys: __keys.remove("self")
571 self.__logSerie.append( (str(__command), __keys, __local, __pre, __switchoff) )
573 self.__switchoff = True
575 self.__switchoff = False
576 def dump(self, __filename=None, __format="TUI"):
577 if __format == "TUI":
578 self.__dumper = _TUIViewer(self.__name, self.__objname, self.__logSerie)
579 __text = self.__dumper.dump(__filename)
581 raise ValueError("Dumping as \"%s\" is not available"%__format)
584 # ==============================================================================
585 class _GenericViewer(object):
587 Etablissement des commandes de creation d'une vue
589 def __init__(self, __name="", __objname="case", __content=None):
590 self._name = str(__name)
591 self._objname = str(__objname)
593 self._switchoff = False
594 self._numobservers = 1
595 def _addLine(self, line=""):
596 self._lineSerie.append(line)
598 "Enregistrement d'une commande individuelle"
599 raise NotImplementedError()
600 def dump(self, __filename=None):
601 "Restitution de la liste des commandes de creation d'un cas"
602 raise NotImplementedError()
604 class _TUIViewer(_GenericViewer):
606 Etablissement des commandes de creation d'un cas TUI
608 def __init__(self, __name="", __objname="case", __content=None):
609 _GenericViewer.__init__(self, __name, __objname, __content)
610 self._addLine("#\n# Python script for ADAO TUI\n#")
611 self._addLine("from numpy import array, matrix")
612 self._addLine("import adaoBuilder")
613 self._addLine("%s = adaoBuilder.New('%s')"%(self._objname, self._name))
614 if __content is not None:
615 for command in __content:
616 self._append(*command)
617 def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
618 if __command is not None and __keys is not None and __local is not None and not self._switchoff:
620 if __pre is not None:
621 __text += "%s = "%__pre
622 __text += "%s.%s( "%(self._objname,str(__command))
623 if "self" in __keys: __keys.remove("self")
626 if __v is None: continue
627 __text += "%s=%s, "%(k,repr(__v))
629 self._addLine(__text)
631 self._switchoff = True
633 self._switchoff = False
634 def dump(self, __filename=None):
635 __text = "\n".join(self._lineSerie)
636 if __filename is not None:
637 fid = open(__filename,"w")
642 # ==============================================================================
643 if __name__ == "__main__":
644 print('\n AUTODIAGNOSTIC \n')