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["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
416 __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
418 __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
419 __Function.update({"useApproximatedDerivatives":True})
420 __Function.update(__Parameters)
423 "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
424 "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
425 "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
427 __Function.update(__Parameters)
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)
445 self.__adaoStudy.setObservationOperator(
446 asFunction = __Function,
451 # -----------------------------------------------------------
453 def setAlgorithmParameters(
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" )
464 __Algorithm = Algorithm
465 __Parameters = Parameters
466 self.__adaoStudy.setAlgorithm( choice = __Algorithm )
467 self.__adaoStudy.setAlgorithmParameters( asDico = __Parameters )
470 "Définition d'un paramétrage du calcul"
471 self.__dumper.register("setDebug",dir(),locals())
472 return self.__adaoStudy.setDebug()
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()
486 "Définition d'un paramétrage du calcul"
487 self.__dumper.register("setObserver", dir(), locals())
489 raise ValueError("setting an observer has to be done over a variable name, not over None.")
491 __Variable = str(Variable)
493 __Info = str(Variable)
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()
528 __Function = _ObserverF(__FunctionText)
530 self.__adaoStudy.setDataObserver(
531 VariableName = __Variable,
532 HookFunction = __Function.getfunc(),
533 HookParameters = __Info,
536 # -----------------------------------------------------------
538 def executePythonScheme(self):
539 "Lancement du calcul"
540 self.__dumper.register("executePythonScheme", dir(), locals())
542 self.__adaoStudy.analyze()
543 except Exception as e:
544 if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
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))
548 execute = executePythonScheme
550 def executeYACSScheme(self, File=None):
551 "Lancement du calcul"
552 self.__dumper.register("executeYACSScheme", dir(), locals())
553 raise NotImplementedError()
555 # -----------------------------------------------------------
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)
562 def dumpNormalizedCommands(self, filename=None):
563 "Récupération de la liste des commandes du cas"
564 return self.__dumper.dump(filename)
567 return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
569 class _DumpLogger(object):
571 Conservation des commandes de création d'un cas
573 def __init__(self, __name="", __objname="case"):
574 self.__name = str(__name)
575 self.__objname = str(__objname)
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:
586 if __pre is not None:
587 __text += "%s = "%__pre
588 __text += "%s.%s( "%(self.__objname,str(__command))
589 __keys.remove("self")
592 if __v is None: continue
593 __text += "%s=%s, "%(k,repr(__v))
595 self.__logSerie.append(__text)
597 self.__switchoff = True
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")
609 class _ObserverF(object):
611 Création d'une fonction d'observateur à partir de son texte
613 def __init__(self, corps=""):
615 def func(self,var,info):
616 "Fonction d'observation"
619 "Restitution du pointeur de fonction dans l'objet"
622 class _ImportFromScript(object):
624 Obtention d'une variable nommée depuis un fichier script importé
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)
645 return getattr(self.__scriptfile, __synonym)
647 return getattr(self.__scriptfile, __varname)
649 "Renvoie le script complet"
650 return self.__scriptstring
652 # ==============================================================================
653 if __name__ == "__main__":
654 print '\n AUTODIAGNOSTIC \n'