]> SALOME platform Git repositories - modules/adao.git/blob - bin/AdaoCatalogGenerator.py
Salome HOME
Fix configure generation with recent versions of libtool
[modules/adao.git] / bin / AdaoCatalogGenerator.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2015 EDF R&D
4 #
5 # This file is part of SALOME ADAO module
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24
25 import logging
26 import traceback
27 import sys
28 import string
29 import StringIO
30
31 import module_version
32
33 logging.basicConfig(level=logging.WARNING)
34
35 #----------- Templates Part ---------------#
36 begin_catalog_file = """#-*-coding:iso-8859-1-*-
37 #
38 # Copyright (C) 2008-2015 EDF R&D
39 #
40 # This file is part of SALOME ADAO module
41 #
42 # This library is free software; you can redistribute it and/or
43 # modify it under the terms of the GNU Lesser General Public
44 # License as published by the Free Software Foundation; either
45 # version 2.1 of the License.
46 #
47 # This library is distributed in the hope that it will be useful,
48 # but WITHOUT ANY WARRANTY; without even the implied warranty of
49 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
50 # Lesser General Public License for more details.
51 #
52 # You should have received a copy of the GNU Lesser General Public
53 # License along with this library; if not, write to the Free Software
54 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
55 #
56 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
57 #
58 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
59
60 # --------------------------------------------------------
61 # Generated by AdaoCatalogGenerator on ${date}
62 # --------------------------------------------------------
63
64 import os, re
65 import Accas
66 from Accas import *
67
68 JdC = JDC_CATA (
69     code = '%s',
70     execmodul = None,
71     regles = ( AU_MOINS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY'), AU_PLUS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY')),
72     )
73 VERSION_CATALOGUE='%s'
74
75 def NoCheckInNS(filename):
76     return 1
77 NoCheckInNS.info = ""
78 def DirectOperatorInNS(filename):
79     if os.path.exists(filename):
80         fc = open(filename, 'r').readlines()
81         cr = re.compile("^def[\s]*DirectOperator[\s]*\(")
82         for ln in fc:
83             if cr.match(ln): return 1
84         cr = re.compile("^DirectOperator[\s]*=")
85         for ln in fc:
86             if cr.match(ln): return 1
87     return 0
88 DirectOperatorInNS.info = u"The Python file has to contain explicitly a \\"DirectOperator\\" function definition with only one vector as argument."
89 def TangentOperatorInNS(filename):
90     if os.path.exists(filename):
91         fc = open(filename, 'r').readlines()
92         cr = re.compile("^def[\s]*TangentOperator[\s]*\(")
93         for ln in fc:
94             if cr.match(ln): return 1
95         cr = re.compile("^TangentOperator[\s]*=")
96         for ln in fc:
97             if cr.match(ln): return 1
98     return 0
99 TangentOperatorInNS.info = u"The Python file has to contain explicitly a \\"TangentOperator\\" function definition with only one pair of vectors as argument."
100 def AdjointOperatorInNS(filename):
101     if os.path.exists(filename):
102         fc = open(filename, 'r').readlines()
103         cr = re.compile("^def[\s]*AdjointOperator[\s]*\(")
104         for ln in fc:
105             if cr.match(ln): return 1
106         cr = re.compile("^AdjointOperator[\s]*=")
107         for ln in fc:
108             if cr.match(ln): return 1
109     return 0
110 AdjointOperatorInNS.info = u"The Python file has to contain explicitly an \\"AdjointOperator\\" function definition with only one pair of vectors as argument."
111 """%(module_version.name,module_version.version)
112
113 # Important : validators=[...] pour que les conditions soient traitées simultanément, en "ET", et pas en "OU" (choisi dans le cas du tuple à la place de la liste)
114 # validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)]
115 data_method = """
116 def F_${data_name}(statut, fv=NoCheckInNS) : return FACT(
117     statut = statut,
118     FROM = SIMP(statut = "o", typ = "TXM", into=(${data_into}), defaut=${data_default}),
119     SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
120         SCRIPT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant si nécessaire la définition d'une variable interne de même nom que le concept parent", ang="Waiting for a script file name, with or without the full path to find it, containing if necessary the definition of an internal variable of the same name as the parent concept"),
121         ),
122     STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
123         STRING = SIMP(statut = "o", typ = "TXM",${ms_default} fr="En attente d'une chaine de caractères entre guillements. Pour construire un vecteur ou une matrice, ce doit être une suite de nombres, utilisant un espace ou une virgule pour séparer deux éléments et un point-virgule pour séparer deux lignes", ang="Waiting for a string in quotes. To build a vector or a matrix, it has to be a float serie, using a space or comma to separate two elements in a line, a semi-colon to separate rows"),
124         ),
125     SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
126         SCRIPTWITHFUNCTIONS_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(DirectOperatorInNS), FunctionVal(TangentOperatorInNS), FunctionVal(AdjointOperatorInNS)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant en variables internes trois fonctions de calcul nommées DirectOperator, TangentOperator et AdjointOperator", ang="Waiting for a script file name, with or without the full path to find it, containing as internal variables three computation functions named DirectOperator, TangentOperator and AdjointOperator"),
127         ),
128     SCRIPTWITHONEFUNCTION_DATA = BLOC ( condition = " FROM in ( 'ScriptWithOneFunction', ) ",
129         SCRIPTWITHONEFUNCTION_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(DirectOperatorInNS)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant en variable interne une seule fonction de calcul nommée DirectOperator", ang="Waiting for a script file name, with or without the full path to find it, containing as internal variable only one function named DirectOperator"),
130         DifferentialIncrement = SIMP(statut="o", typ = "R", val_min=0, val_max=1, defaut=0.01, fr="Incrément de la perturbation dX pour calculer la dérivée, construite en multipliant X par l'incrément en évitant les valeurs nulles", ang="Increment of dX perturbation to calculate the derivative, build multiplying X by the increment avoiding null values"),
131         CenteredFiniteDifference = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0, fr="Formulation centrée (1) ou décentrée (0) pour la méthode des différences finies", ang="Centered (1) or uncentered (0) formulation for the finite differences method"),
132         EnableMultiProcessing = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0, fr="Calculs élémentaires effectués en séquentiel (0) ou en parallèle (1) dans la méthode des différences finies", ang="Elementary calculations done sequentially (0) or in parallel (1) in the finite differences method"),
133         NumberOfProcesses = SIMP(statut="f", typ = "I", val_min=0, defaut=0, fr="Nombre de processus parallèles, 0 pour un contrôle automatique", ang="Number of parallel processes, 0 for automatic control"),
134         ),
135     SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
136         SCRIPTWITHSWITCH_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant un switch pour les calculs direct, tangent et adjoint", ang="Waiting for a script file name, with or without the full path to find it, containing a switch for direct, tangent and adjoint computations"),
137         ),
138     TEMPLATE_DATA =  BLOC (condition = " FROM in ( 'Template', ) ",
139         Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "AnalysisPrinter", into=("AnalysisPrinter", "AnalysisSaver", "AnalysisPrinterAndSaver")),
140         AnalysisPrinter = BLOC (condition = " Template == 'AnalysisPrinter' ",
141             ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy\\nxa=numpy.ravel(ADD.get('Analysis')[-1])\\nprint 'Analysis:',xa" ),
142             ),
143         AnalysisSaver = BLOC (condition = " Template == 'AnalysisSaver' ",
144             ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy\\nxa=numpy.ravel(ADD.get('Analysis')[-1])\\nf='/tmp/analysis.txt'\\nprint 'Analysis saved in \\"%s\\"'%f\\nnumpy.savetxt(f,xa)" ),
145             ),
146         AnalysisPrinterAndSaver = BLOC (condition = " Template == 'AnalysisPrinterAndSaver' ",
147             ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy\\nxa=numpy.ravel(ADD.get('Analysis')[-1])\\nprint 'Analysis:',xa\\nf='/tmp/analysis.txt'\\nprint 'Analysis saved in \\"%s\\"'%f\\nnumpy.savetxt(f,xa)" ),
148             ),
149         ),
150     )
151 """
152
153 init_method = """
154 def F_InitChoice() : return  ("Background",
155                               "BackgroundError",
156                               "Observation",
157                               "ObservationError",
158                               "ObservationOperator",
159                               "EvolutionModel",
160                               "EvolutionError",
161                               "AlgorithmParameters",
162                               "UserPostAnalysis",
163                              )
164
165 def F_Init(statut) : return FACT(statut = statut,
166     INIT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')]),
167     TARGET_LIST = SIMP(statut = "o", typ = "TXM", min=1, max="**", into=F_InitChoice(),  validators=(VerifExiste(2))),
168     )
169 """
170
171 assim_data_method = """
172 def ${assim_name}InNS(filename):
173     if os.path.exists(filename):
174         fc = open(filename, 'r').readlines()
175         cr = re.compile("^${assim_name}[\s]*=")
176         for ln in fc:
177             if cr.match(ln): return 1
178     return 0
179 ${assim_name}InNS.info = u"The Python file has to contain explicitly a \\"${assim_name}\\" variable."
180 def F_${assim_name}(statut, fv=NoCheckInNS) : return FACT(
181     statut=statut,
182 ${storage}
183     INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=(${choices}), defaut=${default_choice}),${decl_choices}
184     )
185 """
186
187 assim_data_choice = """
188     ${choice_name} = BLOC ( condition = " INPUT_TYPE in ( '${choice_name}', ) ",
189         data = F_${choice_name}("o", fv),
190         ),"""
191
192 observers_choice = """
193     ${var_name} = BLOC (condition=" '${var_name}' in set(SELECTION) ",
194         ${var_name}_data = FACT(statut = "o",
195             Scheduler    = SIMP(statut = "f", typ = "TXM"),
196             Info         = SIMP(statut = "o", typ = "TXM", defaut = "${var_name}"),
197             NodeType     = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "Template", into=("String", "Script", "Template")),
198             PythonScript = BLOC (condition = " NodeType == 'String' ",
199                 Value = SIMP(statut = "o", typ = "TXM")
200                 ),
201             UserFile = BLOC (condition = " NodeType == 'Script' ",
202                 Value = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')])
203                 ),
204             ObserverTemplate = F_ObserverTemplate(),
205             ),
206         ),"""
207
208 observers_method = """
209 def F_ObserverTemplate() : return BLOC(condition = " NodeType == 'Template' ",
210                 Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "ValuePrinter", into=("ValuePrinter", "ValueSeriePrinter", "ValueSaver", "ValueSerieSaver", "ValuePrinterAndSaver", "ValueSeriePrinterAndSaver", "ValueGnuPlotter", "ValueSerieGnuPlotter", "ValuePrinterAndGnuPlotter", "ValueSeriePrinterAndGnuPlotter", "ValuePrinterSaverAndGnuPlotter", "ValueSeriePrinterSaverAndGnuPlotter")),
211                 ValuePrinter = BLOC (condition = " Template == 'ValuePrinter' ",
212                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "print info, var[-1]" ),
213                     ),
214                 ValueSeriePrinter = BLOC (condition = " Template == 'ValueSeriePrinter' ",
215                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "print info, var[:] " ),
216                     ),
217                 ValueSaver = BLOC (condition = " Template == 'ValueSaver' ",
218                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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)" ),
219                     ),
220                 ValueSerieSaver = BLOC (condition = " Template == 'ValueSerieSaver' ",
221                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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)" ),
222                     ),
223                 ValuePrinterAndSaver = BLOC (condition = " Template == 'ValuePrinterAndSaver' ",
224                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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)" ),
225                     ),
226                 ValueSeriePrinterAndSaver = BLOC (condition = " Template == 'ValueSeriePrinterAndSaver' ",
227                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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)" ),
228                     ),
229                 ValueGnuPlotter = BLOC (condition = " Template == 'ValueGnuPlotter' ",
230                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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' ) )" ),
231                     ),
232                 ValueSerieGnuPlotter = BLOC (condition = " Template == 'ValueSerieGnuPlotter' ",
233                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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' ) )" ),
234                     ),
235                 ValuePrinterAndGnuPlotter = BLOC (condition = " Template == 'ValuePrinterAndGnuPlotter' ",
236                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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' ) )" ),
237                     ),
238                 ValueSeriePrinterAndGnuPlotter = BLOC (condition = " Template == 'ValueSeriePrinterAndGnuPlotter' ",
239                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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' ) )" ),
240                     ),
241                 ValuePrinterSaverAndGnuPlotter = BLOC (condition = " Template == 'ValuePrinterSaverAndGnuPlotter' ",
242                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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' ) )" ),
243                     ),
244                 ValueSeriePrinterSaverAndGnuPlotter = BLOC (condition = " Template == 'ValueSeriePrinterSaverAndGnuPlotter' ",
245                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "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' ) )" ),
246                     ),
247                 )
248
249 def F_Observers(statut) : return FACT(
250     statut=statut,
251     SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", validators=NoRepeat(), into=(${choices})),${decl_choices}
252     )
253 """
254
255 algo_choices = """
256 def AlgorithmParametersInNS(filename):
257     if os.path.exists(filename):
258         fc = open(filename, 'r').readlines()
259         cr = re.compile("^AlgorithmParameters[\s]*=")
260         for ln in fc:
261             if cr.match(ln): return 1
262     return 0
263 AlgorithmParametersInNS.info = u"The Python file has to contain explicitly an \\"AlgorithmParameters\\" variable."
264 def F_AlgorithmParameters(statut, algos_names, fv=NoCheckInNS) : return FACT(
265     statut = statut,
266     Algorithm = SIMP(statut="o", typ = "TXM", into = algos_names ),
267     Parameters = SIMP(statut="f", typ = "TXM", into=("Defaults", "Dict") ),
268     Dict = BLOC ( condition = " Parameters == 'Dict' ",
269         statut="f",
270         data = F_Dict("o", fv),
271         ),${all_algo_defaults}
272     )
273 """
274 one_algo_choices = """
275     Parameters${algo_name} = BLOC (condition = " (Parameters == 'Defaults') and (Algorithm == '${algo_name}') ",
276         statut="f",
277 ${algo_parameters}        ),"""
278
279 assim_study = """
280 def F_variables(statut) : return FACT(
281     statut=statut,
282     regles = ( MEME_NOMBRE ('NAMES', 'SIZES')),
283     NAMES = SIMP(statut="o", typ="TXM", max="**", validators=NoRepeat()),
284     SIZES = SIMP(statut="o", typ="I", val_min=1, max="**")
285     )
286 def ChDir(dirname):
287     os.chdir(os.path.abspath(dirname))
288     return 1
289 ChDir.info = u"This has to be a regular directory path."
290
291 ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
292     op=None,
293     repetable           = "n",
294     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
295     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
296     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
297     AlgorithmParameters = F_AlgorithmParameters("o",(${algos_names}), AlgorithmParametersInNS),
298     Background          = F_Background("o", BackgroundInNS),
299     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
300     Observation         = F_Observation("o", ObservationInNS),
301     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
302     ObservationOperator = F_ObservationOperator("o"),
303     EvolutionModel      = F_EvolutionModel("f"),
304     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
305     ControlInput        = F_ControlInput("f"),
306     UserDataInit        = F_Init("f"),
307     UserPostAnalysis    = F_UserPostAnalysis("o"),
308     InputVariables      = F_variables("f"),
309     OutputVariables     = F_variables("f"),
310     Observers           = F_Observers("f")
311     )
312
313 CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
314     op=None,
315     repetable           = "n",
316     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Checking Case"),
317     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
318     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
319     AlgorithmParameters = F_AlgorithmParameters("o", (${check_names}), AlgorithmParametersInNS),
320     CheckingPoint       = F_CheckingPoint("o", CheckingPointInNS),
321     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
322     Observation         = F_Observation("f", ObservationInNS),
323     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
324     ObservationOperator = F_ObservationOperator("o"),
325     UserDataInit        = F_Init("f"),
326     Observers           = F_Observers("f")
327     )
328 """
329
330 begin_catalog_file = string.Template(begin_catalog_file)
331 data_method = string.Template(data_method)
332 assim_data_method = string.Template(assim_data_method)
333 assim_data_choice = string.Template(assim_data_choice)
334 assim_study = string.Template(assim_study)
335 observers_method = string.Template(observers_method)
336 observers_choice = string.Template(observers_choice)
337 algo_choices = string.Template(algo_choices)
338 one_algo_choices = string.Template(one_algo_choices)
339
340 #----------- End of Templates Part ---------------#
341
342
343
344 #----------- Begin generation script -----------#
345 print "-- Starting AdaoCalatogGenerator.py --"
346
347 try:
348   import daEficas
349   import daYacsSchemaCreator
350   import daCore.AssimilationStudy
351   import daYacsSchemaCreator.infos_daComposant as infos
352 except:
353   logging.fatal("Import of ADAO python modules failed !" +
354                 "\n add ADAO python installation directory in your PYTHONPATH")
355   traceback.print_exc()
356   sys.exit(1)
357
358 def check_args(args):
359   logging.debug("Arguments are :" + str(args))
360   if len(args) != 2:
361     logging.fatal("Bad number of arguments: you have to provide two arguments (%d given)" % (len(args)))
362     sys.exit(1)
363
364 # Parse arguments
365 from optparse import OptionParser
366 usage = "usage: %prog [options] catalog_path catalog_name"
367 version="%prog 0.1"
368 my_parser = OptionParser(usage=usage, version=version)
369 (options, args) = my_parser.parse_args()
370 check_args(args)
371
372 catalog_path =  args[0]
373 catalog_name =  args[1]
374
375 # Generates into a string
376 mem_file = StringIO.StringIO()
377
378 # Start file
379 from time import strftime
380 mem_file.write(begin_catalog_file.substitute(date=strftime("%Y-%m-%d %H:%M:%S")))
381
382 # Step initial: on obtient la liste des algos
383 algos_names = ""
384 check_names = ""
385 decl_algos  = ""
386 assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
387 algos_list = assim_study_object.get_available_algorithms()
388 del assim_study_object
389 for algo_name in algos_list:
390   if algo_name in infos.AssimAlgos:
391     logging.debug("An assimilation algorithm is found: " + algo_name)
392     algos_names += "\"" + algo_name + "\", "
393   elif algo_name in infos.CheckAlgos:
394     logging.debug("A checking algorithm is found: " + algo_name)
395     check_names += "\"" + algo_name + "\", "
396   else:
397     logging.debug("This algorithm is not considered: " + algo_name)
398
399 # Step 1: A partir des infos, on cree les fonctions qui vont permettre
400 # d'entrer les donnees utilisateur
401 for data_input_name in infos.DataTypeDict.keys():
402   logging.debug('A data input Type is found: ' + data_input_name)
403   data_name = data_input_name
404   data_into = ""
405   data_default = ""
406   ms_default = ""
407
408   # On recupere les differentes facon d'entrer les donnees
409   for basic_type in infos.DataTypeDict[data_input_name]:
410     data_into += "\"" + basic_type + "\", "
411
412   # On choisit le default
413   data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
414   if infos.DataSValueDefaultDict.has_key(data_input_name):
415     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[data_input_name] + "\","
416
417   mem_file.write(data_method.substitute(data_name    = data_name,
418                                         data_into    = data_into,
419                                         data_default = data_default,
420                                         ms_default   = ms_default,
421                                         algos_names  = algos_names+check_names))
422
423 # Step 2: On cree les fonctions qui permettent de rentrer les donnees des algorithmes
424 for assim_data_input_name in infos.AssimDataDict.keys():
425   logging.debug("An input function data input is found: " + assim_data_input_name)
426   # assim_name = assim_data_input_name
427   storage = ""
428   choices = ""
429   default_choice = ""
430   decl_choices = ""
431   decl_opts = ""
432   if infos.AssimDataDefaultDict[assim_data_input_name] in infos.StoredAssimData:
433     storage = "    Stored = SIMP(statut=\"o\", typ = \"I\", into=(0, 1), defaut=0, fr=\"Choix de stockage interne ou non du concept parent\", ang=\"Choice of the storage or not of the parent concept\"),"
434   for choice in infos.AssimDataDict[assim_data_input_name]:
435     choices += "\"" + choice + "\", "
436     decl_choices += assim_data_choice.substitute(choice_name = choice)
437     if choice in infos.StoredAssimData:
438       storage = "    Stored = SIMP(statut=\"o\", typ = \"I\", into=(0, 1), defaut=0, fr=\"Choix de stockage interne ou non du concept parent\", ang=\"Choice of the storage or not of the parent concept\"),"
439   default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
440
441   mem_file.write(assim_data_method.substitute(assim_name = assim_data_input_name,
442                                               storage        = storage,
443                                               choices        = choices,
444                                               decl_choices   = decl_choices,
445                                               default_choice = default_choice))
446
447 # Step 3: On ajoute les fonctions representant les options possibles
448 for opt_name in infos.OptDict.keys():
449   logging.debug("An optional node is found: " + opt_name)
450   data_name = opt_name
451   data_into = ""
452   data_default = ""
453   ms_default = ""
454
455   for choice in infos.OptDict[opt_name]:
456     data_into += "\"" + choice + "\", "
457
458   # On choisit le default
459   data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
460   if infos.DataSValueDefaultDict.has_key(opt_name):
461     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[opt_name] + "\","
462
463   mem_file.write(data_method.substitute(data_name    = data_name,
464                                         data_into    = data_into,
465                                         data_default = data_default,
466                                         ms_default   = ms_default,
467                                         algos_names  = algos_names+check_names))
468
469 # Step 4: On ajoute la methode optionnelle init
470 # TODO uniformiser avec le step 3
471 mem_file.write(init_method)
472
473 # Step 5: Add observers
474 decl_choices = ""
475 for obs_var in infos.ObserversList:
476   decl_choices += observers_choice.substitute(var_name=obs_var)
477 mem_file.write(observers_method.substitute(choices = infos.ObserversList,
478                                            decl_choices = decl_choices))
479
480 # Step 5: Add algorithmic choices
481
482 all_names = eval((algos_names+check_names))
483 all_algo_defaults = ""
484 for algo in all_names:
485     assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
486     assim_study_object.setAlgorithm(choice=algo)
487     par_dict = assim_study_object.getAlgorithmParameters(False)
488     par_keys = par_dict.keys()
489     par_keys.sort()
490     algo_parameters = ""
491     for pn in par_keys:
492         if pn in ("StoreInternalVariables", "PlotAndSave", "ResultFile", "ResultTitle", "ResultLabel"): continue # Cles a supprimer
493         pt = par_dict[pn]["typecast"]
494         pd = par_dict[pn]["default"]
495         pm = par_dict[pn]["message"]
496         if par_dict[pn].has_key("minval") and par_dict[pn]["minval"] is not None:
497             vi = ", val_min=%s"%par_dict[pn]["minval"]
498         else:
499             vi = ""
500         if par_dict[pn].has_key("minval") and par_dict[pn]["maxval"] is not None:
501             vs = ", val_max=%s"%par_dict[pn]["maxval"]
502         else:
503             vs = ""
504         if   pt is int:
505             algo_parameters += """        %s = SIMP(statut="f", typ="I"%s%s, min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,vi,vs,int(pd),pm)
506         elif pt is float:
507             algo_parameters += """        %s = SIMP(statut="f", typ="R"%s%s, min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,vi,vs,float(pd),pm)
508         elif pt is bool:
509             algo_parameters += """        %s = SIMP(statut="f", typ="I", min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
510         elif pt is str and par_dict[pn].has_key("listval"):
511             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", min=1, max=1, defaut="%s", into=%s, fr="%s"),\n"""%(pn,str(pd),par_dict[pn]["listval"],pm)
512         elif pt is tuple and par_dict[pn].has_key("listval"):
513             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", max="**", into=%s, fr="%s"),\n"""%(pn,par_dict[pn]["listval"],pm)
514         else:
515             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", fr="%s"),\n"""%(pn,pm)
516     del assim_study_object
517     if algo_parameters != "":
518         all_algo_defaults += one_algo_choices.substitute(
519             algo_name=algo,
520             algo_parameters=algo_parameters,
521             )
522
523 mem_file.write(algo_choices.substitute(all_algo_defaults=all_algo_defaults))
524
525 # Final step: Add algorithm and assim_study
526 mem_file.write(assim_study.substitute(algos_names=algos_names,
527                                       check_names=check_names,
528                                       decl_algos=decl_algos))
529 # Write file
530 final_file = open(catalog_path + "/" + catalog_name, "wr")
531 final_file.write(mem_file.getvalue())
532 mem_file.close()
533 final_file.close()
534