Salome HOME
Minor documentation and code review corrections (32)
[modules/adao.git] / src / daComposant / daCore / Templates.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2022 EDF R&D
4 #
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.
9 #
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.
14 #
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
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 """
24     Modèles généraux pour les observers, le post-processing.
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27 __all__ = ["ObserverTemplates"]
28
29 import numpy
30
31 # ==============================================================================
32 class TemplateStorage(object):
33     """
34     Classe générale de stockage de type dictionnaire étendu
35     (Template)
36     """
37     __slots__ = ("__preferedLanguage", "__values", "__order")
38     #
39     def __init__( self, language = "fr_FR" ):
40         self.__preferedLanguage = language
41         self.__values           = {}
42         self.__order            = -1
43     #
44     def store( self, name = None, content = None, fr_FR = "", en_EN = "", order = "next" ):
45         "D.store(k, c,  fr_FR, en_EN, o) -> Store template k and its main characteristics"
46         if name is None or content is None:
47             raise ValueError("To be consistent, the storage of a template must provide a name and a content.")
48         if order == "next":
49             self.__order += 1
50         else:
51             self.__order = int(order)
52         self.__values[str(name)] = {
53             'content': str(content),
54             'fr_FR'  : str(fr_FR),
55             'en_EN'  : str(en_EN),
56             'order'  : int(self.__order),
57             }
58     #
59     def keys(self):
60         "D.keys() -> list of D's keys"
61         __keys = sorted(self.__values.keys())
62         return __keys
63     #
64     def __contains__(self, name):
65         "D.__contains__(k) -> True if D has a key k, else False"
66         return name in self.__values
67     #
68     def __len__(self):
69         "x.__len__() <==> len(x)"
70         return len(self.__values)
71     #
72     def __getitem__(self, name=None ):
73         "x.__getitem__(y) <==> x[y]"
74         return self.__values[name]['content']
75     #
76     def getdoc(self, name = None, lang = "fr_FR"):
77         "D.getdoc(k, l) -> Return documentation of key k in language l"
78         if lang not in self.__values[name]: lang = self.__preferedLanguage
79         return self.__values[name][lang]
80     #
81     def keys_in_presentation_order(self):
82         "D.keys_in_presentation_order() -> list of D's keys in presentation order"
83         __orders = []
84         for k in self.keys():
85             __orders.append( self.__values[k]['order'] )
86         __reorder = numpy.array(__orders).argsort()
87         return list(numpy.array(self.keys())[__reorder])
88
89 # ==============================================================================
90 ObserverTemplates = TemplateStorage()
91
92 ObserverTemplates.store(
93     name    = "ValuePrinter",
94     content = """print(str(info)+" "+str(var[-1]))""",
95     fr_FR   = "Imprime sur la sortie standard la valeur courante de la variable",
96     en_EN   = "Print on standard output the current value of the variable",
97     order   = "next",
98     )
99 ObserverTemplates.store(
100     name    = "ValueAndIndexPrinter",
101     content = """print(str(info)+(" index %i:"%(len(var)-1))+" "+str(var[-1]))""",
102     fr_FR   = "Imprime sur la sortie standard la valeur courante de la variable, en ajoutant son index",
103     en_EN   = "Print on standard output the current value of the variable, adding its index",
104     order   = "next",
105     )
106 ObserverTemplates.store(
107     name    = "ValueSeriePrinter",
108     content = """print(str(info)+" "+str(var[:]))""",
109     fr_FR   = "Imprime sur la sortie standard la série des valeurs de la variable",
110     en_EN   = "Print on standard output the value series of the variable",
111     order   = "next",
112     )
113 ObserverTemplates.store(
114     name    = "ValueSaver",
115     content = """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)""",
116     fr_FR   = "Enregistre la valeur courante de la variable dans un fichier du répertoire '/tmp' nommé 'value...txt' selon le nom de la variable et l'étape d'enregistrement",
117     en_EN   = "Save the current value of the variable in a file of the '/tmp' directory named 'value...txt' from the variable name and the saving step",
118     order   = "next",
119     )
120 ObserverTemplates.store(
121     name    = "ValueSerieSaver",
122     content = """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)""",
123     fr_FR   = "Enregistre la série des valeurs de la variable dans un fichier du répertoire '/tmp' nommé 'value...txt' selon le nom de la variable et l'étape",
124     en_EN   = "Save the value series of the variable in a file of the '/tmp' directory named 'value...txt' from the variable name and the saving step",
125     order   = "next",
126     )
127 ObserverTemplates.store(
128     name    = "ValuePrinterAndSaver",
129     content = """import numpy, re\nv=numpy.array(var[-1], ndmin=1)\nprint(str(info)+" "+str(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)""",
130     fr_FR   = "Imprime sur la sortie standard et, en même temps enregistre dans un fichier du répertoire '/tmp', la valeur courante de la variable",
131     en_EN   = "Print on standard output and, in the same time save in a file of the '/tmp' directory, the current value of the variable",
132     order   = "next",
133     )
134 ObserverTemplates.store(
135     name    = "ValueIndexPrinterAndSaver",
136     content = """import numpy, re\nv=numpy.array(var[-1], ndmin=1)\nprint(str(info)+(" index %i:"%(len(var)-1))+" "+str(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)""",
137     fr_FR   = "Imprime sur la sortie standard et, en même temps enregistre dans un fichier du répertoire '/tmp', la valeur courante de la variable, en ajoutant son index",
138     en_EN   = "Print on standard output and, in the same time save in a file of the '/tmp' directory, the current value of the variable, adding its index",
139     order   = "next",
140     )
141 ObserverTemplates.store(
142     name    = "ValueSeriePrinterAndSaver",
143     content = """import numpy, re\nv=numpy.array(var[:], ndmin=1)\nprint(str(info)+" "+str(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)""",
144     fr_FR   = "Imprime sur la sortie standard et, en même temps, enregistre dans un fichier du répertoire '/tmp', la série des valeurs de la variable",
145     en_EN   = "Print on standard output and, in the same time, save in a file of the '/tmp' directory, the value series of the variable",
146     order   = "next",
147     )
148 ObserverTemplates.store(
149     name    = "ValueGnuPlotter",
150     content = """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' ) )""",
151     fr_FR   = "Affiche graphiquement avec Gnuplot la valeur courante de la variable",
152     en_EN   = "Graphically plot with Gnuplot the current value of the variable",
153     order   = "next",
154     )
155 ObserverTemplates.store(
156     name    = "ValueSerieGnuPlotter",
157     content = """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' ) )""",
158     fr_FR   = "Affiche graphiquement avec Gnuplot la série des valeurs de la variable",
159     en_EN   = "Graphically plot with Gnuplot the value series of the variable",
160     order   = "next",
161     )
162 ObserverTemplates.store(
163     name    = "ValuePrinterAndGnuPlotter",
164     content = """print(str(info)+' '+str(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' ) )""",
165     fr_FR   = "Imprime sur la sortie standard et, en même temps, affiche graphiquement avec Gnuplot la valeur courante de la variable",
166     en_EN   = "Print on standard output and, in the same time, graphically plot with Gnuplot the current value of the variable",
167     order   = "next",
168     )
169 ObserverTemplates.store(
170     name    = "ValueSeriePrinterAndGnuPlotter",
171     content = """print(str(info)+' '+str(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' ) )""",
172     fr_FR   = "Imprime sur la sortie standard et, en même temps, affiche graphiquement avec Gnuplot la série des valeurs de la variable",
173     en_EN   = "Print on standard output and, in the same time, graphically plot with Gnuplot the value series of the variable",
174     order   = "next",
175     )
176 ObserverTemplates.store(
177     name    = "ValuePrinterSaverAndGnuPlotter",
178     content = """print(str(info)+' '+str(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' ) )""",
179     fr_FR   = "Imprime sur la sortie standard et, en même temps, enregistre dans un fichier du répertoire '/tmp' et affiche graphiquement la valeur courante de la variable",
180     en_EN   = "Print on standard output and, in the same, time save in a file of the '/tmp' directory and graphically plot the current value of the variable",
181     order   = "next",
182     )
183 ObserverTemplates.store(
184     name    = "ValueSeriePrinterSaverAndGnuPlotter",
185     content = """print(str(info)+' '+str(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' ) )""",
186     fr_FR   = "Imprime sur la sortie standard et, en même temps, enregistre dans un fichier du répertoire '/tmp' et affiche graphiquement la série des valeurs de la variable",
187     en_EN   = "Print on standard output and, in the same, time save in a file of the '/tmp' directory and graphically plot the value series of the variable",
188     order   = "next",
189     )
190 ObserverTemplates.store(
191     name    = "ValueMean",
192     content = """import numpy\nprint(str(info)+' '+str(numpy.nanmean(var[-1])))""",
193     fr_FR   = "Imprime sur la sortie standard la moyenne de la valeur courante de la variable",
194     en_EN   = "Print on standard output the mean of the current value of the variable",
195     order   = "next",
196     )
197 ObserverTemplates.store(
198     name    = "ValueStandardError",
199     content = """import numpy\nprint(str(info)+' '+str(numpy.nanstd(var[-1])))""",
200     fr_FR   = "Imprime sur la sortie standard l'écart-type de la valeur courante de la variable",
201     en_EN   = "Print on standard output the standard error of the current value of the variable",
202     order   = "next",
203     )
204 ObserverTemplates.store(
205     name    = "ValueVariance",
206     content = """import numpy\nprint(str(info)+' '+str(numpy.nanvar(var[-1])))""",
207     fr_FR   = "Imprime sur la sortie standard la variance de la valeur courante de la variable",
208     en_EN   = "Print on standard output the variance of the current value of the variable",
209     order   = "next",
210     )
211 ObserverTemplates.store(
212     name    = "ValueL2Norm",
213     content = """import numpy\nv = numpy.ravel( var[-1] )\nprint(str(info)+' '+str(float( numpy.linalg.norm(v) )))""",
214     fr_FR   = "Imprime sur la sortie standard la norme L2 de la valeur courante de la variable",
215     en_EN   = "Print on standard output the L2 norm of the current value of the variable",
216     order   = "next",
217     )
218 ObserverTemplates.store(
219     name    = "ValueRMS",
220     content = """import numpy\nv = numpy.ravel( var[-1] )\nprint(str(info)+' '+str(float( numpy.sqrt((1./v.size)*numpy.dot(v,v)) )))""",
221     fr_FR   = "Imprime sur la sortie standard la racine de la moyenne des carrés (RMS), ou moyenne quadratique, de la valeur courante de la variable",
222     en_EN   = "Print on standard output the root mean square (RMS), or quadratic mean, of the current value of the variable",
223     order   = "next",
224     )
225
226 # ==============================================================================
227 UserPostAnalysisTemplates = TemplateStorage()
228
229 UserPostAnalysisTemplates.store(
230     name    = "AnalysisPrinter",
231     content = """print('# Post-analysis')\nimport numpy\nxa=ADD.get('Analysis')[-1]\nprint('Analysis',xa)""",
232     fr_FR   = "Imprime sur la sortie standard la valeur optimale",
233     en_EN   = "Print on standard output the optimal value",
234     order   = "next",
235     )
236 UserPostAnalysisTemplates.store(
237     name    = "AnalysisSaver",
238     content = """print('# Post-analysis')\nimport numpy\nxa=ADD.get('Analysis')[-1]\nf='/tmp/analysis.txt'\nprint('Analysis saved in \"%s\"'%f)\nnumpy.savetxt(f,xa)""",
239     fr_FR   = "Enregistre la valeur optimale dans un fichier du répertoire '/tmp' nommé 'analysis.txt'",
240     en_EN   = "Save the optimal value in a file of the '/tmp' directory named 'analysis.txt'",
241     order   = "next",
242     )
243 UserPostAnalysisTemplates.store(
244     name    = "AnalysisPrinterAndSaver",
245     content = """print('# Post-analysis')\nimport numpy\nxa=ADD.get('Analysis')[-1]\nprint('Analysis',xa)\nf='/tmp/analysis.txt'\nprint('Analysis saved in \"%s\"'%f)\nnumpy.savetxt(f,xa)""",
246     fr_FR   = "Imprime sur la sortie standard et, en même temps enregistre dans un fichier du répertoire '/tmp', la valeur optimale",
247     en_EN   = "Print on standard output and, in the same time save in a file of the '/tmp' directory, the optimal value",
248     order   = "next",
249     )
250 UserPostAnalysisTemplates.store(
251     name    = "AnalysisSeriePrinter",
252     content = """print('# Post-analysis')\nimport numpy\nxa=ADD.get('Analysis')\nprint('Analysis',xa)""",
253     fr_FR   = "Imprime sur la sortie standard la série des valeurs optimales",
254     en_EN   = "Print on standard output the optimal value series",
255     order   = "next",
256     )
257 UserPostAnalysisTemplates.store(
258     name    = "AnalysisSerieSaver",
259     content = """print('# Post-analysis')\nimport numpy\nxa=ADD.get('Analysis')\nf='/tmp/analysis.txt'\nprint('Analysis saved in \"%s\"'%f)\nnumpy.savetxt(f,xa)""",
260     fr_FR   = "Enregistre la série des valeurs optimales dans un fichier du répertoire '/tmp' nommé 'analysis.txt'",
261     en_EN   = "Save the optimal value series in a file of the '/tmp' directory named 'analysis.txt'",
262     order   = "next",
263     )
264 UserPostAnalysisTemplates.store(
265     name    = "AnalysisSeriePrinterAndSaver",
266     content = """print('# Post-analysis')\nimport numpy\nxa=ADD.get('Analysis')\nprint('Analysis',xa)\nf='/tmp/analysis.txt'\nprint('Analysis saved in \"%s\"'%f)\nnumpy.savetxt(f,xa)""",
267     fr_FR   = "Imprime sur la sortie standard et, en même temps enregistre dans un fichier du répertoire '/tmp', la série des valeurs optimales",
268     en_EN   = "Print on standard output and, in the same time save in a file of the '/tmp' directory, the optimal value series",
269     order   = "next",
270     )
271
272 # ==============================================================================
273 if __name__ == "__main__":
274     print('\n AUTODIAGNOSTIC\n')