1 # -*- coding: utf-8 -*-
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 (generic API)
26 __author__ = "Jean-Philippe ARGAUD"
30 from daCore import ExtendedLogging ; ExtendedLogging.ExtendedLogging() # A importer en premier
34 from daCore.BasicObjects import State, Covariance, FullOperator, Operator
35 from daCore.BasicObjects import AlgorithmAndParameters, DataObserver
36 from daCore.BasicObjects import DiagnosticAndParameters, ImportFromScript
37 from daCore.BasicObjects import CaseLogger, GenericCaseViewer
38 from daCore.Templates import ObserverTemplates
39 from daCore import Persistence
40 from daCore import PlatformInfo
42 # ==============================================================================
43 class DICViewer(GenericCaseViewer):
45 Etablissement des commandes de creation d'un cas DIC
47 def __init__(self, __name="", __objname="case", __content=None):
48 "Initialisation et enregistrement de l'entete"
49 GenericCaseViewer.__init__(self, __name, __objname, __content)
50 self._addLine("# -*- coding: utf-8 -*-")
51 self._addLine("#\n# Input for ADAO converter to YACS\n#")
52 self._addLine("from numpy import array, matrix")
54 self._addLine("study_config = {}")
55 self._addLine("study_config['StudyType'] = 'ASSIMILATION_STUDY'")
56 self._addLine("study_config['Name'] = '%s'"%self._name)
57 self._addLine("observers = {}")
58 self._addLine("study_config['Observers'] = observers")
60 self._addLine("inputvariables_config = {}")
61 self._addLine("inputvariables_config['Order'] =['adao_default']")
62 self._addLine("inputvariables_config['adao_default'] = -1")
63 self._addLine("study_config['InputVariables'] = inputvariables_config")
65 self._addLine("outputvariables_config = {}")
66 self._addLine("outputvariables_config['Order'] = ['adao_default']")
67 self._addLine("outputvariables_config['adao_default'] = -1")
68 self._addLine("study_config['OutputVariables'] = outputvariables_config")
69 if __content is not None:
70 for command in __content:
71 self._append(*command)
72 def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
73 "Transformation d'une commande individuelle en un enregistrement"
74 if __command == "set": __command = __local["Concept"]
75 else: __command = __command.replace("set", "", 1)
78 if __command in (None, 'execute', 'executePythonScheme', 'executeYACSScheme', 'get'):
80 elif __command in ['Debug', 'setDebug']:
81 __text = "#\nstudy_config['Debug'] = '1'"
82 elif __command in ['NoDebug', 'setNoDebug']:
83 __text = "#\nstudy_config['Debug'] = '0'"
84 elif __command in ['Observer', 'setObserver']:
85 __obs = __local['Variable']
86 self._numobservers += 1
88 __text += "observers['%s'] = {}\n"%__obs
89 if __local['String'] is not None:
90 __text += "observers['%s']['nodetype'] = '%s'\n"%(__obs, 'String')
91 __text += "observers['%s']['String'] = \"\"\"%s\"\"\"\n"%(__obs, __local['String'])
92 if __local['Script'] is not None:
93 __text += "observers['%s']['nodetype'] = '%s'\n"%(__obs, 'Script')
94 __text += "observers['%s']['Script'] = \"%s\"\n"%(__obs, __local['Script'])
95 if __local['Template'] is not None:
96 __text += "observers['%s']['nodetype'] = '%s'\n"%(__obs, 'String')
97 __text += "observers['%s']['String'] = \"\"\"%s\"\"\"\n"%(__obs, ObserverTemplates[__local['Template']])
98 if __local['Info'] is not None:
99 __text += "observers['%s']['info'] = \"\"\"%s\"\"\"\n"%(__obs, __local['Info'])
101 __text += "observers['%s']['info'] = \"\"\"%s\"\"\"\n"%(__obs, __obs)
102 __text += "observers['%s']['number'] = %s"%(__obs, self._numobservers)
103 elif __local is not None: # __keys is not None and
104 numpy.set_printoptions(precision=15,threshold=1000000,linewidth=1000*15)
106 __text += "%s_config = {}\n"%__command
107 if 'self' in __local: __local.pop('self')
109 for __k,__v in __local.items():
110 if __v is None: __to_be_removed.append(__k)
111 for __k in __to_be_removed:
113 for __k,__v in __local.items():
114 if __k == "Concept": continue
115 if __k in ['ScalarSparseMatrix','DiagonalSparseMatrix','Matrix','OneFunction','ThreeFunctions'] and 'Script' in __local: continue
116 if __k == 'Algorithm':
117 __text += "study_config['Algorithm'] = %s\n"%(repr(__v))
118 elif __k == 'Script':
121 __v = "'"+repr(__v)+"'"
122 for __lk in ['ScalarSparseMatrix','DiagonalSparseMatrix','Matrix']:
123 if __lk in __local and __local[__lk]: __k = __lk
124 if __command == "AlgorithmParameters": __k = "Dict"
125 if 'OneFunction' in __local and __local['OneFunction']:
126 __text += "%s_ScriptWithOneFunction = {}\n"%(__command,)
127 __text += "%s_ScriptWithOneFunction['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"%(__command,)
128 __text += "%s_ScriptWithOneFunction['Script'] = {}\n"%(__command,)
129 __text += "%s_ScriptWithOneFunction['Script']['Direct'] = %s\n"%(__command,__v)
130 __text += "%s_ScriptWithOneFunction['Script']['Tangent'] = %s\n"%(__command,__v)
131 __text += "%s_ScriptWithOneFunction['Script']['Adjoint'] = %s\n"%(__command,__v)
132 __text += "%s_ScriptWithOneFunction['DifferentialIncrement'] = 1e-06\n"%(__command,)
133 __text += "%s_ScriptWithOneFunction['CenteredFiniteDifference'] = 0\n"%(__command,)
135 __f = 'ScriptWithOneFunction'
136 __v = '%s_ScriptWithOneFunction'%(__command,)
137 if 'ThreeFunctions' in __local and __local['ThreeFunctions']:
138 __text += "%s_ScriptWithFunctions = {}\n"%(__command,)
139 __text += "%s_ScriptWithFunctions['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"%(__command,)
140 __text += "%s_ScriptWithFunctions['Script'] = {}\n"%(__command,)
141 __text += "%s_ScriptWithFunctions['Script']['Direct'] = %s\n"%(__command,__v)
142 __text += "%s_ScriptWithFunctions['Script']['Tangent'] = %s\n"%(__command,__v)
143 __text += "%s_ScriptWithFunctions['Script']['Adjoint'] = %s\n"%(__command,__v)
145 __f = 'ScriptWithFunctions'
146 __v = '%s_ScriptWithFunctions'%(__command,)
147 __text += "%s_config['Type'] = '%s'\n"%(__command,__k)
148 __text += "%s_config['From'] = '%s'\n"%(__command,__f)
149 __text += "%s_config['Data'] = %s\n"%(__command,__v)
150 __text = __text.replace("''","'")
151 elif __k in ('Stored', 'Checked'):
153 __text += "%s_config['%s'] = '%s'\n"%(__command,__k,int(bool(__v)))
154 elif __k in ('AvoidRC', 'noDetails'):
156 __text += "%s_config['%s'] = '%s'\n"%(__command,__k,int(bool(__v)))
158 if __k is 'Parameters': __k = "Dict"
159 if isinstance(__v,Persistence.Persistence): __v = __v.values()
160 if callable(__v): __text = self._missing%__v.__name__+__text
161 if isinstance(__v,dict):
162 for val in __v.values():
163 if callable(val): __text = self._missing%val.__name__+__text
164 __text += "%s_config['Type'] = '%s'\n"%(__command,__k)
165 __text += "%s_config['From'] = '%s'\n"%(__command,'String')
166 __text += "%s_config['Data'] = \"\"\"%s\"\"\"\n"%(__command,repr(__v))
167 __text += "study_config['%s'] = %s_config"%(__command,__command)
168 numpy.set_printoptions(precision=8,threshold=1000,linewidth=75)
170 self._switchoff = True
171 if __text is not None: self._addLine(__text)
173 self._switchoff = False
175 self.__loadVariablesByScript()
177 self._addLine("Analysis_config = {}")
178 self._addLine("Analysis_config['From'] = 'String'")
179 self._addLine("Analysis_config['Data'] = \"\"\"import numpy")
180 self._addLine("xa=numpy.ravel(ADD.get('Analysis')[-1])")
181 self._addLine("print 'Analysis:',xa\"\"\"")
182 self._addLine("study_config['UserPostAnalysis'] = Analysis_config")
183 def __loadVariablesByScript(self):
184 exec("\n".join(self._lineSerie))
185 if "Algorithm" in study_config and len(study_config['Algorithm'])>0:
186 self.__hasAlgorithm = True
188 self.__hasAlgorithm = False
189 if not self.__hasAlgorithm and \
190 "AlgorithmParameters" in study_config and \
191 isinstance(study_config['AlgorithmParameters'], dict) and \
192 "From" in study_config['AlgorithmParameters'] and \
193 "Data" in study_config['AlgorithmParameters'] and \
194 study_config['AlgorithmParameters']['From'] == 'Script':
195 __asScript = study_config['AlgorithmParameters']['Data']
196 __var = ImportFromScript(__asScript).getvalue( "Algorithm" )
197 __text = "#\nstudy_config['Algorithm'] = '%s'"%(__var,)
198 self._addLine(__text)
199 if self.__hasAlgorithm and \
200 "AlgorithmParameters" in study_config and \
201 isinstance(study_config['AlgorithmParameters'], dict) and \
202 "From" not in study_config['AlgorithmParameters'] and \
203 "Data" not in study_config['AlgorithmParameters']:
205 __text += "AlgorithmParameters_config['Type'] = 'Dict'\n"
206 __text += "AlgorithmParameters_config['From'] = 'String'\n"
207 __text += "AlgorithmParameters_config['Data'] = '{}'\n"
208 self._addLine(__text)
211 class XMLViewer(GenericCaseViewer):
213 Etablissement des commandes de creation d'un cas XML
215 def __init__(self, __name="", __objname="case", __content=None):
216 "Initialisation et enregistrement de l'entete"
217 GenericCaseViewer.__init__(self, __name, __objname, __content)
218 raise NotImplementedError()
220 # ==============================================================================
222 """ ADAO Internal Data Structure Model """
223 def __init__(self, name = "", addViewers={"DIC":DICViewer}):
224 self.__name = str(name)
225 self.__case = CaseLogger(self.__name, "case", addViewers)
227 self.__adaoObject = {}
228 self.__StoredInputs = {}
231 "AlgorithmParameters",
240 "ObservationOperator",
248 for ename in self.__Concepts:
249 self.__adaoObject[ename] = None
250 for ename in ("ObservationOperator", "EvolutionModel", "ControlModel"):
251 self.__adaoObject[ename] = {}
252 for ename in ("Diagnostic", "Observer"):
253 self.__adaoObject[ename] = []
254 self.__StoredInputs[ename] = []
256 # Récupère le chemin du répertoire parent et l'ajoute au path
257 # (Cela complète l'action de la classe PathManagement dans PlatformInfo,
258 # qui est activée dans Persistence)
259 self.__parent = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
260 sys.path.insert(0, self.__parent)
261 sys.path = PlatformInfo.uniq( sys.path ) # Conserve en unique exemplaire chaque chemin
264 Concept = None, # Premier argument
271 DiagonalSparseMatrix = None,
275 ObjectFunction = None,
279 ScalarSparseMatrix = None,
285 ThreeFunctions = None,
291 "Interface unique de definition de variables d'entrees par argument"
292 self.__case.register("set",dir(),locals(),None,True)
294 if Concept in ("Background", "CheckingPoint", "ControlInput", "Observation", "Controls"):
295 commande = getattr(self,"set"+Concept)
296 commande(Vector, VectorSerie, Script, Scheduler, Stored, Checked )
297 elif Concept in ("BackgroundError", "ObservationError", "EvolutionError"):
298 commande = getattr(self,"set"+Concept)
299 commande(Matrix, ScalarSparseMatrix, DiagonalSparseMatrix,
300 ObjectMatrix, Script, Stored, Checked )
301 elif Concept == "AlgorithmParameters":
302 self.setAlgorithmParameters( Algorithm, Parameters, Script )
303 elif Concept == "Debug":
305 elif Concept == "NoDebug":
307 elif Concept == "Observer":
308 self.setObserver( Variable, Template, String, Script, ObjectFunction, Scheduler, Info )
309 elif Concept == "Diagnostic":
310 self.setDiagnostic( Diagnostic, Identifier, Parameters, Script, Unit, BaseType )
311 elif Concept == "ObservationOperator":
312 self.setObservationOperator(
313 Matrix, OneFunction, ThreeFunctions, AppliedInXb,
314 Parameters, Script, AvoidRC, Stored, Checked )
315 elif Concept in ("EvolutionModel", "ControlModel"):
316 commande = getattr(self,"set"+Concept)
318 Matrix, OneFunction, ThreeFunctions,
319 Parameters, Script, Scheduler, AvoidRC, Stored, Checked )
322 raise ValueError("the variable named '%s' is not allowed."%str(Concept))
323 except Exception as e:
324 if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
326 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))
328 # -----------------------------------------------------------
330 def setBackground(self,
337 "Definition d'un concept de calcul"
338 Concept = "Background"
339 self.__case.register("set"+Concept, dir(), locals())
340 self.__adaoObject[Concept] = State(
343 asPersistentVector = VectorSerie,
345 scheduledBy = Scheduler,
346 toBeChecked = Checked,
349 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
352 def setCheckingPoint(self,
359 "Definition d'un concept de calcul"
360 Concept = "CheckingPoint"
361 self.__case.register("set"+Concept, dir(), locals())
362 self.__adaoObject[Concept] = State(
365 asPersistentVector = VectorSerie,
367 scheduledBy = Scheduler,
368 toBeChecked = Checked,
371 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
374 def setControlInput(self,
381 "Definition d'un concept de calcul"
382 Concept = "ControlInput"
383 self.__case.register("set"+Concept, dir(), locals())
384 self.__adaoObject[Concept] = State(
387 asPersistentVector = VectorSerie,
389 scheduledBy = Scheduler,
390 toBeChecked = Checked,
393 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
396 def setObservation(self,
403 "Definition d'un concept de calcul"
404 Concept = "Observation"
405 self.__case.register("set"+Concept, dir(), locals())
406 self.__adaoObject[Concept] = State(
409 asPersistentVector = VectorSerie,
411 scheduledBy = Scheduler,
412 toBeChecked = Checked,
415 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
418 def setControls(self,
419 Vector = (), # Valeur par defaut pour un vecteur vide
425 "Definition d'un concept de calcul"
427 self.__case.register("set"+Concept, dir(), locals())
428 self.__adaoObject[Concept] = State(
431 asPersistentVector = VectorSerie,
433 scheduledBy = Scheduler,
434 toBeChecked = Checked,
437 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
440 def setBackgroundError(self,
442 ScalarSparseMatrix = None,
443 DiagonalSparseMatrix = None,
448 "Definition d'un concept de calcul"
449 Concept = "BackgroundError"
450 self.__case.register("set"+Concept, dir(), locals())
451 self.__adaoObject[Concept] = Covariance(
453 asCovariance = Matrix,
454 asEyeByScalar = ScalarSparseMatrix,
455 asEyeByVector = DiagonalSparseMatrix,
456 asCovObject = ObjectMatrix,
458 toBeChecked = Checked,
461 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
464 def setObservationError(self,
466 ScalarSparseMatrix = None,
467 DiagonalSparseMatrix = None,
472 "Definition d'un concept de calcul"
473 Concept = "ObservationError"
474 self.__case.register("set"+Concept, dir(), locals())
475 self.__adaoObject[Concept] = Covariance(
477 asCovariance = Matrix,
478 asEyeByScalar = ScalarSparseMatrix,
479 asEyeByVector = DiagonalSparseMatrix,
480 asCovObject = ObjectMatrix,
482 toBeChecked = Checked,
485 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
488 def setEvolutionError(self,
490 ScalarSparseMatrix = None,
491 DiagonalSparseMatrix = None,
496 "Definition d'un concept de calcul"
497 Concept = "EvolutionError"
498 self.__case.register("set"+Concept, dir(), locals())
499 self.__adaoObject[Concept] = Covariance(
501 asCovariance = Matrix,
502 asEyeByScalar = ScalarSparseMatrix,
503 asEyeByVector = DiagonalSparseMatrix,
504 asCovObject = ObjectMatrix,
506 toBeChecked = Checked,
509 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
512 def setObservationOperator(self,
515 ThreeFunctions = None,
522 "Definition d'un concept de calcul"
523 Concept = "ObservationOperator"
524 self.__case.register("set"+Concept, dir(), locals())
525 self.__adaoObject[Concept] = FullOperator(
528 asOneFunction = OneFunction,
529 asThreeFunctions = ThreeFunctions,
532 appliedInX = AppliedInXb,
535 toBeChecked = Checked,
538 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
541 def setEvolutionModel(self,
544 ThreeFunctions = None,
551 "Definition d'un concept de calcul"
552 Concept = "EvolutionModel"
553 self.__case.register("set"+Concept, dir(), locals())
554 self.__adaoObject[Concept] = FullOperator(
557 asOneFunction = OneFunction,
558 asThreeFunctions = ThreeFunctions,
563 scheduledBy = Scheduler,
564 toBeChecked = Checked,
567 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
570 def setControlModel(self,
573 ThreeFunctions = None,
580 "Definition d'un concept de calcul"
581 Concept = "ControlModel"
582 self.__case.register("set"+Concept, dir(), locals())
583 self.__adaoObject[Concept] = FullOperator(
586 asOneFunction = OneFunction,
587 asThreeFunctions = ThreeFunctions,
592 scheduledBy = Scheduler,
593 toBeChecked = Checked,
596 self.__StoredInputs[Concept] = self.__adaoObject[Concept].getO()
599 def setDebug(self, level = 10):
600 "NOTSET=0 < DEBUG=10 < INFO=20 < WARNING=30 < ERROR=40 < CRITICAL=50"
601 self.__case.register("setDebug",dir(),locals())
602 log = logging.getLogger()
603 log.setLevel( level )
604 self.__StoredInputs["Debug"] = level
605 self.__StoredInputs["NoDebug"] = False
608 def setNoDebug(self):
609 "NOTSET=0 < DEBUG=10 < INFO=20 < WARNING=30 < ERROR=40 < CRITICAL=50"
610 self.__case.register("setNoDebug",dir(),locals())
611 log = logging.getLogger()
612 log.setLevel( logging.WARNING )
613 self.__StoredInputs["Debug"] = logging.WARNING
614 self.__StoredInputs["NoDebug"] = True
617 def setAlgorithmParameters(self,
621 "Definition d'un concept de calcul"
622 Concept = "AlgorithmParameters"
623 self.__case.register("set"+Concept, dir(), locals())
624 self.__adaoObject[Concept] = AlgorithmAndParameters(
626 asAlgorithm = Algorithm,
632 def updateAlgorithmParameters(self,
635 "Mise a jour d'un concept de calcul"
636 if "AlgorithmParameters" not in self.__adaoObject:
637 raise ValueError("No algorithm registred, ask for one before updating parameters")
638 self.__adaoObject["AlgorithmParameters"].updateParameters(
644 def setObserver(self,
649 ObjectFunction = None,
652 "Definition d'un concept de calcul"
654 self.__case.register("set"+Concept, dir(), locals())
655 self.__adaoObject[Concept].append( DataObserver(
657 onVariable = Variable,
658 asTemplate = Template,
661 asObsObject = ObjectFunction,
663 scheduledBy = Scheduler,
664 withAlgo = self.__adaoObject["AlgorithmParameters"]
668 def removeObserver(self,
670 ObjectFunction = None,
673 Permet de retirer un observer à une ou des variable nommée.
675 if "AlgorithmParameters" not in self.__adaoObject:
676 raise ValueError("No algorithm registred, ask for one before removing observers")
678 # Vérification du nom de variable et typage
679 # -----------------------------------------
680 if isinstance(Variable, str):
681 VariableNames = (Variable,)
682 elif isinstance(Variable, list):
683 VariableNames = tuple(map( str, Variable ))
685 raise ValueError("The observer requires a name or a list of names of variables.")
687 # Association interne de l'observer à la variable
688 # -----------------------------------------------
689 for ename in VariableNames:
690 if ename not in self.__adaoObject["AlgorithmParameters"]:
691 raise ValueError("An observer requires to be removed on a variable named %s which does not exist."%ename)
693 return self.__adaoObject["AlgorithmParameters"].removeObserver( ename, ObjectFunction )
695 # -----------------------------------------------------------
697 def setDiagnostic(self,
704 "Definition d'un concept de calcul"
705 Concept = "Diagnostic"
706 self.__case.register("set"+Concept, dir(), locals())
707 self.__adaoObject[Concept].append( DiagnosticAndParameters(
709 asDiagnostic = Diagnostic,
710 asIdentifier = Identifier,
714 asBaseType = BaseType,
715 asExistingDiags = self.__StoredInputs[Concept],
717 self.__StoredInputs[Concept].append(str(Identifier))
720 def get(self, Concept=None, noDetails=True ):
721 "Recuperation d'une sortie du calcul"
723 Permet d'accéder aux informations stockées, diagnostics et résultats
724 disponibles après l'exécution du calcul. Attention, quand un diagnostic
725 porte le même nom qu'une variable stockée (paramètre ou résultat),
726 c'est la variable stockée qui est renvoyée, et le diagnostic est
729 if Concept is not None:
731 self.__case.register("get", dir(), locals(), Concept) # Break pickle in Python 2
734 if Concept in self.__StoredInputs:
735 return self.__StoredInputs[Concept]
737 elif self.__adaoObject["AlgorithmParameters"] is not None and Concept == "AlgorithmParameters":
738 return self.__adaoObject["AlgorithmParameters"].get()
740 elif self.__adaoObject["AlgorithmParameters"] is not None and Concept in self.__adaoObject["AlgorithmParameters"]:
741 return self.__adaoObject["AlgorithmParameters"].get( Concept )
743 elif Concept == "AlgorithmRequiredParameters" and self.__adaoObject["AlgorithmParameters"] is not None:
744 return self.__adaoObject["AlgorithmParameters"].getAlgorithmRequiredParameters(noDetails)
746 elif Concept in self.__StoredInputs["Diagnostic"]:
747 indice = self.__StoredInputs["Diagnostic"].index(Concept)
748 return self.__adaoObject["Diagnostic"][indice].get()
751 raise ValueError("The requested key \"%s\" does not exists as an input, a diagnostic or a stored variable."%Concept)
754 allvariables.update( {"AlgorithmParameters":self.__adaoObject["AlgorithmParameters"].get()} )
755 allvariables.update( self.__adaoObject["AlgorithmParameters"].get() )
756 allvariables.update( self.__StoredInputs )
757 allvariables.pop('Diagnostic', None)
758 allvariables.pop('Observer', None)
761 # -----------------------------------------------------------
763 def get_available_variables(self):
765 Renvoie les variables potentiellement utilisables pour l'étude,
766 initialement stockées comme données d'entrées ou dans les algorithmes,
767 identifiés par les chaînes de caractères. L'algorithme doit avoir été
768 préalablement choisi sinon la méthode renvoie "None".
770 if len(list(self.__adaoObject["AlgorithmParameters"].keys())) == 0 and \
771 len(list(self.__StoredInputs.keys())) == 0:
775 if len(list(self.__adaoObject["AlgorithmParameters"].keys())) > 0:
776 variables.extend(list(self.__adaoObject["AlgorithmParameters"].keys()))
777 if len(list(self.__StoredInputs.keys())) > 0:
778 variables.extend( list(self.__StoredInputs.keys()) )
779 variables.remove('Diagnostic')
780 variables.remove('Observer')
784 def get_available_algorithms(self):
786 Renvoie la liste des algorithmes potentiellement utilisables, identifiés
787 par les chaînes de caractères.
790 for directory in sys.path:
791 if os.path.isdir(os.path.join(directory,"daAlgorithms")):
792 for fname in os.listdir(os.path.join(directory,"daAlgorithms")):
793 root, ext = os.path.splitext(fname)
794 if ext == '.py' and root != '__init__':
799 def get_available_diagnostics(self):
801 Renvoie la liste des diagnostics potentiellement utilisables, identifiés
802 par les chaînes de caractères.
805 for directory in sys.path:
806 if os.path.isdir(os.path.join(directory,"daDiagnostics")):
807 for fname in os.listdir(os.path.join(directory,"daDiagnostics")):
808 root, ext = os.path.splitext(fname)
809 if ext == '.py' and root != '__init__':
814 # -----------------------------------------------------------
816 def get_algorithms_main_path(self):
818 Renvoie le chemin pour le répertoire principal contenant les algorithmes
819 dans un sous-répertoire "daAlgorithms"
823 def add_algorithms_path(self, Path=None):
825 Ajoute au chemin de recherche des algorithmes un répertoire dans lequel
826 se trouve un sous-répertoire "daAlgorithms"
828 Remarque : si le chemin a déjà été ajouté pour les diagnostics, il n'est
829 pas indispensable de le rajouter ici.
831 if not os.path.isdir(Path):
832 raise ValueError("The given "+Path+" argument must exist as a directory")
833 if not os.path.isdir(os.path.join(Path,"daAlgorithms")):
834 raise ValueError("The given \""+Path+"\" argument must contain a subdirectory named \"daAlgorithms\"")
835 if not os.path.isfile(os.path.join(Path,"daAlgorithms","__init__.py")):
836 raise ValueError("The given \""+Path+"/daAlgorithms\" path must contain a file named \"__init__.py\"")
837 sys.path.insert(0, os.path.abspath(Path))
838 sys.path = PlatformInfo.uniq( sys.path ) # Conserve en unique exemplaire chaque chemin
841 def get_diagnostics_main_path(self):
843 Renvoie le chemin pour le répertoire principal contenant les diagnostics
844 dans un sous-répertoire "daDiagnostics"
848 def add_diagnostics_path(self, Path=None):
850 Ajoute au chemin de recherche des algorithmes un répertoire dans lequel
851 se trouve un sous-répertoire "daDiagnostics"
853 Remarque : si le chemin a déjà été ajouté pour les algorithmes, il n'est
854 pas indispensable de le rajouter ici.
856 if not os.path.isdir(Path):
857 raise ValueError("The given "+Path+" argument must exist as a directory")
858 if not os.path.isdir(os.path.join(Path,"daDiagnostics")):
859 raise ValueError("The given \""+Path+"\" argument must contain a subdirectory named \"daDiagnostics\"")
860 if not os.path.isfile(os.path.join(Path,"daDiagnostics","__init__.py")):
861 raise ValueError("The given \""+Path+"/daDiagnostics\" path must contain a file named \"__init__.py\"")
862 sys.path.insert(0, os.path.abspath(Path))
863 sys.path = PlatformInfo.uniq( sys.path ) # Conserve en unique exemplaire chaque chemin
866 # -----------------------------------------------------------
868 def execute(self, Executor=None, SaveCaseInFile=None):
869 "Lancement du calcul"
870 self.__case.register("execute",dir(),locals(),None,True)
871 Operator.CM.clearCache()
873 if Executor == "YACS": self.__executeYACSScheme( SaveCaseInFile )
874 else: self.__executePythonScheme( SaveCaseInFile )
875 except Exception as e:
876 if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
878 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.\n"%(str(e),msg))
881 def __executePythonScheme(self, FileName=None):
882 "Lancement du calcul"
883 self.__case.register("executePythonScheme", dir(), locals())
884 if FileName is not None:
885 self.dump( FileName, "TUI")
886 self.__adaoObject["AlgorithmParameters"].executePythonScheme( self.__adaoObject )
889 def __executeYACSScheme(self, FileName=None):
890 "Lancement du calcul"
891 self.__case.register("executeYACSScheme", dir(), locals())
892 if FileName is not None:
893 self.dump( FileName, "DIC")
894 self.__adaoObject["AlgorithmParameters"].executeYACSScheme( FileName )
897 # -----------------------------------------------------------
899 def dump(self, FileName=None, Formater="TUI"):
900 "Restitution normalisée des commandes"
901 return self.__case.dump(FileName, Formater)
903 def load(self, FileName=None, Formater="TUI"):
904 "Chargement normalisé des commandes"
905 __commands = self.__case.load(FileName, Formater)
906 from numpy import array, matrix
907 for __command in __commands:
908 exec("self."+__command)
912 "Effacement du contenu du cas en cours"
913 self.__init__(self.__name)
915 # -----------------------------------------------------------
918 "Clarifie la visibilité des méthodes"
919 return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
921 def prepare_to_pickle(self):
922 "Retire les variables non pickelisables, avec recopie efficace"
923 if self.__adaoObject['AlgorithmParameters'] is not None:
924 for k in self.__adaoObject['AlgorithmParameters'].keys():
925 if k == "Algorithm": continue
926 if k in self.__StoredInputs:
927 raise ValueError("the key \"%s\s to be transfered for pickling will overwrite an existing one.")
928 if self.__adaoObject['AlgorithmParameters'].hasObserver( k ):
929 self.__adaoObject['AlgorithmParameters'].removeObserver( k, "", True )
930 self.__StoredInputs[k] = self.__adaoObject['AlgorithmParameters'].pop(k, None)
931 del self.__adaoObject # Because it breaks pickle in Python 2. Not required for Python 3
932 del self.__case # Because it breaks pickle in Python 2. Not required for Python 3
935 # ==============================================================================
936 if __name__ == "__main__":
937 print('\n AUTODIAGNOSTIC \n')