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