Salome HOME
Documentation corrections and improvements for outputs
[modules/adao.git] / src / daEficas / generator_adao.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2008-2015 EDF R&D
3 #
4 # This file is part of SALOME ADAO module
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #
22 # Author: AndrĂ© Ribes, andre.ribes@edf.fr, EDF R&D
23
24 from generator.generator_python import PythonGenerator
25 import traceback
26 import logging
27
28 def entryPoint():
29    """
30       Retourne les informations necessaires pour le chargeur de plugins
31
32       Ces informations sont retournees dans un dictionnaire
33    """
34    return {
35         # Le nom du plugin
36         'name' : 'adao',
37         # La factory pour creer une instance du plugin
38           'factory' : AdaoGenerator,
39           }
40
41 class AdaoGenerator(PythonGenerator):
42
43   def __init__(self,cr=None):
44     PythonGenerator.__init__(self, cr)
45     self.dictMCVal={}
46     self.text_comm = ""
47     self.text_da = ""
48     self.text_da_status = False
49     self.logger = logging.getLogger('ADAO EFICAS GENERATOR')
50     self.logger.setLevel(logging.INFO)
51     ch = logging.StreamHandler()
52     ch.setLevel(logging.INFO)
53     formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
54     ch.setFormatter(formatter)
55     self.logger.addHandler(ch)
56
57   def gener(self,obj,format='brut',config=None):
58     self.logger.debug("method gener called")
59     self.text_comm = PythonGenerator.gener(self, obj, format, config)
60     for key, value in self.dictMCVal.iteritems():
61       self.logger.debug("dictMCVAl %s %s" % (key,value))
62
63     try :
64       self.text_da_status = False
65       self.generate_da()
66       self.text_da_status = True
67     except:
68       self.logger.info("Case is not correct, python command file for YACS schema generation cannot be created")
69       self.logger.debug(self.text_da)
70       self.dictMCVal = {}
71       traceback.print_exc()
72     return self.text_comm
73
74   def writeDefault(self, fn):
75     if self.text_da_status:
76       self.logger.debug("write adao python command file")
77       filename = fn[:fn.rfind(".")] + '.py'
78       f = open( str(filename), 'wb')
79       f.write( self.text_da )
80       f.close()
81
82   def generMCSIMP(self,obj) :
83     """
84     Convertit un objet MCSIMP en texte python
85     """
86     clef=""
87     for i in obj.get_genealogie() :
88       clef=clef+"__"+i
89     self.dictMCVal[clef]=obj.valeur
90
91     s=PythonGenerator.generMCSIMP(self,obj)
92     return s
93
94   def generate_da(self):
95   
96     if "__CHECKING_STUDY__Study_name" in self.dictMCVal.keys():
97       self.type_of_study = "CHECKING_STUDY"
98     else:
99       self.type_of_study = "ASSIMILATION_STUDY"
100         
101     self.text_da += "#-*-coding:iso-8859-1-*- \n"
102     self.text_da += "study_config = {} \n"
103
104     # Extraction de Study_type
105     self.text_da += "study_config['StudyType'] = '" + self.type_of_study + "'\n"
106     # Extraction de Study_name
107     self.text_da += "study_config['Name'] = '" + self.dictMCVal["__"+self.type_of_study+"__Study_name"] + "'\n"
108     # Extraction de Debug
109     if "__"+self.type_of_study+"__Debug" in self.dictMCVal.keys():
110       self.text_da += "study_config['Debug'] = '" + str(self.dictMCVal["__"+self.type_of_study+"__Debug"]) + "'\n"
111     else:
112       self.text_da += "study_config['Debug'] = '0'\n"
113     # Extraction de Algorithm
114     self.text_da += "study_config['Algorithm'] = '" + self.dictMCVal["__"+self.type_of_study+"__Algorithm"] + "'\n"
115
116     if "__"+self.type_of_study+"__Background__INPUT_TYPE" in self.dictMCVal.keys():
117       self.add_data("Background")
118     if "__"+self.type_of_study+"__BackgroundError__INPUT_TYPE" in self.dictMCVal.keys():
119       self.add_data("BackgroundError")
120     if "__"+self.type_of_study+"__Observation__INPUT_TYPE" in self.dictMCVal.keys():
121       self.add_data("Observation")
122     if "__"+self.type_of_study+"__ObservationError__INPUT_TYPE" in self.dictMCVal.keys():
123       self.add_data("ObservationError")
124     if "__"+self.type_of_study+"__CheckingPoint__INPUT_TYPE" in self.dictMCVal.keys():
125       self.add_data("CheckingPoint")
126     if "__"+self.type_of_study+"__ObservationOperator__INPUT_TYPE" in self.dictMCVal.keys():
127       self.add_data("ObservationOperator")
128     if "__"+self.type_of_study+"__EvolutionModel__INPUT_TYPE" in self.dictMCVal.keys():
129       self.add_data("EvolutionModel")
130     if "__"+self.type_of_study+"__EvolutionError__INPUT_TYPE" in self.dictMCVal.keys():
131       self.add_data("EvolutionError")
132     if "__"+self.type_of_study+"__ControlInput__INPUT_TYPE" in self.dictMCVal.keys():
133       self.add_data("ControlInput")
134
135     self.add_variables()
136     # Parametres optionnels
137
138     # Extraction du Study_repertory
139     if "__"+self.type_of_study+"__Study_repertory" in self.dictMCVal.keys():
140       self.text_da += "study_config['Repertory'] = '" + self.dictMCVal["__"+self.type_of_study+"__Study_repertory"] + "'\n"
141     # Extraction de AlgorithmParameters
142     if "__"+self.type_of_study+"__AlgorithmParameters__INPUT_TYPE" in self.dictMCVal.keys():
143       self.add_algorithm_parameters()
144     # Extraction de UserPostAnalysis
145     if "__"+self.type_of_study+"__UserPostAnalysis__FROM" in self.dictMCVal.keys():
146       self.add_UserPostAnalysis()
147     if "__"+self.type_of_study+"__UserDataInit__INIT_FILE" in self.dictMCVal.keys():
148       self.add_init()
149     if "__"+self.type_of_study+"__Observers__SELECTION" in self.dictMCVal.keys():
150       self.add_observers()
151
152   def add_data(self, data_name):
153
154     # Extraction des donnĂ©es
155     search_text = "__"+self.type_of_study+"__" + data_name + "__"
156     data_type = self.dictMCVal[search_text + "INPUT_TYPE"]
157     search_type = search_text + data_type + "__data__"
158     from_type = self.dictMCVal[search_type + "FROM"]
159     data = ""
160     if from_type == "String":
161       data = self.dictMCVal[search_type + "STRING_DATA__STRING"]
162     elif from_type == "Script":
163       data = self.dictMCVal[search_type + "SCRIPT_DATA__SCRIPT_FILE"]
164     elif from_type == "ScriptWithSwitch":
165       data = self.dictMCVal[search_type + "SCRIPTWITHSWITCH_DATA__SCRIPTWITHSWITCH_FILE"]
166     elif from_type == "ScriptWithFunctions":
167       data = self.dictMCVal[search_type + "SCRIPTWITHFUNCTIONS_DATA__SCRIPTWITHFUNCTIONS_FILE"]
168     elif from_type == "ScriptWithOneFunction":
169       data = self.dictMCVal[search_type + "SCRIPTWITHONEFUNCTION_DATA__SCRIPTWITHONEFUNCTION_FILE"]
170     elif from_type == "FunctionDict":
171       data = self.dictMCVal[search_type + "FUNCTIONDICT_DATA__FUNCTIONDICT_FILE"]
172     else:
173       raise Exception('From Type unknown', from_type)
174
175     if from_type == "String" or from_type == "Script":
176       self.text_da += data_name + "_config = {}\n"
177       self.text_da += data_name + "_config['Type'] = '" + data_type + "'\n"
178       self.text_da += data_name + "_config['From'] = '" + from_type + "'\n"
179       self.text_da += data_name + "_config['Data'] = '" + data      + "'\n"
180       if search_text+"Stored" in self.dictMCVal.keys():
181         self.text_da += data_name + "_config['Stored'] = '" +  str(self.dictMCVal[search_text+"Stored"])  + "'\n"
182       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
183
184     if from_type == "ScriptWithSwitch":
185       self.text_da += data_name + "_ScriptWithSwitch = {}\n"
186       self.text_da += data_name + "_ScriptWithSwitch['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"
187       self.text_da += data_name + "_ScriptWithSwitch['Script'] = {}\n"
188       self.text_da += data_name + "_ScriptWithSwitch['Script']['Direct'] = '"  + data + "'\n"
189       self.text_da += data_name + "_ScriptWithSwitch['Script']['Tangent'] = '" + data + "'\n"
190       self.text_da += data_name + "_ScriptWithSwitch['Script']['Adjoint'] = '" + data + "'\n"
191       self.text_da += data_name + "_config = {}\n"
192       self.text_da += data_name + "_config['Type'] = 'Function'\n"
193       self.text_da += data_name + "_config['From'] = 'ScriptWithSwitch'\n"
194       self.text_da += data_name + "_config['Data'] = " + data_name + "_ScriptWithSwitch\n"
195       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
196
197     if from_type == "ScriptWithFunctions":
198       self.text_da += data_name + "_ScriptWithFunctions = {}\n"
199       self.text_da += data_name + "_ScriptWithFunctions['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"
200       self.text_da += data_name + "_ScriptWithFunctions['Script'] = {}\n"
201       self.text_da += data_name + "_ScriptWithFunctions['Script']['Direct'] = '"  + data + "'\n"
202       self.text_da += data_name + "_ScriptWithFunctions['Script']['Tangent'] = '" + data + "'\n"
203       self.text_da += data_name + "_ScriptWithFunctions['Script']['Adjoint'] = '" + data + "'\n"
204       self.text_da += data_name + "_config = {}\n"
205       self.text_da += data_name + "_config['Type'] = 'Function'\n"
206       self.text_da += data_name + "_config['From'] = 'ScriptWithFunctions'\n"
207       self.text_da += data_name + "_config['Data'] = " + data_name + "_ScriptWithFunctions\n"
208       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
209
210     if from_type == "ScriptWithOneFunction":
211       self.text_da += data_name + "_ScriptWithOneFunction = {}\n"
212       self.text_da += data_name + "_ScriptWithOneFunction['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"
213       self.text_da += data_name + "_ScriptWithOneFunction['Script'] = {}\n"
214       self.text_da += data_name + "_ScriptWithOneFunction['Script']['Direct'] = '"  + data + "'\n"
215       self.text_da += data_name + "_ScriptWithOneFunction['Script']['Tangent'] = '" + data + "'\n"
216       self.text_da += data_name + "_ScriptWithOneFunction['Script']['Adjoint'] = '" + data + "'\n"
217       self.text_da += data_name + "_ScriptWithOneFunction['DifferentialIncrement'] = " + str(float(self.dictMCVal[search_type + "SCRIPTWITHONEFUNCTION_DATA__DifferentialIncrement"])) + "\n"
218       self.text_da += data_name + "_ScriptWithOneFunction['CenteredFiniteDifference'] = " + str(self.dictMCVal[search_type + "SCRIPTWITHONEFUNCTION_DATA__CenteredFiniteDifference"]) + "\n"
219       if search_type + "SCRIPTWITHONEFUNCTION_DATA__EnableMultiProcessing" in self.dictMCVal.keys():
220         self.text_da += data_name + "_ScriptWithOneFunction['EnableMultiProcessing'] = " + str(self.dictMCVal[search_type + "SCRIPTWITHONEFUNCTION_DATA__EnableMultiProcessing"]) + "\n"
221       self.text_da += data_name + "_config = {}\n"
222       self.text_da += data_name + "_config['Type'] = 'Function'\n"
223       self.text_da += data_name + "_config['From'] = 'ScriptWithOneFunction'\n"
224       self.text_da += data_name + "_config['Data'] = " + data_name + "_ScriptWithOneFunction\n"
225       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
226
227     if from_type == "FunctionDict":
228       self.text_da += data_name + "_FunctionDict = {}\n"
229       self.text_da += data_name + "_FunctionDict['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"
230       self.text_da += data_name + "_FunctionDict['Script'] = {}\n"
231       self.text_da += data_name + "_FunctionDict['Script']['Direct'] = '"  + data + "'\n"
232       self.text_da += data_name + "_FunctionDict['Script']['Tangent'] = '" + data + "'\n"
233       self.text_da += data_name + "_FunctionDict['Script']['Adjoint'] = '" + data + "'\n"
234       self.text_da += data_name + "_config = {}\n"
235       self.text_da += data_name + "_config['Type'] = 'Function'\n"
236       self.text_da += data_name + "_config['From'] = 'FunctionDict'\n"
237       self.text_da += data_name + "_config['Data'] = " + data_name + "_FunctionDict\n"
238       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
239
240   def add_algorithm_parameters(self):
241
242     data_name = "AlgorithmParameters"
243     data_type = "Dict"
244     from_type = self.dictMCVal["__"+self.type_of_study+"__AlgorithmParameters__Dict__data__FROM"]
245     
246     if from_type == "Script":
247       data = self.dictMCVal["__"+self.type_of_study+"__AlgorithmParameters__Dict__data__SCRIPT_DATA__SCRIPT_FILE"]
248       self.text_da += data_name + "_config = {} \n"
249       self.text_da += data_name + "_config['Type'] = '" + data_type + "'\n"
250       self.text_da += data_name + "_config['From'] = '" + from_type + "'\n"
251       self.text_da += data_name + "_config['Data'] = '" + data + "'\n"
252       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
253     
254     if from_type == "String":
255       data = self.dictMCVal["__"+self.type_of_study+"__AlgorithmParameters__Dict__data__STRING_DATA__STRING"]
256       self.text_da += data_name + "_config = {} \n"
257       self.text_da += data_name + "_config['Type'] = '" + data_type + "'\n"
258       self.text_da += data_name + "_config['From'] = '" + from_type + "'\n"
259       self.text_da += data_name + "_config['Data'] = '" + data + "'\n"
260       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
261
262   def add_init(self):
263
264       init_file_data = self.dictMCVal["__"+self.type_of_study+"__UserDataInit__INIT_FILE"]
265       init_target_list = self.dictMCVal["__"+self.type_of_study+"__UserDataInit__TARGET_LIST"]
266
267       self.text_da += "Init_config = {}\n"
268       self.text_da += "Init_config['Type'] = 'Dict'\n"
269       self.text_da += "Init_config['From'] = 'Script'\n"
270       self.text_da += "Init_config['Data'] = '" + init_file_data + "'\n"
271       self.text_da += "Init_config['Target'] = ["
272       if type(init_target_list) is type("str"):
273         self.text_da +=  "'" + init_target_list + "',"
274       else:
275         for target in init_target_list:
276           self.text_da += "'" + target + "',"
277       self.text_da += "]\n"
278       self.text_da += "study_config['UserDataInit'] = Init_config\n"
279
280   def add_UserPostAnalysis(self):
281
282     from_type = self.dictMCVal["__"+self.type_of_study+"__UserPostAnalysis__FROM"]
283     data = ""
284     if from_type == "String":
285       data = self.dictMCVal["__"+self.type_of_study+"__UserPostAnalysis__STRING_DATA__STRING"]
286       self.text_da += "Analysis_config = {}\n"
287       self.text_da += "Analysis_config['From'] = 'String'\n"
288       self.text_da += "Analysis_config['Data'] = \"\"\"" + data + "\"\"\"\n"
289       self.text_da += "study_config['UserPostAnalysis'] = Analysis_config\n"
290     elif from_type == "Script":
291       data = self.dictMCVal["__"+self.type_of_study+"__UserPostAnalysis__SCRIPT_DATA__SCRIPT_FILE"]
292       self.text_da += "Analysis_config = {}\n"
293       self.text_da += "Analysis_config['From'] = 'Script'\n"
294       self.text_da += "Analysis_config['Data'] = '" + data + "'\n"
295       self.text_da += "study_config['UserPostAnalysis'] = Analysis_config\n"
296     elif from_type == "Template":
297       tmpl = self.dictMCVal["__"+self.type_of_study+"__UserPostAnalysis__TEMPLATE_DATA__Template"]
298       data = self.dictMCVal["__"+self.type_of_study+"__UserPostAnalysis__TEMPLATE_DATA__%s__ValueTemplate"%tmpl]
299       self.text_da += "Analysis_config = {}\n"
300       self.text_da += "Analysis_config['From'] = 'String'\n"
301       self.text_da += "Analysis_config['Data'] = \"\"\"" + data + "\"\"\"\n"
302       self.text_da += "study_config['UserPostAnalysis'] = Analysis_config\n"
303     else:
304       raise Exception('From Type unknown', from_type)
305
306   def add_variables(self):
307
308     # Input variables
309     if "__"+self.type_of_study+"__InputVariables__NAMES" in self.dictMCVal.keys():
310       names = []
311       sizes = []
312       if isinstance(self.dictMCVal["__"+self.type_of_study+"__InputVariables__NAMES"], type("")):
313         names.append(self.dictMCVal["__"+self.type_of_study+"__InputVariables__NAMES"])
314       else:
315         names = self.dictMCVal["__"+self.type_of_study+"__InputVariables__NAMES"]
316       if isinstance(self.dictMCVal["__"+self.type_of_study+"__InputVariables__SIZES"], type(1)):
317         sizes.append(self.dictMCVal["__"+self.type_of_study+"__InputVariables__SIZES"])
318       else:
319         sizes = self.dictMCVal["__"+self.type_of_study+"__InputVariables__SIZES"]
320
321       self.text_da += "inputvariables_config = {}\n"
322       self.text_da += "inputvariables_config['Order'] = %s\n" % list(names)
323       for name, size in zip(names, sizes):
324         self.text_da += "inputvariables_config['%s'] = %s\n" % (name,size)
325       self.text_da += "study_config['InputVariables'] = inputvariables_config\n"
326     else:
327       self.text_da += "inputvariables_config = {}\n"
328       self.text_da += "inputvariables_config['Order'] =['adao_default']\n"
329       self.text_da += "inputvariables_config['adao_default'] = -1\n"
330       self.text_da += "study_config['InputVariables'] = inputvariables_config\n"
331
332     # Output variables
333     if "__"+self.type_of_study+"__OutputVariables__NAMES" in self.dictMCVal.keys():
334       names = []
335       sizes = []
336       if isinstance(self.dictMCVal["__"+self.type_of_study+"__OutputVariables__NAMES"], type("")):
337         names.append(self.dictMCVal["__"+self.type_of_study+"__OutputVariables__NAMES"])
338       else:
339         names = self.dictMCVal["__"+self.type_of_study+"__OutputVariables__NAMES"]
340       if isinstance(self.dictMCVal["__"+self.type_of_study+"__OutputVariables__SIZES"], type(1)):
341         sizes.append(self.dictMCVal["__"+self.type_of_study+"__OutputVariables__SIZES"])
342       else:
343         sizes = self.dictMCVal["__"+self.type_of_study+"__OutputVariables__SIZES"]
344
345       self.text_da += "outputvariables_config = {}\n"
346       self.text_da += "outputvariables_config['Order'] = %s\n" % list(names)
347       for name, size in zip(names, sizes):
348         self.text_da += "outputvariables_config['%s'] = %s\n" % (name,size)
349       self.text_da += "study_config['OutputVariables'] = outputvariables_config\n"
350     else:
351       self.text_da += "outputvariables_config = {}\n"
352       self.text_da += "outputvariables_config['Order'] = ['adao_default']\n"
353       self.text_da += "outputvariables_config['adao_default'] = -1\n"
354       self.text_da += "study_config['OutputVariables'] = outputvariables_config\n"
355
356   def add_observers(self):
357     observers = {}
358     observer = self.dictMCVal["__"+self.type_of_study+"__Observers__SELECTION"]
359     if isinstance(observer, type("")):
360       self.add_observer_in_dict(observer, observers)
361     else:
362       for observer in self.dictMCVal["__"+self.type_of_study+"__Observers__SELECTION"]:
363         self.add_observer_in_dict(observer, observers)
364
365     # Write observers in the python command file
366     number = 2
367     self.text_da += "observers = {}\n"
368     for observer in observers.keys():
369       number += 1
370       self.text_da += "observers[\"" + observer + "\"] = {}\n"
371       self.text_da += "observers[\"" + observer + "\"][\"number\"] = " + str(number) + "\n"
372       self.text_da += "observers[\"" + observer + "\"][\"nodetype\"] = \"" + observers[observer]["nodetype"] + "\"\n"
373       if observers[observer]["nodetype"] == "String":
374         self.text_da += "observers[\"" + observer + "\"][\"String\"] = \"\"\"" + observers[observer]["script"] + "\"\"\"\n"
375       elif observers[observer]["nodetype"] == "Template":
376         self.text_da += "observers[\"" + observer + "\"][\"String\"] = \"\"\"" + observers[observer]["script"] + "\"\"\"\n"
377         self.text_da += "observers[\"" + observer + "\"][\"Template\"] = \"\"\"" + observers[observer]["template"] + "\"\"\"\n"
378       else:
379         self.text_da += "observers[\"" + observer + "\"][\"Script\"] = \"" + observers[observer]["file"] + "\"\n"
380       if "scheduler" in observers[observer].keys():
381         self.text_da += "observers[\"" + observer + "\"][\"scheduler\"] = \"\"\"" + observers[observer]["scheduler"] + "\"\"\"\n"
382       if "info" in observers[observer].keys():
383         self.text_da += "observers[\"" + observer + "\"][\"info\"] = \"\"\"" + observers[observer]["info"] + "\"\"\"\n"
384     self.text_da += "study_config['Observers'] = observers\n"
385
386   def add_observer_in_dict(self, observer, observers):
387     """
388       Add observer in the observers dict.
389     """
390     observers[observer] = {}
391     observers[observer]["name"] = observer
392     observer_eficas_name = "__"+self.type_of_study+"__Observers__" + observer + "__" + observer + "_data__"
393     # NodeType
394     node_type_key_name = observer_eficas_name + "NodeType"
395     observers[observer]["nodetype"] = self.dictMCVal[node_type_key_name]
396
397     # NodeType script/file
398     if observers[observer]["nodetype"] == "String":
399       observers[observer]["script"] = self.dictMCVal[observer_eficas_name + "PythonScript__Value"]
400     elif observers[observer]["nodetype"] == "Template":
401       observers[observer]["nodetype"] = "String"
402       observer_template_key = observer_eficas_name + "ObserverTemplate__"
403       observers[observer]["template"] = self.dictMCVal[observer_template_key + "Template"]
404       observers[observer]["script"]   = self.dictMCVal[observer_template_key + observers[observer]["template"] + "__ValueTemplate"]
405     else:
406       observers[observer]["file"] = self.dictMCVal[observer_eficas_name + "UserFile__Value"]
407
408     # Scheduler
409     scheduler_key_name = observer_eficas_name + "Scheduler"
410     if scheduler_key_name in self.dictMCVal.keys():
411       observers[observer]["scheduler"] = self.dictMCVal[scheduler_key_name]
412
413     # Info
414     info_key_name = observer_eficas_name + "Info"
415     if info_key_name in self.dictMCVal.keys():
416       observers[observer]["info"] = self.dictMCVal[info_key_name]