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