Salome HOME
Documentation update
[modules/adao.git] / bin / AdaoCatalogGenerator.py
index d7b0e3ea210e1bdc9244fc0cfb79db12b46b5f3f..2c25a63f8b875a492220c25d2f9ab6fba9909ce5 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2021 EDF R&D
+# Copyright (C) 2008-2022 EDF R&D
 #
 # This file is part of SALOME ADAO module
 #
@@ -55,7 +55,7 @@ except:
 
 begin_catalog_file = """# -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2021 EDF R&D
+# Copyright (C) 2008-2022 EDF R&D
 #
 # This file is part of SALOME ADAO module
 #
@@ -96,7 +96,7 @@ def NoCheckInNS(filename):
     return 1
 NoCheckInNS.info = u""
 def DirectOperatorInNS(filename):
-    if os.path.exists(filename):
+    if os.path.isfile(filename):
         fc = open(filename, 'r').readlines()
         cr = re.compile("^def[\s]*DirectOperator[\s]*\(")
         for ln in fc:
@@ -107,7 +107,7 @@ def DirectOperatorInNS(filename):
     return 0
 DirectOperatorInNS.info = u"The Python file has to contain explicitly a \\"DirectOperator\\" function definition with only one vector as argument."
 def TangentOperatorInNS(filename):
-    if os.path.exists(filename):
+    if os.path.isfile(filename):
         fc = open(filename, 'r').readlines()
         cr = re.compile("^def[\s]*TangentOperator[\s]*\(")
         for ln in fc:
@@ -118,7 +118,7 @@ def TangentOperatorInNS(filename):
     return 0
 TangentOperatorInNS.info = u"The Python file has to contain explicitly a \\"TangentOperator\\" function definition with only one pair of vectors as argument."
 def AdjointOperatorInNS(filename):
-    if os.path.exists(filename):
+    if os.path.isfile(filename):
         fc = open(filename, 'r').readlines()
         cr = re.compile("^def[\s]*AdjointOperator[\s]*\(")
         for ln in fc:
@@ -130,13 +130,28 @@ def AdjointOperatorInNS(filename):
 AdjointOperatorInNS.info = u"The Python file has to contain explicitly an \\"AdjointOperator\\" function definition with only one pair of vectors as argument."
 def ColDataFileExtVal(filename):
     __readable = (".csv", ".tsv", ".txt", ".npy", ".npz")
-    if os.path.exists(filename) and os.path.splitext(filename)[1] in __readable:
+    if os.path.isfile(filename) and os.path.splitext(filename)[1] in __readable:
         return 1
     return 0
 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."
 """%(module_version.name,module_version.cata)
 
-# 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)
+# --------------------------------------
+
+from daCore.Templates import UserPostAnalysisTemplates
+upa_list = UserPostAnalysisTemplates.keys_in_presentation_order()
+upa_list = '"%s"'%str('", "'.join(upa_list))
+upa_cont = ""
+for k in UserPostAnalysisTemplates.keys_in_presentation_order():
+    upa_cont += """        %s = BLOC (condition = " Template == '%s' ",\n"""%(k,k)
+    upa_cont += """            ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "%s", fr="%s", ang="%s" ),\n"""%(
+        UserPostAnalysisTemplates[k].replace("\n","\\n").replace('"','\\"'),
+        UserPostAnalysisTemplates.getdoc(k, "fr_FR"),
+        UserPostAnalysisTemplates.getdoc(k, "en_EN"),
+        )
+    upa_cont += """            ),\n"""
+
+# 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)
 # validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)]
 data_method = """
 def F_{data_name}(statut, fv=NoCheckInNS) : return FACT(
@@ -150,7 +165,7 @@ def F_{data_name}(statut, fv=NoCheckInNS) : return FACT(
         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)"),
         ),
     STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
-        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"),
+        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"),
         ),
     SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
         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"),
@@ -165,21 +180,17 @@ def F_{data_name}(statut, fv=NoCheckInNS) : return FACT(
     SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
         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"),
         ),
-    TEMPLATE_DATA =  BLOC (condition = " FROM in ( 'Template', ) ",
-        Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "AnalysisPrinter", into=("AnalysisPrinter", "AnalysisSaver", "AnalysisPrinterAndSaver")),
-        AnalysisPrinter = BLOC (condition = " Template == 'AnalysisPrinter' ",
-            ValueTemplate = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "import numpy\\nxa=numpy.ravel(ADD.get('Analysis')[-1])\\nprint('Analysis:',xa)" ),
-            ),
-        AnalysisSaver = BLOC (condition = " Template == 'AnalysisSaver' ",
-            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)" ),
-            ),
-        AnalysisPrinterAndSaver = BLOC (condition = " Template == 'AnalysisPrinterAndSaver' ",
-            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)" ),
-            ),
-        ),
+"""+\
+"""    TEMPLATE_DATA =  BLOC (condition = " FROM in ( 'Template', ) ",
+        Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "AnalysisPrinter", into=(%s)),
+"""%(upa_list,)+\
+upa_cont+\
+"""        ),
     )
 """
 
