Salome HOME
Improvement of user *_STUDY
[modules/adao.git] / bin / AdaoCatalogGenerator.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2021 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 io
29 import os
30
31 import module_version
32
33 logging.basicConfig(level=logging.WARNING)
34
35 if sys.version_info.major > 2:
36     def unicode(text, encoding='utf-8'): return text
37
38 print("-- Starting AdaoCalatogGenerator.py --")
39
40 try:
41   import adao
42   import daEficas
43   import daYacsSchemaCreator
44   import daCore.Aidsm
45   import daYacsSchemaCreator.infos_daComposant as infos
46 except:
47   logging.fatal("Import of ADAO python modules failed !" +
48                 "\n add ADAO python installation directory in your PYTHONPATH")
49   traceback.print_exc()
50   sys.exit(1)
51
52 #===============================================================================
53
54 #----------- Templates Part ---------------#
55
56 begin_catalog_file = """# -*- coding: utf-8 -*-
57 #
58 # Copyright (C) 2008-2021 EDF R&D
59 #
60 # This file is part of SALOME ADAO module
61 #
62 # This library is free software; you can redistribute it and/or
63 # modify it under the terms of the GNU Lesser General Public
64 # License as published by the Free Software Foundation; either
65 # version 2.1 of the License.
66 #
67 # This library is distributed in the hope that it will be useful,
68 # but WITHOUT ANY WARRANTY; without even the implied warranty of
69 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
70 # Lesser General Public License for more details.
71 #
72 # You should have received a copy of the GNU Lesser General Public
73 # License along with this library; if not, write to the Free Software
74 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
75 #
76 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
77 #
78 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
79
80 # --------------------------------------------------------
81 # Generated by AdaoCatalogGenerator on {date}
82 # --------------------------------------------------------
83
84 import os, re
85 import Accas
86 from Accas import *
87
88 JdC = JDC_CATA (
89     code = '%s',
90     execmodul = None,
91     regles = ( AU_MOINS_UN ('ASSIMILATION_STUDY','OPTIMIZATION_STUDY','REDUCTION_STUDY','CHECKING_STUDY'), AU_PLUS_UN ('ASSIMILATION_STUDY','OPTIMIZATION_STUDY','REDUCTION_STUDY','CHECKING_STUDY')),
92     )
93 VERSION_CATALOGUE='%s'
94
95 def NoCheckInNS(filename):
96     return 1
97 NoCheckInNS.info = u""
98 def DirectOperatorInNS(filename):
99     if os.path.exists(filename):
100         fc = open(filename, 'r').readlines()
101         cr = re.compile("^def[\s]*DirectOperator[\s]*\(")
102         for ln in fc:
103             if cr.match(ln): return 1
104         cr = re.compile("^DirectOperator[\s]*=")
105         for ln in fc:
106             if cr.match(ln): return 1
107     return 0
108 DirectOperatorInNS.info = u"The Python file has to contain explicitly a \\"DirectOperator\\" function definition with only one vector as argument."
109 def TangentOperatorInNS(filename):
110     if os.path.exists(filename):
111         fc = open(filename, 'r').readlines()
112         cr = re.compile("^def[\s]*TangentOperator[\s]*\(")
113         for ln in fc:
114             if cr.match(ln): return 1
115         cr = re.compile("^TangentOperator[\s]*=")
116         for ln in fc:
117             if cr.match(ln): return 1
118     return 0
119 TangentOperatorInNS.info = u"The Python file has to contain explicitly a \\"TangentOperator\\" function definition with only one pair of vectors as argument."
120 def AdjointOperatorInNS(filename):
121     if os.path.exists(filename):
122         fc = open(filename, 'r').readlines()
123         cr = re.compile("^def[\s]*AdjointOperator[\s]*\(")
124         for ln in fc:
125             if cr.match(ln): return 1
126         cr = re.compile("^AdjointOperator[\s]*=")
127         for ln in fc:
128             if cr.match(ln): return 1
129     return 0
130 AdjointOperatorInNS.info = u"The Python file has to contain explicitly an \\"AdjointOperator\\" function definition with only one pair of vectors as argument."
131 def ColDataFileExtVal(filename):
132     __readable = (".csv", ".tsv", ".txt", ".npy", ".npz")
133     if os.path.exists(filename) and os.path.splitext(filename)[1] in __readable:
134         return 1
135     return 0
136 ColDataFileExtVal.info = u"The data file has to contain explicitly one or more number columns with separator, or one variable, that can fit in a unique continuous vector."
137 """%(module_version.name,module_version.cata)
138
139 # Important : validators=[...] pour que les conditions soient traitees simultanement, en "ET", et pas en "OU" (choisi dans le cas du tuple a la place de la liste)
140 # validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)]
141 data_method = """
142 def F_{data_name}(statut, fv=NoCheckInNS) : return FACT(
143     statut = statut,
144     FROM = SIMP(statut = "o", typ = "TXM", into=({data_into}), defaut={data_default}),
145     SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
146         SCRIPT_FILE = SIMP(statut = "o", typ = ("FichierNoAbs",'Python Files (*.py)',), 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"),
147         ),
148     DATA_DATA = BLOC ( condition = " FROM in ( 'DataFile', ) ",
149         DATA_FILE = SIMP(statut = "o", typ = ("FichierNoAbs",'CSV Text Files (*.csv);;TSV Text Files (*.tsv);;TXT Text Files (*.txt);;NPY Binary Numpy Files (*.npy);;NPZ Binary Numpy Files (*.npz);;All Files (*)", ',), validators=[OnlyStr(), FunctionVal(ColDataFileExtVal)], fr="En attente d'un nom de fichier de données, avec ou sans le chemin complet pour le trouver, contenant ou plusieurs colonnes pour définir un unique vecteur continu", ang="Waiting for a data file name, with or without the full path to find it, containing one or more columns to define a unique continuous vector"),
150         ColMajor = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0, fr="Variables en colonnes acquises ligne par ligne (0) ou colonne par colonne (1)", ang="Variables in columns acquired line by line (0) or column by column (1)"),
151         ),
152     STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
153         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"),
154         ),
155     SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
156         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"),
157         ),
158     SCRIPTWITHONEFUNCTION_DATA = BLOC ( condition = " FROM in ( 'ScriptWithOneFunction', ) ",
159         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"),
160         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"),
161         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"),
162         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"),
163         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"),
164         ),
165     SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
166         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"),
167         ),
168     TEMPLATE_DATA =  BLOC (condition = " FROM in ( 'Template', ) ",
169         Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "AnalysisPrinter", into=("AnalysisPrinter", "AnalysisSaver", "AnalysisPrinterAndSaver")),
170         AnalysisPrinter = BLOC (condition = " Template == 'AnalysisPrinter' ",
171             ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy\\nxa=numpy.ravel(ADD.get('Analysis')[-1])\\nprint('Analysis:',xa)" ),
172             ),
173         AnalysisSaver = BLOC (condition = " Template == 'AnalysisSaver' ",
174             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)" ),
175             ),
176         AnalysisPrinterAndSaver = BLOC (condition = " Template == 'AnalysisPrinterAndSaver' ",
177             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)" ),
178             ),
179         ),
180     )
181 """
182
183 init_method = """
184 def F_InitChoice() : return  ("Background",
185                               "BackgroundError",
186                               "Observation",
187                               "ObservationError",
188                               "ObservationOperator",
189                               "EvolutionModel",
190                               "EvolutionError",
191                               "AlgorithmParameters",
192                               "UserPostAnalysis",
193                              )
194
195 def F_Init(statut) : return FACT(statut = statut,
196     INIT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')]),
197     TARGET_LIST = SIMP(statut = "o", typ = "TXM", min=1, max="**", into=F_InitChoice(),  validators=(VerifExiste(2))),
198     )
199 """
200
201 assim_data_method = """
202 def {assim_name}InNS(filename):
203     if os.path.exists(filename):
204         fc = open(filename, 'r').readlines()
205         cr = re.compile("^{assim_name}[\s]*=")
206         for ln in fc:
207             if cr.match(ln): return 1
208     return 0
209 {assim_name}InNS.info = u"The Python file has to contain explicitly a \\"{assim_name}\\" variable."
210 def F_{assim_name}(statut, fv=NoCheckInNS) : return FACT(
211     statut=statut,
212 {storage}
213     INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=({choices}), defaut={default_choice}),{decl_choices}
214     )
215 """
216
217 assim_data_choice = """
218     {choice_name} = BLOC ( condition = " INPUT_TYPE in ( '{choice_name}', ) ",
219         data = F_{choice_name}("o", fv),
220         ),"""
221
222 observers_choice = """
223     {var_name} = BLOC (condition=" '{var_name}' in set(SELECTION) ",
224         {var_name}_data = FACT(statut = "o",
225             Scheduler    = SIMP(statut = "f", typ = "TXM"),
226             Info         = SIMP(statut = "o", typ = "TXM", defaut = "{var_name}"),
227             NodeType     = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "Template", into=("String", "Script", "Template")),
228             PythonScript = BLOC (condition = " NodeType == 'String' ",
229                 Value = SIMP(statut = "o", typ = "TXM")
230                 ),
231             UserFile = BLOC (condition = " NodeType == 'Script' ",
232                 Value = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')])
233                 ),
234             ObserverTemplate = F_ObserverTemplate(),
235             ),
236         ),"""
237
238 from daCore.Templates import ObserverTemplates
239 observers_list = ObserverTemplates.keys_in_presentation_order()
240 observers_list = '"%s"'%str('", "'.join(observers_list))
241 observers_cont = ""
242 for k in ObserverTemplates.keys_in_presentation_order():
243     observers_cont += """                %s = BLOC (condition = " Template == '%s' ",\n"""%(k,k)
244     observers_cont += """                    ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "%s", fr="%s", ang="%s" ),\n"""%(
245         ObserverTemplates[k].replace("\n","\\n").replace('"','\\"'),
246         ObserverTemplates.getdoc(k, "fr_FR"),
247         ObserverTemplates.getdoc(k, "en_EN"),
248         )
249     observers_cont += """                    ),\n"""
250 observers_method = """
251 def F_ObserverTemplate() : return BLOC(condition = " NodeType == 'Template' ",
252                 Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "ValuePrinter", into=(%s)),
253 %s                )
254
255 def F_Observers(statut) : return FACT(
256     statut=statut,
257     SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", homo="SansOrdreNiDoublon", validators=NoRepeat(), into=({choices})),{decl_choices}
258     )
259 """%(observers_list,observers_cont)
260
261 algo_choices = """
262 def AlgorithmParametersInNS(filename):
263     if os.path.exists(filename):
264         fc = open(filename, 'r').readlines()
265         cr = re.compile("^AlgorithmParameters[\s]*=")
266         for ln in fc:
267             if cr.match(ln): return 1
268     return 0
269 AlgorithmParametersInNS.info = u"The Python file has to contain explicitly an \\"AlgorithmParameters\\" variable."
270 def F_AlgorithmParameters(statut, algos_names, fv=NoCheckInNS) : return FACT(
271     statut = statut,
272     Algorithm = SIMP(statut="o", typ = "TXM", into = algos_names ),
273     Parameters = SIMP(statut="f", typ = "TXM", into=("Defaults", "Dict"), defaut="Defaults"),
274     Dict = BLOC ( condition = " Parameters == 'Dict' ",
275         statut="f",
276         data = F_Dict("o", fv),
277         ),{all_algo_defaults}
278     )
279 """
280 one_algo_choices = """
281     Parameters{algo_name} = BLOC (condition = " (Parameters == 'Defaults') and (Algorithm == '{algo_name}') ",
282         statut="f",
283 {algo_parameters}        ),"""
284
285 assim_study = """
286 def F_variables(statut) : return FACT(
287     statut=statut,
288     regles = ( MEME_NOMBRE ('NAMES', 'SIZES')),
289     NAMES = SIMP(statut="o", typ="TXM", max="**", validators=NoRepeat()),
290     SIZES = SIMP(statut="o", typ="I", val_min=1, max="**")
291     )
292 def ChDir(dirname):
293     os.chdir(os.path.abspath(dirname))
294     return 1
295 ChDir.info = u"This has to be a regular directory path."
296
297 ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
298     op=None,
299     repetable           = "n",
300     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
301     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
302     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
303     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
304     AlgorithmParameters = F_AlgorithmParameters("o",({algos_names}), AlgorithmParametersInNS),
305     Background          = F_Background("o", BackgroundInNS),
306     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
307     Observation         = F_Observation("o", ObservationInNS),
308     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
309     ObservationOperator = F_ObservationOperator("o"),
310     EvolutionModel      = F_EvolutionModel("f"),
311     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
312     ControlInput        = F_ControlInput("f"),
313     UserDataInit        = F_Init("f"),
314     UserPostAnalysis    = F_UserPostAnalysis("o"),
315     InputVariables      = F_variables("f"),
316     OutputVariables     = F_variables("f"),
317     Observers           = F_Observers("f")
318     )
319
320 OPTIMIZATION_STUDY = PROC(nom="OPTIMIZATION_STUDY",
321     op=None,
322     repetable           = "n",
323     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
324     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
325     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
326     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
327     AlgorithmParameters = F_AlgorithmParameters("o",({optim_names}), AlgorithmParametersInNS),
328     Background          = F_Background("o", BackgroundInNS),
329     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
330     Observation         = F_Observation("o", ObservationInNS),
331     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
332     ObservationOperator = F_ObservationOperator("o"),
333     EvolutionModel      = F_EvolutionModel("f"),
334     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
335     ControlInput        = F_ControlInput("f"),
336     UserDataInit        = F_Init("f"),
337     UserPostAnalysis    = F_UserPostAnalysis("o"),
338     InputVariables      = F_variables("f"),
339     OutputVariables     = F_variables("f"),
340     Observers           = F_Observers("f")
341     )
342
343 REDUCTION_STUDY = PROC(nom="REDUCTION_STUDY",
344     op=None,
345     repetable           = "n",
346     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
347     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
348     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
349     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
350     AlgorithmParameters = F_AlgorithmParameters("o",({reduc_names}), AlgorithmParametersInNS),
351     Background          = F_Background("o", BackgroundInNS),
352     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
353     Observation         = F_Observation("o", ObservationInNS),
354     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
355     ObservationOperator = F_ObservationOperator("o"),
356     EvolutionModel      = F_EvolutionModel("f"),
357     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
358     ControlInput        = F_ControlInput("f"),
359     UserDataInit        = F_Init("f"),
360     UserPostAnalysis    = F_UserPostAnalysis("o"),
361     InputVariables      = F_variables("f"),
362     OutputVariables     = F_variables("f"),
363     Observers           = F_Observers("f")
364     )
365
366 CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
367     op=None,
368     repetable           = "n",
369     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Checking Case"),
370     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
371     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
372     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
373     AlgorithmParameters = F_AlgorithmParameters("o", ({check_names}), AlgorithmParametersInNS),
374     CheckingPoint       = F_CheckingPoint("o", CheckingPointInNS),
375     Background          = F_Background("f", BackgroundInNS),
376     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
377     Observation         = F_Observation("f", ObservationInNS),
378     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
379     ObservationOperator = F_ObservationOperator("o"),
380     UserDataInit        = F_Init("f"),
381     Observers           = F_Observers("f")
382     )
383 """
384
385 #----------- End of Templates Part ---------------#
386
387 #===============================================================================
388
389 #----------- Begin generation script -----------#
390
391 # Parse arguments
392 from argparse import ArgumentParser
393 usage = "usage: %(prog)s [options] catalog_path catalog_name"
394 version="%(prog)s 0.1"
395 my_parser = ArgumentParser(usage=usage)
396 my_parser.add_argument('-v', '--version', action='version', version=version)
397 my_parser.add_argument('catalog_path')
398 my_parser.add_argument('catalog_name')
399 args = my_parser.parse_args()
400
401 # Generates into a string
402 mem_file = io.StringIO()
403
404 # Initial step: On ouvre le fichier
405 from time import strftime
406 mem_file.write(unicode(begin_catalog_file, 'utf-8').format(**{'date':strftime("%Y-%m-%d %H:%M:%S")}))
407
408 # Step 0: on obtient la liste des algos
409 algos_names = ""
410 optim_names = ""
411 reduc_names = ""
412 check_names = ""
413 decl_algos  = ""
414 algal_names = ""
415 assim_study_object = daCore.Aidsm.Aidsm()
416 algos_list = assim_study_object.get_available_algorithms()
417 del assim_study_object
418 for algo_name in algos_list:
419   if algo_name in infos.AssimAlgos:
420     logging.debug("An assimilation algorithm is found: " + algo_name)
421     algos_names += "\"" + algo_name + "\", "
422   if algo_name in infos.OptimizationAlgos:
423     logging.debug("An optimization algorithm is found: " + algo_name)
424     optim_names += "\"" + algo_name + "\", "
425   if algo_name in infos.ReductionAlgos:
426     logging.debug("A reduction algorithm is found: " + algo_name)
427     reduc_names += "\"" + algo_name + "\", "
428   if algo_name in infos.CheckAlgos:
429     logging.debug("A checking algorithm is found: " + algo_name)
430     check_names += "\"" + algo_name + "\", "
431   if algo_name in infos.AssimAlgos+infos.OptimizationAlgos+infos.ReductionAlgos+infos.CheckAlgos:
432     # Pour filtrer sur les algorithmes vraiment interfacés, car il peut y en avoir moins que "algos_list"
433     algal_names += "\"" + algo_name + "\", "
434
435 # Step 1: A partir des infos, on crée les fonctions qui vont permettre
436 # d'entrer les données utilisateur
437 for data_input_name in infos.DataTypeDict:
438   logging.debug('A data input Type is found: ' + data_input_name)
439   data_name = data_input_name
440   data_into = ""
441   data_default = ""
442   ms_default = ""
443
444   # On récupère les différentes façon d'entrer les données
445   for basic_type in infos.DataTypeDict[data_input_name]:
446     data_into += "\"" + basic_type + "\", "
447
448   # On choisit le défaut
449   data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
450   if data_input_name in infos.DataSValueDefaultDict:
451     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[data_input_name] + "\","
452
453   mem_file.write(unicode(data_method, 'utf-8').format(**{
454     'data_name'    : data_name,
455     'data_into'    : data_into,
456     'data_default' : data_default,
457     'ms_default'   : ms_default,
458     #~ 'algos_names'  : algal_names,
459     }))
460
461 # Step 2: On crée les fonctions qui permettent de rentrer les données des algorithmes
462 for assim_data_input_name in infos.AssimDataDict:
463   logging.debug("An input function data input is found: " + assim_data_input_name)
464   # assim_name = assim_data_input_name
465   storage = ""
466   choices = ""
467   default_choice = ""
468   decl_choices = ""
469   decl_opts = ""
470   if infos.AssimDataDefaultDict[assim_data_input_name] in infos.StoredAssimData:
471     storage = "    Stored = SIMP(statut=\"f\", 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\"),"
472   for choice in infos.AssimDataDict[assim_data_input_name]:
473     choices += "\"" + choice + "\", "
474     decl_choices += assim_data_choice.format(**{'choice_name' : choice})
475     if choice in infos.StoredAssimData:
476       storage = "    Stored = SIMP(statut=\"f\", 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\"),"
477   default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
478
479   mem_file.write(unicode(assim_data_method, 'utf-8').format(**{
480     'assim_name'     : assim_data_input_name,
481     'storage'        : storage,
482     'choices'        : choices,
483     'decl_choices'   : decl_choices,
484     'default_choice' : default_choice,
485     }))
486
487 # Step 3: On ajoute les fonctions représentant les options possibles
488 for opt_name in infos.OptDict:
489   logging.debug("An optional node is found: " + opt_name)
490   data_name = opt_name
491   data_into = ""
492   data_default = ""
493   ms_default = ""
494
495   for choice in infos.OptDict[opt_name]:
496     data_into += "\"" + choice + "\", "
497
498   # On choisit le default
499   data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
500   if opt_name in infos.DataSValueDefaultDict:
501     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[opt_name] + "\","
502
503   mem_file.write(unicode(data_method, 'utf-8').format(**{
504     'data_name'    : data_name,
505     'data_into'    : data_into,
506     'data_default' : data_default,
507     'ms_default'   : ms_default,
508     #~ 'algos_names'  : algal_names,
509     }))
510
511 # Step 3bis: On ajoute la méthode optionnelle init
512 #            TODO si possible uniformiser avec le step 3
513 mem_file.write(unicode(init_method, 'utf-8'))
514
515 # Step 4: On ajoute les observers
516 decl_choices = ""
517 for obs_var in infos.ObserversList:
518   decl_choices += observers_choice.format(**{'var_name':obs_var})
519 mem_file.write(unicode(observers_method, 'utf-8').format(**{
520   'choices' : infos.ObserversList,
521   'decl_choices' : decl_choices,
522   }))
523
524 # Step 5: On ajoute les choix algorithmiques
525 all_names = eval((algal_names))
526 all_algo_defaults = ""
527 for algo in all_names:
528     assim_study_object = daCore.Aidsm.Aidsm()
529     assim_study_object.setAlgorithmParameters(Algorithm=algo)
530     par_dict = assim_study_object.get("AlgorithmRequiredParameters",False)
531     par_keys = sorted(par_dict.keys())
532     algo_parameters = ""
533     for pn in par_keys:
534         if pn in ("StoreInternalVariables", "PlotAndSave", "ResultFile", "ResultTitle", "ResultLabel"): continue # Cles a supprimer
535         pt = par_dict[pn]["typecast"] # Pointeur de type
536         pd = par_dict[pn]["default"]
537         pm = par_dict[pn]["message"]
538         if "minval" in par_dict[pn] and par_dict[pn]["minval"] is not None:
539             vi = ", val_min=%s"%par_dict[pn]["minval"]
540         else:
541             vi = ""
542         if "minval" in par_dict[pn] and par_dict[pn]["maxval"] is not None:
543             vs = ", val_max=%s"%par_dict[pn]["maxval"]
544         else:
545             vs = ""
546         if   pt is int:
547             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)
548         elif pt is float:
549             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)
550         elif pt is bool:
551             algo_parameters += """        %s = SIMP(statut="f", typ="I", min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
552         elif pt is str and "listval" in par_dict[pn]:
553             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", min=1, max=1, defaut="%s", into=%s, fr="%s"),\n"""%(pn,pd,par_dict[pn]["listval"],pm)
554         elif pt is tuple and "listval" in par_dict[pn]:
555             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", max="**", into=%s, fr="%s"),\n"""%(pn,par_dict[pn]["listval"],pm)
556         else:
557             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", fr="%s"),\n"""%(pn,pm)
558     del assim_study_object
559     if algo_parameters != "":
560         all_algo_defaults += one_algo_choices.format(**{
561             'algo_name':algo,
562             'algo_parameters':algo_parameters,
563             })
564 mem_file.write(unicode(algo_choices, 'utf-8').format(**{'all_algo_defaults':unicode(all_algo_defaults, 'utf-8')}))
565
566 # Step 6: On ajoute l'algorithme et le assim_study
567 mem_file.write(unicode(assim_study, 'utf-8').format(**{
568   'algos_names':algos_names,
569   'optim_names':optim_names,
570   'reduc_names':reduc_names,
571   'check_names':check_names,
572   'decl_algos':decl_algos,
573   }))
574
575 # Final step: On écrit le fichier
576 if sys.version_info.major > 2:
577     with open(os.path.join(args.catalog_path, args.catalog_name), "w", encoding='utf8') as final_file:
578         final_file.write(mem_file.getvalue())
579 else:
580     with open(os.path.join(args.catalog_path, args.catalog_name), "wr") as final_file:
581         final_file.write(mem_file.getvalue().encode('utf-8'))
582 mem_file.close()
583
584 #----------- End generation script -----------#
585
586 #===============================================================================