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