Salome HOME
d31df645ff70c466ed6bb562851bd3872523eedd
[modules/adao.git] / src / daEficas / generator_adao.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2010-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 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       print "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     self.text_da += "#-*-coding:iso-8859-1-*- \n"
95     self.text_da += "study_config = {} \n"
96
97     # Extraction de Study_name
98     self.text_da += "study_config['Name'] = '" + self.dictMCVal["__ASSIMILATION_STUDY__Study_name"] + "'\n"
99     # Extraction de Debug
100     self.text_da += "study_config['Debug'] = '" + str(self.dictMCVal["__ASSIMILATION_STUDY__Debug"]) + "'\n"
101     # Extraction de Algorithm
102     self.text_da += "study_config['Algorithm'] = '" + self.dictMCVal["__ASSIMILATION_STUDY__Algorithm"] + "'\n"
103
104     self.add_data("Background")
105     self.add_data("BackgroundError")
106     self.add_data("Observation")
107     self.add_data("ObservationError")
108     self.add_data("ObservationOperator")
109
110     self.add_variables()
111     # Parametres optionnels
112
113     # Extraction du Study_repertory
114     if "__ASSIMILATION_STUDY__Study_repertory" in self.dictMCVal.keys():
115       self.text_da += "study_config['Repertory'] = '" + self.dictMCVal["__ASSIMILATION_STUDY__Study_repertory"] + "'\n"
116     # Extraction de AlgorithmParameters
117     if "__ASSIMILATION_STUDY__AlgorithmParameters__INPUT_TYPE" in self.dictMCVal.keys():
118       self.add_algorithm_parameters()
119     # Extraction de UserPostAnalysis
120     if "__ASSIMILATION_STUDY__UserPostAnalysis__FROM" in self.dictMCVal.keys():
121       self.add_UserPostAnalysis()
122     if "__ASSIMILATION_STUDY__UserDataInit__INIT_FILE" in self.dictMCVal.keys():
123       self.add_init()
124     if "__ASSIMILATION_STUDY__Observers__SELECTION" in self.dictMCVal.keys():
125       self.add_observers()
126
127   def add_data(self, data_name):
128
129     # Extraction des donnĂ©es
130     search_text = "__ASSIMILATION_STUDY__" + data_name + "__"
131     data_type = self.dictMCVal[search_text + "INPUT_TYPE"]
132     search_type = search_text + data_type + "__data__"
133     from_type = self.dictMCVal[search_type + "FROM"]
134     data = ""
135     if from_type == "String":
136       data = self.dictMCVal[search_type + "STRING_DATA__STRING"]
137     elif from_type == "Script":
138       data = self.dictMCVal[search_type + "SCRIPT_DATA__SCRIPT_FILE"]
139     elif from_type == "FunctionDict":
140       data = self.dictMCVal[search_type + "FUNCTIONDICT_DATA__FUNCTIONDICT_FILE"]
141     else:
142       raise Exception('From Type unknown', from_type)
143
144     if from_type == "String" or from_type == "Script":
145       self.text_da += data_name + "_config = {}\n"
146       self.text_da += data_name + "_config['Type'] = '" + data_type + "'\n"
147       self.text_da += data_name + "_config['From'] = '" + from_type + "'\n"
148       self.text_da += data_name + "_config['Data'] = '" + data      + "'\n"
149       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
150
151     if from_type == "FunctionDict":
152       self.text_da += data_name + "_FunctionDict = {}\n"
153       self.text_da += data_name + "_FunctionDict['Function'] = ['Direct', 'Tangent', 'Adjoint']\n"
154       self.text_da += data_name + "_FunctionDict['Script'] = {}\n"
155       self.text_da += data_name + "_FunctionDict['Script']['Direct'] = '"  + data + "'\n"
156       self.text_da += data_name + "_FunctionDict['Script']['Tangent'] = '" + data + "'\n"
157       self.text_da += data_name + "_FunctionDict['Script']['Adjoint'] = '" + data + "'\n"
158       self.text_da += data_name + "_config = {}\n"
159       self.text_da += data_name + "_config['Type'] = 'Function'\n"
160       self.text_da += data_name + "_config['From'] = 'FunctionDict'\n"
161       self.text_da += data_name + "_config['Data'] = " + data_name + "_FunctionDict\n"
162       self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
163
164   def add_algorithm_parameters(self):
165
166     data_name = "AlgorithmParameters"
167     data_type = "Dict"
168     from_type = "Script"
169     data = self.dictMCVal["__ASSIMILATION_STUDY__AlgorithmParameters__Dict__data__SCRIPT_DATA__SCRIPT_FILE"]
170
171     self.text_da += data_name + "_config = {} \n"
172     self.text_da += data_name + "_config['Type'] = '" + data_type + "'\n"
173     self.text_da += data_name + "_config['From'] = '" + from_type + "'\n"
174     self.text_da += data_name + "_config['Data'] = '" + data + "'\n"
175     self.text_da += "study_config['" + data_name + "'] = " + data_name + "_config\n"
176
177   def add_init(self):
178
179       init_file_data = self.dictMCVal["__ASSIMILATION_STUDY__UserDataInit__INIT_FILE"]
180       init_target_list = self.dictMCVal["__ASSIMILATION_STUDY__UserDataInit__TARGET_LIST"]
181
182       self.text_da += "Init_config = {}\n"
183       self.text_da += "Init_config['Type'] = 'Dict'\n"
184       self.text_da += "Init_config['From'] = 'Script'\n"
185       self.text_da += "Init_config['Data'] = '" + init_file_data + "'\n"
186       self.text_da += "Init_config['Target'] = ["
187       if type(init_target_list) is type("str"):
188         self.text_da +=  "'" + init_target_list + "',"
189       else:
190         for target in init_target_list:
191           self.text_da += "'" + target + "',"
192       self.text_da += "]\n"
193       self.text_da += "study_config['UserDataInit'] = Init_config\n"
194
195   def add_UserPostAnalysis(self):
196
197     from_type = self.dictMCVal["__ASSIMILATION_STUDY__UserPostAnalysis__FROM"]
198     data = ""
199     if from_type == "String":
200       data = self.dictMCVal["__ASSIMILATION_STUDY__UserPostAnalysis__STRING_DATA__STRING"]
201       self.text_da += "Analysis_config = {}\n"
202       self.text_da += "Analysis_config['From'] = 'String'\n"
203       self.text_da += "Analysis_config['Data'] = \"\"\"" + data + "\"\"\"\n"
204       self.text_da += "study_config['UserPostAnalysis'] = Analysis_config\n"
205     elif from_type == "Script":
206       data = self.dictMCVal["__ASSIMILATION_STUDY__UserPostAnalysis__SCRIPT_DATA__SCRIPT_FILE"]
207       self.text_da += "Analysis_config = {}\n"
208       self.text_da += "Analysis_config['From'] = 'Script'\n"
209       self.text_da += "Analysis_config['Data'] = '" + data + "'\n"
210       self.text_da += "study_config['UserPostAnalysis'] = Analysis_config\n"
211     else:
212       raise Exception('From Type unknown', from_type)
213
214   def add_variables(self):
215
216     # Input variables
217     if "__ASSIMILATION_STUDY__InputVariables__NAMES" in self.dictMCVal.keys():
218       names = []
219       sizes = []
220       if isinstance(self.dictMCVal["__ASSIMILATION_STUDY__InputVariables__NAMES"], type("")):
221         names.append(self.dictMCVal["__ASSIMILATION_STUDY__InputVariables__NAMES"])
222       else:
223         names = self.dictMCVal["__ASSIMILATION_STUDY__InputVariables__NAMES"]
224       if isinstance(self.dictMCVal["__ASSIMILATION_STUDY__InputVariables__SIZES"], type(1)):
225         sizes.append(self.dictMCVal["__ASSIMILATION_STUDY__InputVariables__SIZES"])
226       else:
227         sizes = self.dictMCVal["__ASSIMILATION_STUDY__InputVariables__SIZES"]
228
229       self.text_da += "inputvariables_config = {}\n"
230       self.text_da += "inputvariables_config['Order'] = %s\n" % list(names)
231       for name, size in zip(names, sizes):
232         self.text_da += "inputvariables_config['%s'] = %s\n" % (name,size)
233       self.text_da += "study_config['InputVariables'] = inputvariables_config\n"
234     else:
235       self.text_da += "inputvariables_config = {}\n"
236       self.text_da += "inputvariables_config['Order'] =['adao_default']\n"
237       self.text_da += "inputvariables_config['adao_default'] = -1\n"
238       self.text_da += "study_config['InputVariables'] = inputvariables_config\n"
239
240     # Output variables
241     if "__ASSIMILATION_STUDY__OutputVariables__NAMES" in self.dictMCVal.keys():
242       names = []
243       sizes = []
244       if isinstance(self.dictMCVal["__ASSIMILATION_STUDY__OutputVariables__NAMES"], type("")):
245         names.append(self.dictMCVal["__ASSIMILATION_STUDY__OutputVariables__NAMES"])
246       else:
247         names = self.dictMCVal["__ASSIMILATION_STUDY__OutputVariables__NAMES"]
248       if isinstance(self.dictMCVal["__ASSIMILATION_STUDY__OutputVariables__SIZES"], type(1)):
249         sizes.append(self.dictMCVal["__ASSIMILATION_STUDY__OutputVariables__SIZES"])
250       else:
251         sizes = self.dictMCVal["__ASSIMILATION_STUDY__OutputVariables__SIZES"]
252
253       self.text_da += "outputvariables_config = {}\n"
254       self.text_da += "outputvariables_config['Order'] = %s\n" % list(names)
255       for name, size in zip(names, sizes):
256         self.text_da += "outputvariables_config['%s'] = %s\n" % (name,size)
257       self.text_da += "study_config['OutputVariables'] = outputvariables_config\n"
258     else:
259       self.text_da += "outputvariables_config = {}\n"
260       self.text_da += "outputvariables_config['Order'] = ['adao_default']\n"
261       self.text_da += "outputvariables_config['adao_default'] = -1\n"
262       self.text_da += "study_config['OutputVariables'] = outputvariables_config\n"
263
264   def add_observers(self):
265     observers = {}
266     observer = self.dictMCVal["__ASSIMILATION_STUDY__Observers__SELECTION"]
267     if isinstance(observer, type("")):
268       self.add_observer_in_dict(observer, observers)
269     else:
270       for observer in self.dictMCVal["__ASSIMILATION_STUDY__Observers__SELECTION"]:
271         self.add_observer_in_dict(observer, observers)
272
273     # Write observers in the python command file
274     number = 1
275     self.text_da += "observers = {}\n"
276     for observer in observers.keys():
277       number += 1
278       self.text_da += "observers[\"" + observer + "\"] = {}\n"
279       self.text_da += "observers[\"" + observer + "\"][\"number\"] = " + str(number) + "\n"
280       self.text_da += "observers[\"" + observer + "\"][\"nodetype\"] = \"" + observers[observer]["nodetype"] + "\"\n"
281       if observers[observer]["nodetype"] == "String":
282         self.text_da += "observers[\"" + observer + "\"][\"String\"] = \"\"\"" + observers[observer]["script"] + "\"\"\"\n"
283       else:
284         self.text_da += "observers[\"" + observer + "\"][\"Script\"] = \"" + observers[observer]["file"] + "\"\n"
285       if "scheduler" in observers[observer].keys():
286         self.text_da += "observers[\"" + observer + "\"][\"scheduler\"] = \"\"\"" + observers[observer]["scheduler"] + "\"\"\"\n"
287     self.text_da += "study_config['Observers'] = observers\n"
288
289   def add_observer_in_dict(self, observer, observers):
290     """
291       Add observer in the observers dict.
292     """
293     observers[observer] = {}
294     observers[observer]["name"] = observer
295     observer_eficas_name = "__ASSIMILATION_STUDY__Observers__" + observer + "__" + observer + "_data__"
296     # NodeType
297     node_type_key_name = observer_eficas_name + "NodeType"
298     observers[observer]["nodetype"] = self.dictMCVal[node_type_key_name]
299
300     # NodeType script/file
301     if observers[observer]["nodetype"] == "String":
302       observers[observer]["script"] = self.dictMCVal[observer_eficas_name + "PythonScript__Value"]
303     else:
304       observers[observer]["file"] = self.dictMCVal[observer_eficas_name + "UserFile__Value"]
305
306     # Scheduler
307     scheduler_key_name = observer_eficas_name + "Scheduler"
308     if scheduler_key_name in self.dictMCVal.keys():
309       observers[observer]["scheduler"] = self.dictMCVal[scheduler_key_name]
310     # Info
311     info_key_name = observer_eficas_name + "Info"
312     if info_key_name in self.dictMCVal.keys():
313       observers[observer]["info"] = self.dictMCVal[info_key_name]