+# --------------------------------------
+
 init_method = """
 def F_InitChoice() : return  ("Background",
                               "BackgroundError",
@@ -200,7 +211,7 @@ def F_Init(statut) : return FACT(statut = statut,
 
 assim_data_method = """
 def {assim_name}InNS(filename):
-    if os.path.exists(filename):
+    if os.path.isfile(filename):
         fc = open(filename, 'r').readlines()
         cr = re.compile("^{assim_name}[\s]*=")
         for ln in fc:
@@ -235,6 +246,8 @@ observers_choice = """
             ),
         ),"""
 
+# --------------------------------------
+
 from daCore.Templates import ObserverTemplates
 observers_list = ObserverTemplates.keys_in_presentation_order()
 observers_list = '"%s"'%str('", "'.join(observers_list))
@@ -247,6 +260,7 @@ for k in ObserverTemplates.keys_in_presentation_order():
         ObserverTemplates.getdoc(k, "en_EN"),
         )
     observers_cont += """                    ),\n"""
+
 observers_method = """
 def F_ObserverTemplate() : return BLOC(condition = " NodeType == 'Template' ",
                 Template = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "ValuePrinter", into=(%s)),
@@ -258,9 +272,11 @@ def F_Observers(statut) : return FACT(
     )
 """%(observers_list,observers_cont)
 
