]> SALOME platform Git repositories - modules/adao.git/blob - bin/AdaoCatalogGenerator.py
Salome HOME
55a322c65604086be1d630c7e34e0a42b4a926de
[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 Accas
65 from Accas import *
66
67 JdC = JDC_CATA (
68     code = '%s',
69     execmodul = None,
70     regles = ( AU_MOINS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY'), AU_PLUS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY')),
71     )
72 VERSION_CATALOGUE='%s'
73 """%(module_version.name,module_version.version)
74
75 data_method = """
76 def F_${data_name}(statut) : return FACT(
77     statut = statut,
78     FROM = SIMP(statut = "o", typ = "TXM", into=(${data_into}), defaut=${data_default}),
79     SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
80         SCRIPT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()), 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"),
81         ),
82     STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
83         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"),
84         ),
85     SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
86         SCRIPTWITHFUNCTIONS_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()), 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"),
87         ),
88     SCRIPTWITHONEFUNCTION_DATA = BLOC ( condition = " FROM in ( 'ScriptWithOneFunction', ) ",
89         SCRIPTWITHONEFUNCTION_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()), 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"),
90         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"),
91         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"),
92         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"),
93         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"),
94         ),
95     SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
96         SCRIPTWITHSWITCH_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()), 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"),
97         ),
98     TEMPLATE_DATA =  BLOC (condition = " FROM in ( 'Template', ) ",
99         Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "AnalysisPrinter", into=("AnalysisPrinter", "AnalysisSaver", "AnalysisPrinterAndSaver")),
100         AnalysisPrinter = BLOC (condition = " Template == 'AnalysisPrinter' ",
101             ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy\\nxa=numpy.ravel(ADD.get('Analysis')[-1])\\nprint 'Analysis:',xa" ),
102             ),
103         AnalysisSaver = BLOC (condition = " Template == 'AnalysisSaver' ",
104             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)" ),
105             ),
106         AnalysisPrinterAndSaver = BLOC (condition = " Template == 'AnalysisPrinterAndSaver' ",
107             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)" ),
108             ),
109         ),
110     )
111 """
112
113 init_method = """
114 def F_InitChoice() : return  ("Background",
115                               "BackgroundError",
116                               "Observation",
117                               "ObservationError",
118                               "ObservationOperator",
119                               "EvolutionModel",
120                               "EvolutionError",
121                               "AlgorithmParameters",
122                               "UserPostAnalysis",
123                              )
124
125 def F_Init(statut) : return FACT(statut = statut,
126     INIT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr())),
127     TARGET_LIST = SIMP(statut = "o", typ = "TXM", min=1, max="**", into=F_InitChoice(),  validators=(VerifExiste(2))),
128     )
129 """
130
131 assim_data_method = """
132 def F_${assim_name}(statut) : return FACT(
133     statut=statut,
134 ${storage}
135     INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=(${choices}), defaut=${default_choice}),${decl_choices}
136     )
137 """
138
139 assim_data_choice = """
140     ${choice_name} = BLOC ( condition = " INPUT_TYPE in ( '${choice_name}', ) ",
141         data = F_${choice_name}("o"),
142         ),"""
143
144 observers_choice = """
145     ${var_name} = BLOC (condition=" '${var_name}' in set(SELECTION) ",
146         ${var_name}_data = FACT(statut = "o",
147             Scheduler    = SIMP(statut = "f", typ = "TXM"),
148             Info         = SIMP(statut = "o", typ = "TXM", defaut = "${var_name}"),
149             NodeType     = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "Template", into=("String", "Script", "Template")),
150             PythonScript = BLOC (condition = " NodeType == 'String' ",
151                 Value = SIMP(statut = "o", typ = "TXM")
152                 ),
153             UserFile = BLOC (condition = " NodeType == 'Script' ",
154                 Value = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()))
155                 ),
156             ObserverTemplate = F_ObserverTemplate(),
157             ),
158         ),"""
159
160 observers_method = """
161 def F_ObserverTemplate() : return BLOC(condition = " NodeType == 'Template' ",
162                 Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "ValuePrinter", into=("ValuePrinter", "ValueSeriePrinter", "ValueSaver", "ValueSerieSaver", "ValuePrinterAndSaver", "ValueSeriePrinterAndSaver", "ValueGnuPlotter", "ValueSerieGnuPlotter")),
163                 ValuePrinter = BLOC (condition = " Template == 'ValuePrinter' ",
164                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "print info,var[-1]" ),
165                     ),
166                 ValueSeriePrinter = BLOC (condition = " Template == 'ValueSeriePrinter' ",
167                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "print info,var[:]" ),
168                     ),
169                 ValueSaver = BLOC (condition = " Template == 'ValueSaver' ",
170                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy,re\\nv=numpy.array((var[-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)" ),
171                     ),
172                 ValueSerieSaver = BLOC (condition = " Template == 'ValueSerieSaver' ",
173                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy,re\\nv=numpy.array((var[:])) \\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)" ),
174                     ),
175                 ValuePrinterAndSaver = BLOC (condition = " Template == 'ValuePrinterAndSaver' ",
176                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy,re\\nv=numpy.array((var[-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)" ),
177                     ),
178                 ValueSeriePrinterAndSaver = BLOC (condition = " Template == 'ValueSeriePrinterAndSaver' ",
179                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy,re\\nv=numpy.array((var[:])) \\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)" ),
180                     ),
181                 ValueGnuPlotter = BLOC (condition = " Template == 'ValueGnuPlotter' ",
182                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import 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( var[-1], with_='lines lw 2' ) )" ),
183                     ),
184                 ValueSerieGnuPlotter = BLOC (condition = " Template == 'ValueSerieGnuPlotter' ",
185                     ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import 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( var[:], with_='lines lw 2' ) )" ),
186                     ),
187                 )
188
189 def F_Observers(statut) : return FACT(
190     statut=statut,
191     SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", validators=NoRepeat(), into=(${choices})),${decl_choices}
192     )
193 """
194
195 algo_choices = """
196 def F_AlgorithmParameters(statut,algos_names) : return FACT(
197     statut = statut,
198     Algorithm = SIMP(statut="o", typ = "TXM", into = algos_names ),
199     Parameters = SIMP(statut="f", typ = "TXM", into=("Defaults", "Dict") ),
200     Dict = BLOC ( condition = " Parameters == 'Dict' ",
201         statut="f",
202         data = F_Dict("o"),
203         ),${all_algo_defaults}
204     )
205 """
206 one_algo_choices = """
207     Parameters${algo_name} = BLOC (condition = " (Parameters == 'Defaults') and (Algorithm == '${algo_name}') ",
208         statut="f",
209 ${algo_parameters}        ),"""
210
211 assim_study = """
212
213 def F_variables(statut) : return FACT(
214     statut=statut,
215     regles = ( MEME_NOMBRE ('NAMES', 'SIZES')),
216     NAMES = SIMP(statut="o", typ="TXM", max="**", validators=NoRepeat()),
217     SIZES = SIMP(statut="o", typ="I", val_min=1, max="**")
218     )
219
220 ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
221     op=None,
222     repetable           = "n",
223     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
224     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", min=1, max=1),
225     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
226     AlgorithmParameters = F_AlgorithmParameters("o",(${algos_names})),
227     Background          = F_Background("o"),
228     BackgroundError     = F_BackgroundError("o"),
229     Observation         = F_Observation("o"),
230     ObservationError    = F_ObservationError("o"),
231     ObservationOperator = F_ObservationOperator("o"),
232     EvolutionModel      = F_EvolutionModel("f"),
233     EvolutionError      = F_EvolutionError("f"),
234     ControlInput        = F_ControlInput("f"),
235     UserDataInit        = F_Init("f"),
236     UserPostAnalysis    = F_UserPostAnalysis("o"),
237     InputVariables      = F_variables("f"),
238     OutputVariables     = F_variables("f"),
239     Observers           = F_Observers("f")
240     )
241
242 CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
243     op=None,
244     repetable           = "n",
245     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Checking Case"),
246     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", min=1, max=1),
247     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
248     AlgorithmParameters = F_AlgorithmParameters("o",(${check_names})),
249     CheckingPoint       = F_CheckingPoint("o"),
250     BackgroundError     = F_BackgroundError("f"),
251     Observation         = F_Observation("f"),
252     ObservationError    = F_ObservationError("f"),
253     ObservationOperator = F_ObservationOperator("o"),
254     UserDataInit        = F_Init("f"),
255     Observers           = F_Observers("f")
256     )
257 """
258
259 begin_catalog_file = string.Template(begin_catalog_file)
260 data_method = string.Template(data_method)
261 assim_data_method = string.Template(assim_data_method)
262 assim_data_choice = string.Template(assim_data_choice)
263 assim_study = string.Template(assim_study)
264 observers_method = string.Template(observers_method)
265 observers_choice = string.Template(observers_choice)
266 algo_choices = string.Template(algo_choices)
267 one_algo_choices = string.Template(one_algo_choices)
268
269 #----------- End of Templates Part ---------------#
270
271
272
273 #----------- Begin generation script -----------#
274 print "-- Starting AdaoCalatogGenerator.py --"
275
276 try:
277   import daEficas
278   import daYacsSchemaCreator
279   import daCore.AssimilationStudy
280   import daYacsSchemaCreator.infos_daComposant as infos
281 except:
282   logging.fatal("Import of ADAO python modules failed !" +
283                 "\n add ADAO python installation directory in your PYTHONPATH")
284   traceback.print_exc()
285   sys.exit(1)
286
287 def check_args(args):
288   logging.debug("Arguments are :" + str(args))
289   if len(args) != 2:
290     logging.fatal("Bad number of arguments: you have to provide two arguments (%d given)" % (len(args)))
291     sys.exit(1)
292
293 # Parse arguments
294 from optparse import OptionParser
295 usage = "usage: %prog [options] catalog_path catalog_name"
296 version="%prog 0.1"
297 my_parser = OptionParser(usage=usage, version=version)
298 (options, args) = my_parser.parse_args()
299 check_args(args)
300
301 catalog_path =  args[0]
302 catalog_name =  args[1]
303
304 # Generates into a string
305 mem_file = StringIO.StringIO()
306
307 # Start file
308 from time import strftime
309 mem_file.write(begin_catalog_file.substitute(date=strftime("%Y-%m-%d %H:%M:%S")))
310
311 # Step initial: on obtient la liste des algos
312 algos_names = ""
313 check_names = ""
314 decl_algos  = ""
315 assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
316 algos_list = assim_study_object.get_available_algorithms()
317 del assim_study_object
318 for algo_name in algos_list:
319   if algo_name in infos.AssimAlgos:
320     logging.debug("An assimilation algorithm is found: " + algo_name)
321     algos_names += "\"" + algo_name + "\", "
322   elif algo_name in infos.CheckAlgos:
323     logging.debug("A checking algorithm is found: " + algo_name)
324     check_names += "\"" + algo_name + "\", "
325   else:
326     logging.debug("This algorithm is not considered: " + algo_name)
327
328 # Step 1: A partir des infos, on cree les fonctions qui vont permettre
329 # d'entrer les donnees utilisateur
330 for data_input_name in infos.DataTypeDict.keys():
331   logging.debug('A data input Type is found: ' + data_input_name)
332   data_name = data_input_name
333   data_into = ""
334   data_default = ""
335   ms_default = ""
336
337   # On recupere les differentes facon d'entrer les donnees
338   for basic_type in infos.DataTypeDict[data_input_name]:
339     data_into += "\"" + basic_type + "\", "
340
341   # On choisit le default
342   data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
343   if infos.DataSValueDefaultDict.has_key(data_input_name):
344     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[data_input_name] + "\","
345
346   mem_file.write(data_method.substitute(data_name    = data_name,
347                                         data_into    = data_into,
348                                         data_default = data_default,
349                                         ms_default   = ms_default,
350                                         algos_names  = algos_names+check_names))
351
352 # Step 2: On cree les fonctions qui permettent de rentrer les donnees des algorithmes
353 for assim_data_input_name in infos.AssimDataDict.keys():
354   logging.debug("An input function data input is found: " + assim_data_input_name)
355   # assim_name = assim_data_input_name
356   storage = ""
357   choices = ""
358   default_choice = ""
359   decl_choices = ""
360   decl_opts = ""
361   if infos.AssimDataDefaultDict[assim_data_input_name] in infos.StoredAssimData:
362     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\"),"
363   for choice in infos.AssimDataDict[assim_data_input_name]:
364     choices += "\"" + choice + "\", "
365     decl_choices += assim_data_choice.substitute(choice_name = choice)
366     if choice in infos.StoredAssimData:
367       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\"),"
368   default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
369
370   mem_file.write(assim_data_method.substitute(assim_name = assim_data_input_name,
371                                               storage        = storage,
372                                               choices        = choices,
373                                               decl_choices   = decl_choices,
374                                               default_choice = default_choice))
375
376 # Step 3: On ajoute les fonctions representant les options possibles
377 for opt_name in infos.OptDict.keys():
378   logging.debug("An optional node is found: " + opt_name)
379   data_name = opt_name
380   data_into = ""
381   data_default = ""
382   ms_default = ""
383
384   for choice in infos.OptDict[opt_name]:
385     data_into += "\"" + choice + "\", "
386
387   # On choisit le default
388   data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
389   if infos.DataSValueDefaultDict.has_key(opt_name):
390     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[opt_name] + "\","
391
392   mem_file.write(data_method.substitute(data_name    = data_name,
393                                         data_into    = data_into,
394                                         data_default = data_default,
395                                         ms_default   = ms_default,
396                                         algos_names  = algos_names+check_names))
397
398 # Step 4: On ajoute la methode optionnelle init
399 # TODO uniformiser avec le step 3
400 mem_file.write(init_method)
401
402 # Step 5: Add observers
403 decl_choices = ""
404 for obs_var in infos.ObserversList:
405   decl_choices += observers_choice.substitute(var_name=obs_var)
406 mem_file.write(observers_method.substitute(choices = infos.ObserversList,
407                                            decl_choices = decl_choices))
408
409 # Step 5: Add algorithmic choices
410
411 all_names = eval((algos_names+check_names))
412 all_algo_defaults = ""
413 for algo in all_names:
414     assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
415     assim_study_object.setAlgorithm(choice=algo)
416     par_dict = assim_study_object.getAlgorithmParameters(False)
417     par_keys = par_dict.keys()
418     par_keys.sort()
419     algo_parameters = ""
420     for pn in par_keys:
421         if pn in ("StoreInternalVariables",): continue # Cles a supprimer
422         pt = par_dict[pn]["typecast"]
423         pd = par_dict[pn]["default"]
424         pm = par_dict[pn]["message"]
425         if par_dict[pn].has_key("minval") and par_dict[pn]["minval"] is not None:
426             vi = ", val_min=%s"%par_dict[pn]["minval"]
427         else:
428             vi = ""
429         if par_dict[pn].has_key("minval") and par_dict[pn]["maxval"] is not None:
430             vs = ", val_max=%s"%par_dict[pn]["maxval"]
431         else:
432             vs = ""
433         if   pt is int:
434             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)
435         elif pt is float:
436             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)
437         elif pt is bool:
438             algo_parameters += """        %s = SIMP(statut="f", typ="I", min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
439         elif pt is str and par_dict[pn].has_key("listval"):
440             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)
441         elif pt is tuple and par_dict[pn].has_key("listval"):
442             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", max="**", into=%s, fr="%s"),\n"""%(pn,par_dict[pn]["listval"],pm)
443         else:
444             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", fr="%s"),\n"""%(pn,pm)
445     del assim_study_object
446     if algo_parameters != "":
447         all_algo_defaults += one_algo_choices.substitute(
448             algo_name=algo,
449             algo_parameters=algo_parameters,
450             )
451
452 mem_file.write(algo_choices.substitute(all_algo_defaults=all_algo_defaults))
453
454 # Final step: Add algorithm and assim_study
455 mem_file.write(assim_study.substitute(algos_names=algos_names,
456                                       check_names=check_names,
457                                       decl_algos=decl_algos))
458 # Write file
459 final_file = open(catalog_path + "/" + catalog_name, "wr")
460 final_file.write(mem_file.getvalue())
461 mem_file.close()
462 final_file.close()
463