]> SALOME platform Git repositories - modules/adao.git/blob - bin/AdaoCatalogGenerator.py
Salome HOME
Updating copyright notices
[modules/adao.git] / bin / AdaoCatalogGenerator.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2012  EDF R&D
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
20
21 import logging
22 import traceback
23 import sys
24 import string
25 import StringIO
26
27 logging.basicConfig(level=logging.INFO)
28
29 #----------- Templates Part ---------------#
30 begin_catalog_file = """# -*- coding: utf-8 -*-
31
32 # --------------------------------------------------------
33 # generated by AdaoCatalogGenerator at ${date}
34 # --------------------------------------------------------
35
36 import Accas
37 from Accas import *
38
39 JdC = JDC_CATA (code = 'ADAO',
40                 execmodul = None,
41                 regles = ( AU_MOINS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY'), AU_PLUS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY')),
42                )
43 """
44
45 data_method = """
46 def F_${data_name}(statut) : return FACT(statut = statut,
47                                          FROM = SIMP(statut = "o", typ = "TXM", into=(${data_into}), defaut=${data_default}),
48                                          SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
49
50                                                       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 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 the definition of an internal variable of the same name as the parent concept"),
51                                                      ),
52                                          STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
53
54                                                       STRING = SIMP(statut = "o", typ = "TXM", fr="En attente d'une chaine de caractères entre guillements. Pour construire un vecteur, 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, 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"),
55                                                      ),
56                                          SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
57
58                                                       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"),
59                                                      ),
60                                          SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
61
62                                                       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"),
63                                                      ),
64                                          FUNCTIONDICT_DATA = BLOC ( condition = " FROM in ( 'FunctionDict', ) ",
65
66                                                       FUNCTIONDICT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()), fr="OBSOLETE : conservé pour compatibilité avec la version 6.5, sera supprimé dans le futur", ang="OBSOLETE: keeped for compatibility with the 6.5 version, will be removed in the future"),
67                                                      ),
68                                     )
69 """
70
71 init_method = """
72 def F_InitChoice() : return  ("Background",
73                               "BackgroundError",
74                               "Observation",
75                               "ObservationError",
76                               "ObservationOperator",
77                               "EvolutionModel",
78                               "EvolutionError",
79                               "AlgorithmParameters",
80                               "UserPostAnalysis",
81                              )
82
83 def F_Init(statut) : return FACT(statut = statut,
84                                  INIT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr())),
85                                  TARGET_LIST = SIMP(statut = "o", typ = "TXM", min=1, max="**", into=F_InitChoice(),  validators=(VerifExiste(2))),
86                                 )
87 """
88
89 assim_data_method = """
90 def F_${assim_name}(statut) : return FACT(statut=statut,
91 ${storage}
92                                           INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=(${choices}), defaut=${default_choice}),
93 ${decl_choices}
94                                                 )
95 """
96
97 assim_data_choice = """
98                                                  ${choice_name} = BLOC ( condition = " INPUT_TYPE in ( '${choice_name}', ) ",
99                                                  data = F_${choice_name}("o"),
100                                                  ),
101 """
102
103 observers_choice = """
104                                        ${var_name} = BLOC (condition=" '${var_name}' in set(SELECTION) ",
105                                                   ${var_name}_data = FACT(statut = "o",
106                                                              Scheduler = SIMP(statut = "f", typ = "TXM"),
107                                                              Info      = SIMP(statut = "f", typ = "TXM"),
108                                                              NodeType  = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "", into=("String", "Script")),
109                                                              PythonScript = BLOC (condition = " NodeType == 'String' ",
110                                                                                   Value = SIMP(statut = "o", typ = "TXM")
111                                                                                  ),
112                                                              UserFile = BLOC (condition = " NodeType == 'Script' ",
113                                                                               Value = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()))
114                                                                              )
115                                                                       ),
116                                                           ),
117 """
118
119 observers_method = """
120 def F_Observers(statut) : return FACT(statut=statut,
121                                       SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", validators=NoRepeat(), into=(${choices})),
122 ${decl_choices}
123                                      )
124 """
125
126 assim_study = """
127
128 def F_variables(statut) : return FACT(statut=statut,
129                                       regles = ( MEME_NOMBRE ('NAMES', 'SIZES')),
130                                       NAMES = SIMP(statut="o", typ="TXM", max="**", validators=NoRepeat()),
131                                       SIZES = SIMP(statut="o", typ="I", val_min=1, max="**")
132                                       )
133
134 ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
135                           op=None,
136                           repetable           = "n",
137                           Study_name          = SIMP(statut="o", typ = "TXM"),
138                           Study_repertory     = SIMP(statut="f", typ = "TXM"),
139                           Debug               = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0),
140                           Algorithm           = SIMP(statut="o", typ = "TXM", into=(${algos_names})),
141                           Background          = F_Background("o"),
142                           BackgroundError     = F_BackgroundError("o"),
143                           Observation         = F_Observation("o"),
144                           ObservationError    = F_ObservationError("o"),
145                           ObservationOperator = F_ObservationOperator("o"),
146                           EvolutionModel      = F_EvolutionModel("f"),
147                           EvolutionError      = F_EvolutionError("f"),
148                           AlgorithmParameters = F_AlgorithmParameters("f"),
149                           UserDataInit        = F_Init("f"),
150                           UserPostAnalysis    = F_UserPostAnalysis("f"),
151                           InputVariables      = F_variables("f"),
152                           OutputVariables     = F_variables("f"),
153                           Observers           = F_Observers("f")
154                          )
155
156 CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
157                           op=None,
158                           repetable           = "n",
159                           Study_name          = SIMP(statut="o", typ = "TXM"),
160                           Study_repertory     = SIMP(statut="f", typ = "TXM"),
161                           Debug               = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0),
162                           Algorithm           = SIMP(statut="o", typ = "TXM", into=(${check_names})),
163                           CheckingPoint       = F_CheckingPoint("o"),
164                           ObservationOperator = F_ObservationOperator("o"),
165                           AlgorithmParameters = F_AlgorithmParameters("f"),
166                           UserDataInit        = F_Init("f"),
167                          )
168 """
169
170 begin_catalog_file = string.Template(begin_catalog_file)
171 data_method = string.Template(data_method)
172 assim_data_method = string.Template(assim_data_method)
173 assim_data_choice = string.Template(assim_data_choice)
174 assim_study = string.Template(assim_study)
175 observers_method = string.Template(observers_method)
176 observers_choice = string.Template(observers_choice)
177
178 #----------- End of Templates Part ---------------#
179
180
181
182 #----------- Begin generation script -----------#
183 print "-- Starting AdaoCalatogGenerator.py --"
184
185 try:
186   import daEficas
187   import daYacsSchemaCreator
188   import daCore.AssimilationStudy
189   import daYacsSchemaCreator.infos_daComposant as infos
190 except:
191   logging.fatal("Import of ADAO python modules failed !" +
192                 "\n add ADAO python installation directory in your PYTHONPATH")
193   traceback.print_exc()
194   sys.exit(1)
195
196 def check_args(args):
197   logging.debug("Arguments are :" + str(args))
198   if len(args) != 2:
199     logging.fatal("Bad number of arguments: you have to provide two arguments (%d given)" % (len(args)))
200     sys.exit(1)
201
202 # Parse arguments
203 from optparse import OptionParser
204 usage = "usage: %prog [options] catalog_path catalog_name"
205 version="%prog 0.1"
206 my_parser = OptionParser(usage=usage, version=version)
207 (options, args) = my_parser.parse_args()
208 check_args(args)
209
210 catalog_path =  args[0]
211 catalog_name =  args[1]
212
213 # Generates into a string
214 mem_file = StringIO.StringIO()
215
216 # Start file
217 from time import strftime
218 mem_file.write(begin_catalog_file.substitute(date=strftime("%Y-%m-%d %H:%M:%S")))
219
220 # Step 1: A partir des infos, on crée les fonctions qui vont permettre
221 # d'entrer les données utilisateur
222 for data_input_name in infos.DataTypeDict.keys():
223   logging.debug('A data input Type is found: ' + data_input_name)
224   data_name = data_input_name
225   data_into = ""
226   data_default = ""
227
228   # On récupère les différentes façon d'entrer les données
229   for basic_type in infos.DataTypeDict[data_input_name]:
230     data_into += "\"" + basic_type + "\", "
231
232   # On choisit le défault
233   data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
234
235   mem_file.write(data_method.substitute(data_name    = data_name,
236                                         data_into    = data_into,
237                                         data_default = data_default))
238
239 # Step 2: On crée les fonctions qui permettent de rentrer les données des algorithmes
240 for assim_data_input_name in infos.AssimDataDict.keys():
241   logging.debug("An assimilation algorithm data input is found: " + assim_data_input_name)
242   assim_name = assim_data_input_name
243   storage = ""
244   choices = ""
245   default_choice = ""
246   decl_choices = ""
247   decl_opts = ""
248   if infos.AssimDataDefaultDict[assim_data_input_name] in infos.StoredAssimData:
249     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\"),"
250   for choice in infos.AssimDataDict[assim_data_input_name]:
251     choices += "\"" + choice + "\", "
252     decl_choices += assim_data_choice.substitute(choice_name = choice)
253     if choice in infos.StoredAssimData:
254       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\"),"
255   default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
256
257   mem_file.write(assim_data_method.substitute(assim_name = assim_name,
258                                               storage = storage,
259                                               choices = choices,
260                                               decl_choices = decl_choices,
261                                               default_choice=default_choice))
262
263 # Step 3: On ajoute les fonctions représentant les options possibles
264 for opt_name in infos.OptDict.keys():
265   logging.debug("An optional node is found: " + opt_name)
266   data_name = opt_name
267   data_into = ""
268   data_default = ""
269
270   for choice in infos.OptDict[opt_name]:
271     data_into += "\"" + choice + "\", "
272   data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
273
274   mem_file.write(data_method.substitute(data_name = data_name,
275                                         data_into = data_into,
276                                         data_default = data_default))
277
278 # Step 4: On ajoute la méthode optionnelle init
279 # TODO uniformiser avec le step 3
280 mem_file.write(init_method)
281
282 # Step 5: Add observers
283 decl_choices = ""
284 for obs_var in infos.ObserversList:
285   decl_choices += observers_choice.substitute(var_name=obs_var)
286 mem_file.write(observers_method.substitute(choices = infos.ObserversList,
287                                            decl_choices = decl_choices))
288
289 # Final step: Add algorithm and assim_study
290 algos_names = ""
291 check_names = ""
292 decl_algos  = ""
293
294 assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
295 algos_list = assim_study_object.get_available_algorithms()
296 for algo_name in algos_list:
297   if algo_name in infos.AssimAlgos:
298     logging.debug("An assimilation algorithm is found: " + algo_name)
299     algos_names += "\"" + algo_name + "\", "
300   elif algo_name in infos.CheckAlgos:
301     logging.debug("A checking algorithm is found: " + algo_name)
302     check_names += "\"" + algo_name + "\", "
303   else:
304     logging.debug("This algorithm is not considered: " + algo_name)
305
306 mem_file.write(assim_study.substitute(algos_names=algos_names,
307                                       check_names=check_names,
308                                       decl_algos=decl_algos))
309 # Write file
310 final_file = open(catalog_path + "/" + catalog_name, "wr")
311 final_file.write(mem_file.getvalue())
312 mem_file.close()
313 final_file.close()
314