+# --------------------------------------
+
 algo_choices = """
 def AlgorithmParametersInNS(filename):
-    if os.path.exists(filename):
+    if os.path.isfile(filename):
         fc = open(filename, 'r').readlines()
         cr = re.compile("^AlgorithmParameters[\s]*=")
         for ln in fc:
@@ -282,6 +298,8 @@ one_algo_choices = """
         statut="f",
 {algo_parameters}        ),"""
 
+# --------------------------------------
+
 assim_study = """
 def F_variables(statut) : return FACT(
     statut=statut,
@@ -306,8 +324,8 @@ ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
     Observation         = F_Observation("o", ObservationInNS),
     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
-    ObservationOperator = F_ObservationOperator("o"),
-    EvolutionModel      = F_EvolutionModel("f"),
+    ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
+    EvolutionModel      = F_EvolutionModel("f", EvolutionModelInNS),
     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
     ControlInput        = F_ControlInput("f"),
     UserDataInit        = F_Init("f"),
@@ -329,8 +347,8 @@ OPTIMIZATION_STUDY = PROC(nom="OPTIMIZATION_STUDY",
     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
     Observation         = F_Observation("o", ObservationInNS),
     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
-    ObservationOperator = F_ObservationOperator("o"),
-    EvolutionModel      = F_EvolutionModel("f"),
+    ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
+    EvolutionModel      = F_EvolutionModel("f", EvolutionModelInNS),
     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
     ControlInput        = F_ControlInput("f"),
     UserDataInit        = F_Init("f"),
@@ -352,8 +370,8 @@ REDUCTION_STUDY = PROC(nom="REDUCTION_STUDY",
     BackgroundError     = F_BackgroundError("o", BackgroundErrorInNS),
     Observation         = F_Observation("o", ObservationInNS),
     ObservationError    = F_ObservationError("o", ObservationErrorInNS),
-    ObservationOperator = F_ObservationOperator("o"),
-    EvolutionModel      = F_EvolutionModel("f"),
+    ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
+    EvolutionModel      = F_EvolutionModel("f", EvolutionModelInNS),
     EvolutionError      = F_EvolutionError("f", EvolutionErrorInNS),
     ControlInput        = F_ControlInput("f"),
     UserDataInit        = F_Init("f"),
@@ -376,7 +394,7 @@ CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
     BackgroundError     = F_BackgroundError("f", BackgroundErrorInNS),
     Observation         = F_Observation("f", ObservationInNS),
     ObservationError    = F_ObservationError("f", ObservationErrorInNS),
-    ObservationOperator = F_ObservationOperator("o"),
+    ObservationOperator = F_ObservationOperator("o", ObservationOperatorInNS),
     UserDataInit        = F_Init("f"),
     Observers           = F_Observers("f")
     )
@@ -410,10 +428,10 @@ algos_names = ""
 optim_names = ""
 reduc_names = ""
 check_names = ""
-decl_algos  = ""
-algal_names = ""
+task_names  = ""
+adao_all_names = ""
 assim_study_object = daCore.Aidsm.Aidsm()
-algos_list = assim_study_object.get_available_algorithms()
+algos_list = assim_study_object._Aidsm__get_available_algorithms()
 del assim_study_object
 for algo_name in algos_list:
   if algo_name in infos.AssimAlgos:
@@ -428,9 +446,12 @@ for algo_name in algos_list:
   if algo_name in infos.CheckAlgos:
     logging.debug("A checking algorithm is found: " + algo_name)
     check_names += "\"" + algo_name + "\", "
-  if algo_name in infos.AssimAlgos+infos.OptimizationAlgos+infos.ReductionAlgos+infos.CheckAlgos:
+  if algo_name in infos.TaskAlgos:
+    logging.debug("A task algorithm is found: " + algo_name)
+    task_names += "\"" + algo_name + "\", "
+  if algo_name in infos.AssimAlgos+infos.OptimizationAlgos+infos.ReductionAlgos+infos.CheckAlgos+infos.TaskAlgos:
     # Pour filtrer sur les algorithmes vraiment interfacés, car il peut y en avoir moins que "algos_list"
-    algal_names += "\"" + algo_name + "\", "
+    adao_all_names += "\"" + algo_name + "\", "
 
 # Step 1: A partir des infos, on crée les fonctions qui vont permettre
 # d'entrer les données utilisateur
@@ -455,7 +476,6 @@ for data_input_name in infos.DataTypeDict:
     'data_into'    : data_into,
     'data_default' : data_default,
     'ms_default'   : ms_default,
-    #~ 'algos_names'  : algal_names,
     }))
 
 # Step 2: On crée les fonctions qui permettent de rentrer les données des algorithmes
@@ -505,7 +525,6 @@ for opt_name in infos.OptDict:
     'data_into'    : data_into,
     'data_default' : data_default,
     'ms_default'   : ms_default,
-    #~ 'algos_names'  : algal_names,
     }))
 
 # Step 3bis: On ajoute la méthode optionnelle init
@@ -522,7 +541,7 @@ mem_file.write(unicode(observers_method, 'utf-8').format(**{
   }))
 
 # Step 5: On ajoute les choix algorithmiques
-all_names = eval((algal_names))
+all_names = eval((adao_all_names))
 all_algo_defaults = ""
 for algo in all_names:
     assim_study_object = daCore.Aidsm.Aidsm()
@@ -548,7 +567,7 @@ for algo in all_names:
         elif pt is float:
             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)
         elif pt is bool:
-            algo_parameters += """        %s = SIMP(statut="f", typ="I", min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
+            algo_parameters += """        %s = SIMP(statut="f", typ="I", into=(0, 1), min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
         elif pt is str and "listval" in par_dict[pn]:
             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)
         elif pt is tuple and "listval" in par_dict[pn]:
@@ -569,7 +588,7 @@ mem_file.write(unicode(assim_study, 'utf-8').format(**{
   'optim_names':optim_names,
   'reduc_names':reduc_names,
   'check_names':check_names,
-  'decl_algos':decl_algos,
+  'task_names':task_names,
   }))
 
 # Final step: On écrit le fichier