Salome HOME
Adding checking algorithms environment
[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.INFO)
29
30 #----------- Templates Part ---------------#
31 begin_catalog_file = """# -*- coding: utf-8 -*-
32
33 # --------------------------------------------------------
34 # generated by AdaoCatalogGenerator at ${date}
35 # --------------------------------------------------------
36
37 import Accas
38 from Accas import *
39
40 JdC = JDC_CATA (code = 'ADAO',
41                 execmodul = None,
42                 regles = ( AU_MOINS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY'), AU_PLUS_UN ('ASSIMILATION_STUDY','CHECKING_STUDY')),
43                )
44 """
45
46 data_method = """
47 def F_${data_name}(statut) : return FACT(statut = statut,
48                                          FROM = SIMP(statut = "o", typ = "TXM", into=(${data_into}), defaut=${data_default}),
49                                          SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
50
51                                                       SCRIPT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr())),
52                                                      ),
53                                          STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
54
55                                                       STRING = SIMP(statut = "o", typ = "TXM"),
56                                                      ),
57                                          FUNCTIONDICT_DATA = BLOC ( condition = " FROM in ( 'FunctionDict', ) ",
58
59                                                       FUNCTIONDICT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr())),
60                                                      ),
61                                     )
62 """
63
64 init_method = """
65 def F_InitChoice() : return  ("Background",
66                               "BackgroundError",
67                               "Observation",
68                               "ObservationError",
69                               "ObservationOperator",
70                               "EvolutionModel",
71                               "EvolutionError",
72                               "AlgorithmParameters",
73                               "UserPostAnalysis",
74                              )
75
76 def F_Init(statut) : return FACT(statut = statut,
77                                  INIT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr())),
78                                  TARGET_LIST = SIMP(statut = "o", typ = "TXM", min=1, max="**", into=F_InitChoice(),  validators=(VerifExiste(2))),
79                                 )
80 """
81
82 assim_data_method = """
83 def F_${assim_name}(statut) : return FACT(statut=statut,
84                                           INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=(${choices}), defaut=${default_choice}),
85 ${decl_choices}
86                                                 )
87 """
88
89 assim_data_choice = """
90                                                  ${choice_name} = BLOC ( condition = " INPUT_TYPE in ( '${choice_name}', ) ",
91                                                  data = F_${choice_name}("o"),
92                                                  ),
93 """
94
95 observers_choice = """
96                                        ${var_name} = BLOC (condition=" '${var_name}' in set(SELECTION) ",
97                                                   ${var_name}_data = FACT(statut = "o",
98                                                              Scheduler = SIMP(statut = "f", typ = "TXM"),
99                                                              Info      = SIMP(statut = "f", typ = "TXM"),
100                                                              NodeType  = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "", into=("String", "Script")),
101                                                              PythonScript = BLOC (condition = " NodeType == 'String' ",
102                                                                                   Value = SIMP(statut = "o", typ = "TXM")
103                                                                                  ),
104                                                              UserFile = BLOC (condition = " NodeType == 'Script' ",
105                                                                               Value = SIMP(statut = "o", typ = "FichierNoAbs", validators=(OnlyStr()))
106                                                                              )
107                                                                       ),
108                                                           ),
109 """
110
111 observers_method = """
112 def F_Observers(statut) : return FACT(statut=statut,
113                                       SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", validators=NoRepeat(), into=(${choices})),
114 ${decl_choices}
115                                      )
116 """
117
118 assim_study = """
119
120 def F_variables(statut) : return FACT(statut=statut,
121                                       regles = ( MEME_NOMBRE ('NAMES', 'SIZES')),
122                                       NAMES = SIMP(statut="o", typ="TXM", max="**", validators=NoRepeat()),
123                                       SIZES = SIMP(statut="o", typ="I", val_min=1, max="**")
124                                       )
125
126 ASSIMILATION_STUDY = PROC(nom="ASSIMILATION_STUDY",
127                           op=None,
128                           repetable           = "n",
129                           Study_name          = SIMP(statut="o", typ = "TXM"),
130                           Study_repertory     = SIMP(statut="f", typ = "TXM"),
131                           Debug               = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0),
132                           Algorithm           = SIMP(statut="o", typ = "TXM", into=(${algos_names})),
133                           Background          = F_Background("o"),
134                           BackgroundError     = F_BackgroundError("o"),
135                           Observation         = F_Observation("o"),
136                           ObservationError    = F_ObservationError("o"),
137                           ObservationOperator = F_ObservationOperator("o"),
138                           EvolutionModel      = F_EvolutionModel("f"),
139                           EvolutionError      = F_EvolutionError("f"),
140                           AlgorithmParameters = F_AlgorithmParameters("f"),
141                           UserDataInit        = F_Init("f"),
142                           UserPostAnalysis    = F_UserPostAnalysis("f"),
143                           InputVariables      = F_variables("f"),
144                           OutputVariables     = F_variables("f"),
145                           Observers           = F_Observers("f")
146                          )
147
148 CHECKING_STUDY = PROC(nom="CHECKING_STUDY",
149                           op=None,
150                           repetable           = "n",
151                           Study_name          = SIMP(statut="o", typ = "TXM"),
152                           Study_repertory     = SIMP(statut="f", typ = "TXM"),
153                           Debug               = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0),
154                           Algorithm           = SIMP(statut="o", typ = "TXM", into=(${check_names})),
155                           CheckingPoint       = F_CheckingPoint("o"),
156                           ObservationOperator = F_ObservationOperator("o"),
157                           AlgorithmParameters = F_AlgorithmParameters("f"),
158                           UserDataInit        = F_Init("f"),
159                          )
160 """
161
162 begin_catalog_file = string.Template(begin_catalog_file)
163 data_method = string.Template(data_method)
164 assim_data_method = string.Template(assim_data_method)
165 assim_data_choice = string.Template(assim_data_choice)
166 assim_study = string.Template(assim_study)
167 observers_method = string.Template(observers_method)
168 observers_choice = string.Template(observers_choice)
169
170 #----------- End of Templates Part ---------------#
171
172
173
174 #----------- Begin generation script -----------#
175 print "-- Starting AdaoCalatogGenerator.py --"
176
177 try:
178   import daEficas
179   import daYacsSchemaCreator
180   import daCore.AssimilationStudy
181   import daYacsSchemaCreator.infos_daComposant as infos
182 except:
183   logging.fatal("Import of ADAO python modules failed !" +
184                 "\n add ADAO python installation directory in your PYTHONPATH")
185   traceback.print_exc()
186   sys.exit(1)
187
188 def check_args(args):
189   logging.debug("Arguments are :" + str(args))
190   if len(args) != 2:
191     logging.fatal("Bad number of arguments: you have to provide two arguments (%d given)" % (len(args)))
192     sys.exit(1)
193
194 # Parse arguments
195 from optparse import OptionParser
196 usage = "usage: %prog [options] catalog_path catalog_name"
197 version="%prog 0.1"
198 my_parser = OptionParser(usage=usage, version=version)
199 (options, args) = my_parser.parse_args()
200 check_args(args)
201
202 catalog_path =  args[0]
203 catalog_name =  args[1]
204
205 # Generates into a string
206 mem_file = StringIO.StringIO()
207
208 # Start file
209 from time import strftime
210 mem_file.write(begin_catalog_file.substitute(date=strftime("%Y-%m-%d %H:%M:%S")))
211
212 # Step 1: A partir des infos, on crée les fonctions qui vont permettre
213 # d'entrer les données utilisateur
214 for data_input_name in infos.DataTypeDict.keys():
215   logging.debug('A data input Type is found: ' + data_input_name)
216   data_name = data_input_name
217   data_into = ""
218   data_default = ""
219
220   # On récupère les différentes façon d'entrer les données
221   for basic_type in infos.DataTypeDict[data_input_name]:
222     data_into += "\"" + basic_type + "\", "
223
224   # On choisit le défault
225   data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
226
227   mem_file.write(data_method.substitute(data_name    = data_name,
228                                         data_into    = data_into,
229                                         data_default = data_default))
230
231 # Step 2: On crée les fonctions qui permettent de rentrer les données des algorithmes
232 for assim_data_input_name in infos.AssimDataDict.keys():
233   logging.debug("An assimilation algorithm data input is found: " + assim_data_input_name)
234   assim_name = assim_data_input_name
235   choices = ""
236   default_choice = ""
237   decl_choices = ""
238   decl_opts = ""
239   for choice in infos.AssimDataDict[assim_data_input_name]:
240     choices += "\"" + choice + "\", "
241     decl_choices += assim_data_choice.substitute(choice_name = choice)
242   default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
243
244   mem_file.write(assim_data_method.substitute(assim_name = assim_name,
245                                               choices = choices,
246                                               decl_choices = decl_choices,
247                                               default_choice=default_choice))
248
249 # Step 3: On ajoute les fonctions représentant les options possibles
250 for opt_name in infos.OptDict.keys():
251   logging.debug("An optional node is found: " + opt_name)
252   data_name = opt_name
253   data_into = ""
254   data_default = ""
255
256   for choice in infos.OptDict[opt_name]:
257     data_into += "\"" + choice + "\", "
258   data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
259
260   mem_file.write(data_method.substitute(data_name = data_name,
261                                         data_into = data_into,
262                                         data_default = data_default))
263
264 # Step 4: On ajoute la méthode optionnelle init
265 # TODO uniformiser avec le step 3
266 mem_file.write(init_method)
267
268 # Step 5: Add observers
269 decl_choices = ""
270 for obs_var in infos.ObserversList:
271   decl_choices += observers_choice.substitute(var_name=obs_var)
272 mem_file.write(observers_method.substitute(choices = infos.ObserversList,
273                                            decl_choices = decl_choices))
274
275 # Final step: Add algorithm and assim_study
276 algos_names = ""
277 check_names = ""
278 decl_algos  = ""
279
280 assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
281 algos_list = assim_study_object.get_available_algorithms()
282 for algo_name in algos_list:
283   if algo_name in infos.AssimAlgos:
284     logging.debug("An assimilation algorithm is found: " + algo_name)
285     algos_names += "\"" + algo_name + "\", "
286   elif algo_name in infos.CheckAlgos:
287     logging.debug("A checking algorithm is found: " + algo_name)
288     check_names += "\"" + algo_name + "\", "
289   else:
290     logging.debug("This algorithm is not considered: " + algo_name)
291
292 mem_file.write(assim_study.substitute(algos_names=algos_names,
293                                       check_names=check_names,
294                                       decl_algos=decl_algos))
295 # Write file
296 final_file = open(catalog_path + "/" + catalog_name, "wr")
297 final_file.write(mem_file.getvalue())
298 mem_file.close()
299 final_file.close()
300