Salome HOME
Documentation, style and code performance update
[modules/adao.git] / bin / AdaoCatalogGenerator.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2024 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-2024 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.isfile(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.isfile(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.isfile(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.isfile(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 # --------------------------------------
140
141 from daCore.Templates import UserPostAnalysisTemplates
142 upa_list = UserPostAnalysisTemplates.keys_in_presentation_order()
143 upa_list = '"%s"'%str('", "'.join(upa_list))
144 upa_cont = ""
145 for k in UserPostAnalysisTemplates.keys_in_presentation_order():
146     upa_cont += """        %s = BLOC (condition = " Template == '%s' ",\n"""%(k,k)
147     upa_cont += """            ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "%s", fr="%s", ang="%s" ),\n"""%(
148         UserPostAnalysisTemplates[k].replace("\n","\\n").replace('"','\\"'),
149         UserPostAnalysisTemplates.getdoc(k, "fr_FR"),
150         UserPostAnalysisTemplates.getdoc(k, "en_EN"),
151         )
152     upa_cont += """            ),\n"""
153
154 # Important : validators=[...] pour que les conditions soient traitées simultanément, en "ET", et pas en "OU" (choisi dans le cas du tuple a la place de la liste)
155 # validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)]
156 data_method = """
157 def F_{data_name}(statut, fv=NoCheckInNS) : return FACT(
158     statut = statut,
159     FROM = SIMP(statut = "o", typ = "TXM", into=({data_into}), defaut={data_default}),
160     SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
161         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"),
162         ),
163     DATA_DATA = BLOC ( condition = " FROM in ( 'DataFile', ) ",
164         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"),
165         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)"),
166         ),
167     STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
168         STRING = SIMP(statut = "o", typ = "TXM",{ms_default} fr="En attente d'une chaîne de caractères entre guillemets. 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"),
169         ),
170     SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
171         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"),
172         ),
173     SCRIPTWITHONEFUNCTION_DATA = BLOC ( condition = " FROM in ( 'ScriptWithOneFunction', ) ",
174         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"),
175         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"),
176         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"),
177         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"),
178         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"),
179         ),
180     SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
181         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"),
182         ),
183 """+\
184 """    TEMPLATE_DATA =  BLOC (condition = " FROM in ( 'Template', ) ",
185         Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "AnalysisPrinter", into=(%s)),
186 """%(upa_list,)+\
187 upa_cont+\
188 """        ),
189     )
190 """
191
192 # --------------------------------------
193
194 init_method = """
195 def F_InitChoice() : return  ("Background",
196                               "BackgroundError",
197                               "Observation",
198                               "ObservationError",
199                               "ObservationOperator",
200                               "EvolutionModel",
201                               "EvolutionError",
202                               "AlgorithmParameters",
203                               "UserPostAnalysis",
204                              )
205
206 def F_Init(statut) : return FACT(statut = statut,
207     INIT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')]),
208     TARGET_LIST = SIMP(statut = "o", typ = "TXM", min=1, max="**", into=F_InitChoice(),  validators=(VerifExiste(2))),
209     )
210 """
211
212 assim_data_method = """
213 def {assim_name}InNS(filename):
214     if os.path.isfile(filename):
215         fc = open(filename, 'r').readlines()
216         cr = re.compile("^{assim_name}[\s]*=")
217         for ln in fc:
218             if cr.match(ln): return 1
219     return 0
220 {assim_name}InNS.info = u"The Python file has to contain explicitly a \\"{assim_name}\\" variable."
221 def F_{assim_name}(statut, fv=NoCheckInNS) : return FACT(
222     statut=statut,
223 {storage}
224     INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=({choices}), defaut={default_choice}),{decl_choices}
225     )
226 """
227
228 assim_data_choice = """
229     {choice_name} = BLOC ( condition = " INPUT_TYPE in ( '{choice_name}', ) ",
230         data = F_{choice_name}("o", fv),
231         ),"""
232
233 observers_choice = """
234     {var_name} = BLOC (condition=" '{var_name}' in set(SELECTION) ",
235         {var_name}_data = FACT(statut = "o",
236             Scheduler    = SIMP(statut = "f", typ = "TXM"),
237             Info         = SIMP(statut = "o", typ = "TXM", defaut = "{var_name}"),
238             NodeType     = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "Template", into=("String", "Script", "Template")),
239             PythonScript = BLOC (condition = " NodeType == 'String' ",
240                 Value = SIMP(statut = "o", typ = "TXM")
241                 ),
242             UserFile = BLOC (condition = " NodeType == 'Script' ",
243                 Value = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')])
244                 ),
245             ObserverTemplate = F_ObserverTemplate(),
246             ),
247         ),"""
248
249 # --------------------------------------
250
251 from daCore.Templates import ObserverTemplates
252 observers_list = ObserverTemplates.keys_in_presentation_order()
253 observers_list = '"%s"'%str('", "'.join(observers_list))
254 observers_cont = ""
255 for k in ObserverTemplates.keys_in_presentation_order():
256     observers_cont += """                %s = BLOC (condition = " Template == '%s' ",\n"""%(k,k)
257     observers_cont += """                    ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "%s", fr="%s", ang="%s" ),\n"""%(
258         ObserverTemplates[k].replace("\n","\\n").replace('"','\\"'),
259         ObserverTemplates.getdoc(k, "fr_FR"),
260         ObserverTemplates.getdoc(k, "en_EN"),
261         )
262     observers_cont += """                    ),\n"""
263
264 observers_method = """
265 def F_ObserverTemplate() : return BLOC(condition = " NodeType == 'Template' ",
266                 Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "ValuePrinter", into=(%s)),
267 %s                )
268
269 def F_Observers(statut) : return FACT(
270     statut=statut,
271     SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", homo="SansOrdreNiDoublon", validators=NoRepeat(), into=({choices})),{decl_choices}
272     )
273 """%(observers_list,observers_cont)
274
275 # --------------------------------------
276
277 algo_choices = """
278 def AlgorithmParametersInNS(filename):
279     if os.path.isfile(filename):
280         fc = open(filename, 'r').readlines()
281         cr = re.compile("^AlgorithmParameters[\s]*=")
282         for ln in fc:
283             if cr.match(ln): return 1
284     return 0
285 AlgorithmParametersInNS.info = u"The Python file has to contain explicitly an \\"AlgorithmParameters\\" variable."
286 def F_AlgorithmParameters(statut, algos_names, fv=NoCheckInNS) : return FACT(
287     statut = statut,
288     Algorithm = SIMP(statut="o", typ = "TXM", into = algos_names ),
289     Parameters = SIMP(statut="f", typ = "TXM", into=("Defaults", "Dict"), defaut="Defaults"),
290     Dict = BLOC ( condition = " Parameters == 'Dict' ",
291         statut="f",
292         data = F_Dict("o", fv),
293         ),{all_algo_defaults}
294     )
295 """
296 one_algo_choices = """
297     Parameters{algo_name} = BLOC (condition = " (Parameters == 'Defaults') and (Algorithm == '{algo_name}') ",
298         statut="f",
299 {algo_parameters}        ),"""
300
301 # --------------------------------------
302
303 assim_study = """
304 def F_variables(statut) : return FACT(
305     statut=statut,
306     regles = ( MEME_NOMBRE ('NAMES', 'SIZES')),
307     NAMES = SIMP(statut="o", typ="TXM", max="**", validators=NoRepeat()),
308     SIZES = SIMP(statut="o", typ="I", val_min=1, max="**")
309     )
310 def ChDir(dirname):
311     os.chdir(os.path.abspath(dirname))
312     return 1
313 ChDir.info = u"This has to be a regular directory path."
314
315 ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
316     op=None,
317     repetable           = "n",
318     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
319     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
320     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
321     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
322     AlgorithmParameters = F_AlgorithmParameters("o",({algos_names}), AlgorithmParametersInNS),
323     Background          = F_Background("o", BackgroundInNS),
324     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
325     Observation         = F_Observation("o", ObservationInNS),
326     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
327     ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
328     EvolutionModel      = F_EvolutionModel("f", EvolutionModelInNS),
329     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
330     ControlInput        = F_ControlInput("f"),
331     UserDataInit        = F_Init("f"),
332     UserPostAnalysis    = F_UserPostAnalysis("o"),
333     InputVariables      = F_variables("f"),
334     OutputVariables     = F_variables("f"),
335     Observers           = F_Observers("f")
336     )
337
338 OPTIMIZATION_STUDY = PROC(nom="OPTIMIZATION_STUDY",
339     op=None,
340     repetable           = "n",
341     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
342     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
343     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
344     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
345     AlgorithmParameters = F_AlgorithmParameters("o",({optim_names}), AlgorithmParametersInNS),
346     Background          = F_Background("o", BackgroundInNS),
347     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
348     Observation         = F_Observation("o", ObservationInNS),
349     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
350     ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
351     EvolutionModel      = F_EvolutionModel("f", EvolutionModelInNS),
352     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
353     ControlInput        = F_ControlInput("f"),
354     UserDataInit        = F_Init("f"),
355     UserPostAnalysis    = F_UserPostAnalysis("o"),
356     InputVariables      = F_variables("f"),
357     OutputVariables     = F_variables("f"),
358     Observers           = F_Observers("f")
359     )
360
361 REDUCTION_STUDY = PROC(nom="REDUCTION_STUDY",
362     op=None,
363     repetable           = "n",
364     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
365     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
366     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
367     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
368     AlgorithmParameters = F_AlgorithmParameters("o",({reduc_names}), AlgorithmParametersInNS),
369     Background          = F_Background("o", BackgroundInNS),
370     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
371     Observation         = F_Observation("o", ObservationInNS),
372     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
373     ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
374     EvolutionModel      = F_EvolutionModel("f", EvolutionModelInNS),
375     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
376     ControlInput        = F_ControlInput("f"),
377     UserDataInit        = F_Init("f"),
378     UserPostAnalysis    = F_UserPostAnalysis("o"),
379     InputVariables      = F_variables("f"),
380     OutputVariables     = F_variables("f"),
381     Observers           = F_Observers("f")
382     )
383
384 CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
385     op=None,
386     repetable           = "n",
387     StudyName           = SIMP(statut="o", typ = "TXM", defaut="ADAO Checking Case"),
388     StudyRepertory      = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
389     Debug               = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
390     ExecuteInContainer  = SIMP(statut="f", typ = "TXM", min=1, max=1, defaut = "No", into=("No", "Mono", "Multi")),
391     AlgorithmParameters = F_AlgorithmParameters("o", ({check_names}), AlgorithmParametersInNS),
392     CheckingPoint       = F_CheckingPoint("o", CheckingPointInNS),
393     Background          = F_Background("f", BackgroundInNS),
394     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
395     Observation         = F_Observation("f", ObservationInNS),
396     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
397     ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
398     UserDataInit        = F_Init("f"),
399     Observers           = F_Observers("f")
400     )
401 """
402
403 #----------- End of Templates Part ---------------#
404
405 #===============================================================================
406
407 #----------- Begin generation script -----------#
408
409 # Parse arguments
410 from argparse import ArgumentParser
411 usage = "usage: %(prog)s [options] catalog_path catalog_name"
412 version="%(prog)s 0.1"
413 my_parser = ArgumentParser(usage=usage)
414 my_parser.add_argument('-v', '--version', action='version', version=version)
415 my_parser.add_argument('catalog_path')
416 my_parser.add_argument('catalog_name')
417 args = my_parser.parse_args()
418
419 # Generates into a string
420 mem_file = io.StringIO()
421
422 # Initial step: On ouvre le fichier
423 from time import strftime
424 mem_file.write(unicode(begin_catalog_file, 'utf-8').format(**{'date':strftime("%Y-%m-%d %H:%M:%S")}))
425
426 # Step 0: on obtient la liste des algos
427 algos_names = ""
428 optim_names = ""
429 reduc_names = ""
430 check_names = ""
431 task_names  = ""
432 adao_all_names = ""
433 assim_study_object = daCore.Aidsm.Aidsm()
434 algos_list = assim_study_object._Aidsm__get_available_algorithms()
435 del assim_study_object
436 for algo_name in algos_list:
437   if algo_name in infos.AssimAlgos:
438     logging.debug("An assimilation algorithm is found: " + algo_name)
439     algos_names += "\"" + algo_name + "\", "
440   if algo_name in infos.OptimizationAlgos:
441     logging.debug("An optimization algorithm is found: " + algo_name)
442     optim_names += "\"" + algo_name + "\", "
443   if algo_name in infos.ReductionAlgos:
444     logging.debug("A reduction algorithm is found: " + algo_name)
445     reduc_names += "\"" + algo_name + "\", "
446   if algo_name in infos.CheckAlgos:
447     logging.debug("A checking algorithm is found: " + algo_name)
448     check_names += "\"" + algo_name + "\", "
449   if algo_name in infos.TaskAlgos:
450     logging.debug("A task algorithm is found: " + algo_name)
451     task_names += "\"" + algo_name + "\", "
452   if algo_name in infos.AssimAlgos+infos.OptimizationAlgos+infos.ReductionAlgos+infos.CheckAlgos+infos.TaskAlgos:
453     # Pour filtrer sur les algorithmes vraiment interfacés, car il peut y en avoir moins que "algos_list"
454     adao_all_names += "\"" + algo_name + "\", "
455
456 # Step 1: A partir des infos, on crée les fonctions qui vont permettre
457 # d'entrer les données utilisateur
458 for data_input_name in infos.DataTypeDict:
459   logging.debug('A data input Type is found: ' + data_input_name)
460   data_name = data_input_name
461   data_into = ""
462   data_default = ""
463   ms_default = ""
464
465   # On récupère les différentes façon d'entrer les données
466   for basic_type in infos.DataTypeDict[data_input_name]:
467     data_into += "\"" + basic_type + "\", "
468
469   # On choisit le défaut
470   data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
471   if data_input_name in infos.DataSValueDefaultDict:
472     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[data_input_name] + "\","
473
474   mem_file.write(unicode(data_method, 'utf-8').format(**{
475     'data_name'    : data_name,
476     'data_into'    : data_into,
477     'data_default' : data_default,
478     'ms_default'   : ms_default,
479     }))
480
481 # Step 2: On crée les fonctions qui permettent de rentrer les données des algorithmes
482 for assim_data_input_name in infos.AssimDataDict:
483   logging.debug("An input function data input is found: " + assim_data_input_name)
484   # assim_name = assim_data_input_name
485   storage = ""
486   choices = ""
487   default_choice = ""
488   decl_choices = ""
489   decl_opts = ""
490   if infos.AssimDataDefaultDict[assim_data_input_name] in infos.StoredAssimData:
491     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\"),"
492   for choice in infos.AssimDataDict[assim_data_input_name]:
493     choices += "\"" + choice + "\", "
494     decl_choices += assim_data_choice.format(**{'choice_name' : choice})
495     if choice in infos.StoredAssimData:
496       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\"),"
497   default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
498
499   mem_file.write(unicode(assim_data_method, 'utf-8').format(**{
500     'assim_name'     : assim_data_input_name,
501     'storage'        : storage,
502     'choices'        : choices,
503     'decl_choices'   : decl_choices,
504     'default_choice' : default_choice,
505     }))
506
507 # Step 3: On ajoute les fonctions représentant les options possibles
508 for opt_name in infos.OptDict:
509   logging.debug("An optional node is found: " + opt_name)
510   data_name = opt_name
511   data_into = ""
512   data_default = ""
513   ms_default = ""
514
515   for choice in infos.OptDict[opt_name]:
516     data_into += "\"" + choice + "\", "
517
518   # On choisit le default
519   data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
520   if opt_name in infos.DataSValueDefaultDict:
521     ms_default = " defaut=\"" + infos.DataSValueDefaultDict[opt_name] + "\","
522
523   mem_file.write(unicode(data_method, 'utf-8').format(**{
524     'data_name'    : data_name,
525     'data_into'    : data_into,
526     'data_default' : data_default,
527     'ms_default'   : ms_default,
528     }))
529
530 # Step 3bis: On ajoute la méthode optionnelle init
531 #            TODO si possible uniformiser avec le step 3
532 mem_file.write(unicode(init_method, 'utf-8'))
533
534 # Step 4: On ajoute les observers
535 decl_choices = ""
536 for obs_var in infos.ObserversList:
537   decl_choices += observers_choice.format(**{'var_name':obs_var})
538 mem_file.write(unicode(observers_method, 'utf-8').format(**{
539   'choices' : infos.ObserversList,
540   'decl_choices' : decl_choices,
541   }))
542
543 # Step 5: On ajoute les choix algorithmiques
544 all_names = eval((adao_all_names))
545 all_algo_defaults = ""
546 for algo in all_names:
547     assim_study_object = daCore.Aidsm.Aidsm()
548     assim_study_object.setAlgorithmParameters(Algorithm=algo)
549     par_dict = assim_study_object.get("AlgorithmRequiredParameters",False)
550     par_keys = sorted(par_dict.keys())
551     algo_parameters = ""
552     for pn in par_keys:
553         if pn in ("StoreInternalVariables", "PlotAndSave", "ResultFile", "ResultTitle", "ResultLabel"): continue # Cles a supprimer
554         pt = par_dict[pn]["typecast"] # Pointeur de type
555         pd = par_dict[pn]["default"]
556         pm = par_dict[pn]["message"]
557         if "minval" in par_dict[pn] and par_dict[pn]["minval"] is not None:
558             vi = ", val_min=%s"%par_dict[pn]["minval"]
559         else:
560             vi = ""
561         if "minval" in par_dict[pn] and par_dict[pn]["maxval"] is not None:
562             vs = ", val_max=%s"%par_dict[pn]["maxval"]
563         else:
564             vs = ""
565         if   pt is int:
566             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)
567         elif pt is float:
568             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)
569         elif pt is bool:
570             algo_parameters += """        %s = SIMP(statut="f", typ="I", into=(0, 1), min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
571         elif pt is str and "listval" in par_dict[pn]:
572             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)
573         elif pt is tuple and "listval" in par_dict[pn]:
574             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", max="**", into=%s, fr="%s"),\n"""%(pn,par_dict[pn]["listval"],pm)
575         else:
576             algo_parameters += """        %s = SIMP(statut="f", typ="TXM", fr="%s"),\n"""%(pn,pm)
577     del assim_study_object
578     if algo_parameters != "":
579         all_algo_defaults += one_algo_choices.format(**{
580             'algo_name':algo,
581             'algo_parameters':algo_parameters,
582             })
583 mem_file.write(unicode(algo_choices, 'utf-8').format(**{'all_algo_defaults':unicode(all_algo_defaults, 'utf-8')}))
584
585 # Step 6: On ajoute l'algorithme et le assim_study
586 mem_file.write(unicode(assim_study, 'utf-8').format(**{
587   'algos_names':algos_names,
588   'optim_names':optim_names,
589   'reduc_names':reduc_names,
590   'check_names':check_names,
591   'task_names':task_names,
592   }))
593
594 # Final step: On écrit le fichier
595 if sys.version_info.major > 2:
596     with open(os.path.join(args.catalog_path, args.catalog_name), "w", encoding='utf8') as final_file:
597         final_file.write(mem_file.getvalue())
598 else:
599     with open(os.path.join(args.catalog_path, args.catalog_name), "wr") as final_file:
600         final_file.write(mem_file.getvalue().encode('utf-8'))
601 mem_file.close()
602
603 #----------- End generation script -----------#
604
605 #===============================================================================