]> SALOME platform Git repositories - modules/adao.git/blob - src/daSalome/daYacsSchemaCreator/methods.py
Salome HOME
Updating copyright date information
[modules/adao.git] / src / daSalome / daYacsSchemaCreator / methods.py
1 #-*- coding: utf-8 -*-
2 # Copyright (C) 2008-2016 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: Andre Ribes, andre.ribes@edf.fr, EDF R&D
23
24 import sys
25 import traceback
26 import logging
27 import pilot
28 import loader
29 import SALOMERuntime
30 import os
31
32 from daYacsSchemaCreator.infos_daComposant import *
33
34 def _Internal_Add_dir_script_ports(node, sf, ed, br, t_type):
35   # On conserve le pointeur de "node" et "typ"
36   __scriptfile = str( sf )
37   __exist_dir  = bool( ed )
38   __base_dir   = str( br )
39   __full_name  = os.path.join(__base_dir, os.path.basename(__scriptfile))
40   if os.path.exists(__full_name):
41     node.getInputPort("script").edInitPy(__full_name)
42   else:
43     node.getInputPort("script").edInitPy(__scriptfile)
44   if __exist_dir:
45     node.edAddInputPort("studydir", t_type)
46     node.getInputPort("studydir").edInitPy(__base_dir)
47
48 def create_yacs_proc(study_config):
49
50   logging.debug("[create_yacs_proc]")
51
52   # Init part
53   SALOMERuntime.RuntimeSALOME_setRuntime()
54   l = loader.YACSLoader()
55   l.registerProcCataLoader()
56   runtime = pilot.getRuntime()
57   try:
58     catalogAd = runtime.loadCatalog("proc", os.environ["ADAO_ROOT_DIR"] + "/share/salome/resources/adao/ADAOSchemaCatalog.xml")
59     runtime.addCatalog(catalogAd)
60   except:
61     raise ValueError("Exception in loading ADAO YACS Schema catalog")
62
63   # Starting creating proc
64   proc = runtime.createProc("proc")
65   proc.setTypeCode("pyobj", runtime.getTypeCode("pyobj"))
66   proc.setTypeCode("SALOME_TYPES/ParametricInput", catalogAd._typeMap["SALOME_TYPES/ParametricInput"])
67   proc.setTypeCode("SALOME_TYPES/ParametricOutput", catalogAd._typeMap["SALOME_TYPES/ParametricOutput"])
68   t_pyobj  = proc.getTypeCode("pyobj")
69   t_string = proc.getTypeCode("string")
70   t_bool = proc.getTypeCode("bool")
71   t_param_input  = proc.getTypeCode("SALOME_TYPES/ParametricInput")
72   t_param_output = proc.getTypeCode("SALOME_TYPES/ParametricOutput")
73   if "Repertory" in study_config.keys():
74     base_repertory = study_config["Repertory"]
75     repertory      = True
76   else:
77     base_repertory = ""
78     repertory = False
79
80   # Create ADAO case bloc
81   ADAO_Case = runtime.createBloc("ADAO_Case_Bloc")
82   proc.edAddChild(ADAO_Case)
83
84   # Step 0: create AssimilationStudyObject
85   factory_CAS_node = catalogAd.getNodeFromNodeMap("CreateAssimilationStudy")
86   CAS_node = factory_CAS_node.cloneNode("CreateAssimilationStudy")
87   CAS_node.getInputPort("Name").edInitPy(study_config["Name"])
88   CAS_node.getInputPort("Algorithm").edInitPy(study_config["Algorithm"])
89   if study_config.has_key("Debug") and study_config["Debug"] == "1":
90     CAS_node.getInputPort("Debug").edInitPy(True)
91   else:
92     CAS_node.getInputPort("Debug").edInitPy(False)
93
94   # Ajout des Variables
95   InputVariablesNames = []
96   InputVariablesSizes = []
97   for var in study_config["InputVariables"]["Order"]:
98     InputVariablesNames.append(var)
99     InputVariablesSizes.append(int(study_config["InputVariables"][var]))
100   CAS_node.getInputPort("InputVariablesNames").edInitPy(InputVariablesNames)
101   CAS_node.getInputPort("InputVariablesSizes").edInitPy(InputVariablesSizes)
102   OutputVariablesNames = []
103   OutputVariablesSizes = []
104   for var in study_config["OutputVariables"]["Order"]:
105     OutputVariablesNames.append(var)
106     OutputVariablesSizes.append(int(study_config["OutputVariables"][var]))
107   CAS_node.getInputPort("OutputVariablesNames").edInitPy(OutputVariablesNames)
108   CAS_node.getInputPort("OutputVariablesSizes").edInitPy(OutputVariablesSizes)
109
110   ADAO_Case.edAddChild(CAS_node)
111
112   # Adding an observer init node if an user defines some
113   factory_init_observers_node = catalogAd.getNodeFromNodeMap("SetObserversNode")
114   init_observers_node = factory_init_observers_node.cloneNode("SetObservers")
115   if "Observers" in study_config.keys():
116     node_script = init_observers_node.getScript()
117     node_script += "has_observers = True\n"
118     node_script += "observers = " + str(study_config["Observers"]) + "\n"
119     init_observers_node.setScript(node_script)
120     ADAO_Case.edAddChild(init_observers_node)
121     ADAO_Case.edAddDFLink(init_observers_node.getOutputPort("has_observers"), CAS_node.getInputPort("has_observers"))
122     ADAO_Case.edAddDFLink(init_observers_node.getOutputPort("observers"), CAS_node.getInputPort("observers"))
123   else:
124     node_script = init_observers_node.getScript()
125     node_script += "has_observers = False\n"
126     node_script += "observers = \"\"\n"
127     init_observers_node.setScript(node_script)
128     ADAO_Case.edAddChild(init_observers_node)
129     ADAO_Case.edAddDFLink(init_observers_node.getOutputPort("has_observers"), CAS_node.getInputPort("has_observers"))
130     ADAO_Case.edAddDFLink(init_observers_node.getOutputPort("observers"), CAS_node.getInputPort("observers"))
131
132   # Step 0.5: Find if there is a user init node
133   init_config = {}
134   init_config["Target"] = []
135   if "UserDataInit" in study_config.keys():
136     init_config = study_config["UserDataInit"]
137     factory_init_node = catalogAd.getNodeFromNodeMap("UserDataInitFromScript")
138     init_node = factory_init_node.cloneNode("UserDataInit")
139     _Internal_Add_dir_script_ports( init_node, init_config["Data"], repertory, base_repertory, t_string)
140     init_node_script = init_node.getScript()
141     init_node_script += "# Import script and get data\n__import__(module_name)\nuser_script_module = sys.modules[module_name]\n\n"
142     init_node_script += "init_data = user_script_module.init_data\n"
143     init_node.setScript(init_node_script)
144     ADAO_Case.edAddChild(init_node)
145
146   # Step 1: get input data from user configuration
147
148   st_keys = study_config.keys()
149   st_keys.sort()
150   for key in st_keys:
151     ad_keys = AssimData
152     ad_keys.sort()
153     if key in ad_keys:
154       data_config = study_config[key]
155
156       key_type = key + "Type"
157       key_stored = key + "Stored"
158
159       if data_config["Type"] == "Dict" and data_config["From"] == "Script":
160         # Create node
161         factory_back_node = catalogAd.getNodeFromNodeMap("CreateDictFromScript")
162         back_node = factory_back_node.cloneNode("Get" + key)
163         _Internal_Add_dir_script_ports( back_node, data_config["Data"], repertory, base_repertory, t_string)
164         back_node.edAddOutputPort(key, t_pyobj)
165         ADAO_Case.edAddChild(back_node)
166         # Set content of the node
167         back_node_script = back_node.getScript()
168         if key in init_config["Target"]:
169           # Connect node with InitUserData
170           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
171           back_node.edAddInputPort("init_data", t_pyobj)
172           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
173         back_node_script += "# Import script and get data\n__import__(module_name)\nuser_script_module = sys.modules[module_name]\n\n"
174         back_node_script += key + " = user_script_module." + key + "\n"
175         back_node.setScript(back_node_script)
176         # Connect node with CreateAssimilationStudy
177         CAS_node.edAddInputPort(key, t_pyobj)
178         ADAO_Case.edAddDFLink(back_node.getOutputPort(key), CAS_node.getInputPort(key))
179
180       if data_config["Type"] == "Dict" and data_config["From"] == "String":
181         # Create node
182         factory_back_node = catalogAd.getNodeFromNodeMap("CreateDictFromString")
183         back_node = factory_back_node.cloneNode("Get" + key)
184         back_node.getInputPort("dict_in_string").edInitPy(data_config["Data"])
185         back_node.edAddOutputPort(key, t_pyobj)
186         ADAO_Case.edAddChild(back_node)
187         # Set content of the node
188         back_node_script = back_node.getScript()
189         if key in init_config["Target"]:
190           # Connect node with InitUserData
191           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
192           back_node.edAddInputPort("init_data", t_pyobj)
193           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
194         back_node_script += key + " = dict(dico)\n"
195         back_node_script += "logging.debug(\"Dict is %ss\"%s%s)"%("%","%",key)
196         back_node.setScript(back_node_script)
197         # Connect node with CreateAssimilationStudy
198         CAS_node.edAddInputPort(key, t_pyobj)
199         ADAO_Case.edAddDFLink(back_node.getOutputPort(key), CAS_node.getInputPort(key))
200
201       if data_config["Type"] == "Vector" and data_config["From"] == "String":
202         # Create node
203         factory_back_node = catalogAd.getNodeFromNodeMap("CreateNumpyVectorFromString")
204         back_node = factory_back_node.cloneNode("Get" + key)
205         back_node.getInputPort("vector_in_string").edInitPy(data_config["Data"])
206         ADAO_Case.edAddChild(back_node)
207         # Set content of the node
208         back_node_script = back_node.getScript()
209         back_node_script += "stored = " + str(data_config["Stored"]) + "\n"
210         if key in init_config["Target"]:
211           # Connect node with InitUserData
212           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
213           back_node.edAddInputPort("init_data", t_pyobj)
214           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
215         back_node.setScript(back_node_script)
216         # Connect node with CreateAssimilationStudy
217         CAS_node.edAddInputPort(key, t_pyobj)
218         CAS_node.edAddInputPort(key_type, t_string)
219         CAS_node.edAddInputPort(key_stored, t_bool)
220         ADAO_Case.edAddDFLink(back_node.getOutputPort("vector"), CAS_node.getInputPort(key))
221         ADAO_Case.edAddDFLink(back_node.getOutputPort("type"), CAS_node.getInputPort(key_type))
222         ADAO_Case.edAddDFLink(back_node.getOutputPort("stored"), CAS_node.getInputPort(key_stored))
223
224       if data_config["Type"] == "Vector" and data_config["From"] == "Script":
225         # Create node
226         factory_back_node = catalogAd.getNodeFromNodeMap("CreateNumpyVectorFromScript")
227         back_node = factory_back_node.cloneNode("Get" + key)
228         _Internal_Add_dir_script_ports( back_node, data_config["Data"], repertory, base_repertory, t_string)
229         back_node.edAddOutputPort(key, t_pyobj)
230         ADAO_Case.edAddChild(back_node)
231         # Set content of the node
232         back_node_script = back_node.getScript()
233         if key in init_config["Target"]:
234           # Connect node with InitUserData
235           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
236           back_node.edAddInputPort("init_data", t_pyobj)
237           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
238         back_node_script += "# Import script and get data\n__import__(module_name)\nuser_script_module = sys.modules[module_name]\n\n"
239         back_node_script += key + " = user_script_module." + key + "\n"
240         back_node_script += "stored = " + str(data_config["Stored"]) + "\n"
241         back_node.setScript(back_node_script)
242         # Connect node with CreateAssimilationStudy
243         CAS_node.edAddInputPort(key, t_pyobj)
244         CAS_node.edAddInputPort(key_type, t_string)
245         CAS_node.edAddInputPort(key_stored, t_bool)
246         ADAO_Case.edAddDFLink(back_node.getOutputPort(key), CAS_node.getInputPort(key))
247         ADAO_Case.edAddDFLink(back_node.getOutputPort("type"), CAS_node.getInputPort(key_type))
248         ADAO_Case.edAddDFLink(back_node.getOutputPort("stored"), CAS_node.getInputPort(key_stored))
249
250       if data_config["Type"] == "VectorSerie" and data_config["From"] == "String":
251         # Create node
252         factory_back_node = catalogAd.getNodeFromNodeMap("CreateNumpyVectorSerieFromString")
253         back_node = factory_back_node.cloneNode("Get" + key)
254         back_node.getInputPort("vector_in_string").edInitPy(data_config["Data"])
255         ADAO_Case.edAddChild(back_node)
256         # Set content of the node
257         back_node_script = back_node.getScript()
258         back_node_script += "stored = " + str(data_config["Stored"]) + "\n"
259         if key in init_config["Target"]:
260           # Connect node with InitUserData
261           back_node_script += "__builtins__[\"init_data\"] = init_data\n" + back_node_script
262           back_node.edAddInputPort("init_data", t_pyobj)
263           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
264         back_node.setScript(back_node_script)
265         # Connect node with CreateAssimilationStudy
266         CAS_node.edAddInputPort(key, t_pyobj)
267         CAS_node.edAddInputPort(key_type, t_string)
268         CAS_node.edAddInputPort(key_stored, t_bool)
269         ADAO_Case.edAddDFLink(back_node.getOutputPort("vector"), CAS_node.getInputPort(key))
270         ADAO_Case.edAddDFLink(back_node.getOutputPort("type"), CAS_node.getInputPort(key_type))
271         ADAO_Case.edAddDFLink(back_node.getOutputPort("stored"), CAS_node.getInputPort(key_stored))
272
273       if data_config["Type"] == "VectorSerie" and data_config["From"] == "Script":
274         # Create node
275         factory_back_node = catalogAd.getNodeFromNodeMap("CreateNumpyVectorSerieFromScript")
276         back_node = factory_back_node.cloneNode("Get" + key)
277         _Internal_Add_dir_script_ports( back_node, data_config["Data"], repertory, base_repertory, t_string)
278         back_node.edAddOutputPort(key, t_pyobj)
279         ADAO_Case.edAddChild(back_node)
280         # Set content of the node
281         back_node_script = back_node.getScript()
282         if key in init_config["Target"]:
283           # Connect node with InitUserData
284           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
285           back_node.edAddInputPort("init_data", t_pyobj)
286           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
287         back_node_script += "# Import script and get data\n__import__(module_name)\nuser_script_module = sys.modules[module_name]\n\n"
288         back_node_script += key + " = user_script_module." + key + "\n"
289         back_node_script += "stored = " + str(data_config["Stored"]) + "\n"
290         back_node.setScript(back_node_script)
291         # Connect node with CreateAssimilationStudy
292         CAS_node.edAddInputPort(key, t_pyobj)
293         CAS_node.edAddInputPort(key_type, t_string)
294         CAS_node.edAddInputPort(key_stored, t_bool)
295         ADAO_Case.edAddDFLink(back_node.getOutputPort(key), CAS_node.getInputPort(key))
296         ADAO_Case.edAddDFLink(back_node.getOutputPort("type"), CAS_node.getInputPort(key_type))
297         ADAO_Case.edAddDFLink(back_node.getOutputPort("stored"), CAS_node.getInputPort(key_stored))
298
299       if data_config["Type"] in ("Matrix", "ScalarSparseMatrix", "DiagonalSparseMatrix") and data_config["From"] == "String":
300         # Create node
301         factory_back_node = catalogAd.getNodeFromNodeMap("CreateNumpy%sFromString"%(data_config["Type"],))
302         back_node = factory_back_node.cloneNode("Get" + key)
303         back_node.getInputPort("matrix_in_string").edInitPy(data_config["Data"])
304         ADAO_Case.edAddChild(back_node)
305         # Set content of the node
306         back_node_script = back_node.getScript()
307         back_node_script += "stored = " + str(data_config["Stored"]) + "\n"
308         if key in init_config["Target"]:
309           # Connect node with InitUserData
310           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
311           back_node.edAddInputPort("init_data", t_pyobj)
312           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
313         back_node.setScript(back_node_script)
314         # Connect node with CreateAssimilationStudy
315         CAS_node.edAddInputPort(key, t_pyobj)
316         CAS_node.edAddInputPort(key_type, t_string)
317         CAS_node.edAddInputPort(key_stored, t_bool)
318         ADAO_Case.edAddDFLink(back_node.getOutputPort("matrix"), CAS_node.getInputPort(key))
319         ADAO_Case.edAddDFLink(back_node.getOutputPort("type"), CAS_node.getInputPort(key_type))
320         ADAO_Case.edAddDFLink(back_node.getOutputPort("stored"), CAS_node.getInputPort(key_stored))
321
322       if data_config["Type"] in ("Matrix", "ScalarSparseMatrix", "DiagonalSparseMatrix") and data_config["From"] == "Script":
323         # Create node
324         factory_back_node = catalogAd.getNodeFromNodeMap("CreateNumpy%sFromScript"%(data_config["Type"],))
325         back_node = factory_back_node.cloneNode("Get" + key)
326         _Internal_Add_dir_script_ports( back_node, data_config["Data"], repertory, base_repertory, t_string)
327         back_node.edAddOutputPort(key, t_pyobj)
328         ADAO_Case.edAddChild(back_node)
329         # Set content of the node
330         back_node_script = back_node.getScript()
331         back_node_script += "stored = " + str(data_config["Stored"]) + "\n"
332         if key in init_config["Target"]:
333           # Connect node with InitUserData
334           back_node_script += "__builtins__[\"init_data\"] = init_data\n"
335           back_node.edAddInputPort("init_data", t_pyobj)
336           ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
337         back_node_script += "# Import script and get data\n__import__(module_name)\nuser_script_module = sys.modules[module_name]\n\n"
338         back_node_script += key + " = user_script_module." + key + "\n"
339         back_node.setScript(back_node_script)
340         # Connect node with CreateAssimilationStudy
341         CAS_node.edAddInputPort(key, t_pyobj)
342         CAS_node.edAddInputPort(key_type, t_string)
343         CAS_node.edAddInputPort(key_stored, t_bool)
344         ADAO_Case.edAddDFLink(back_node.getOutputPort(key), CAS_node.getInputPort(key))
345         ADAO_Case.edAddDFLink(back_node.getOutputPort("type"), CAS_node.getInputPort(key_type))
346         ADAO_Case.edAddDFLink(back_node.getOutputPort("stored"), CAS_node.getInputPort(key_stored))
347
348       if data_config["Type"] == "Function" and (key == "ObservationOperator" or key == "EvolutionModel"):
349          TheData = data_config["Data"]
350          for FunctionName in TheData["Function"]:
351            port_name = key + FunctionName
352            CAS_node.edAddInputPort(port_name, t_string)
353            if os.path.exists(os.path.join(base_repertory, os.path.basename(TheData["Script"][FunctionName]))):
354              CAS_node.getInputPort(port_name).edInitPy(os.path.join(base_repertory, os.path.basename(TheData["Script"][FunctionName])))
355            else:
356              CAS_node.getInputPort(port_name).edInitPy(TheData["Script"][FunctionName])
357            try:
358              CAS_node.edAddInputPort("studydir", t_string)
359              CAS_node.getInputPort("studydir").edInitPy(base_repertory)
360            except: pass
361
362   # Step 3: create compute bloc
363   compute_bloc = runtime.createBloc("compute_bloc")
364   ADAO_Case.edAddChild(compute_bloc)
365   ADAO_Case.edAddCFLink(CAS_node, compute_bloc)
366   # We use an optimizer loop
367   name = "Execute" + study_config["Algorithm"]
368   algLib = "daYacsIntegration.py"
369   factoryName = "AssimilationAlgorithm_asynch"
370   optimizer_node = runtime.createOptimizerLoop(name, algLib, factoryName, "")
371   compute_bloc.edAddChild(optimizer_node)
372   ADAO_Case.edAddDFLink(CAS_node.getOutputPort("Study"), optimizer_node.edGetAlgoInitPort())
373
374   # Check if we have a python script for OptimizerLoopNode
375   data_config = study_config["ObservationOperator"]
376   opt_script_nodeOO = None
377   if data_config["Type"] == "Function" and (data_config["From"] == "ScriptWithSwitch" or data_config["From"] == "FunctionDict"):
378     # Get script
379     TheData = data_config["Data"]
380     script_filename = ""
381     for FunctionName in TheData["Function"]:
382       # We currently support only one file
383       script_filename = TheData["Script"][FunctionName]
384       break
385     # We create a new pyscript node
386     opt_script_nodeOO = runtime.createScriptNode("", "FunctionNodeOO")
387     if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(script_filename))):
388       script_filename = os.path.join(base_repertory, os.path.basename(script_filename))
389     try:
390       script_str= open(script_filename, 'r')
391     except:
392       raise ValueError("Exception in opening function script file: " + script_filename)
393     node_script  = "#-*-coding:iso-8859-1-*-\n"
394     node_script += "import sys, os \n"
395     node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
396     node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
397     node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
398     node_script += "  sys.path.insert(0,filepath)\n"
399     node_script += script_str.read()
400     opt_script_nodeOO.setScript(node_script)
401     opt_script_nodeOO.edAddInputPort("computation", t_param_input)
402     opt_script_nodeOO.edAddOutputPort("result", t_param_output)
403
404   elif data_config["Type"] == "Function" and data_config["From"] == "ScriptWithFunctions":
405     # Get script
406     ScriptWithFunctions = data_config["Data"]
407     script_filename = ""
408     for FunctionName in ScriptWithFunctions["Function"]:
409       # We currently support only one file
410       script_filename = ScriptWithFunctions["Script"][FunctionName]
411       break
412
413     # We create a new pyscript node
414     opt_script_nodeOO = runtime.createScriptNode("", "FunctionNodeOO")
415     if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(script_filename))):
416       script_filename = os.path.join(base_repertory, os.path.basename(script_filename))
417     try:
418       script_str= open(script_filename, 'r')
419     except:
420       raise ValueError("Exception in opening function script file: " + script_filename)
421     node_script  = "#-*-coding:iso-8859-1-*-\n"
422     node_script += "import sys, os, numpy, logging\n"
423     node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
424     node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
425     node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
426     node_script += "  sys.path.insert(0,filepath)\n"
427     node_script += """# ==============================================\n"""
428     node_script += script_str.read()
429     node_script += """# ==============================================\n"""
430     node_script += """__method = None\n"""
431     node_script += """for param in computation["specificParameters"]:\n"""
432     node_script += """  if param["name"] == "method": __method = param["value"]\n"""
433     node_script += """if __method not in ["Direct", "Tangent", "Adjoint"]:\n"""
434     node_script += """  raise ValueError("ComputationFunctionNode: no valid computation method is given, it has to be Direct, Tangent or Adjoint (\'%s\' given)."%__method)\n"""
435     node_script += """logging.debug("ComputationFunctionNode: Found method is \'%s\'"%__method)\n"""
436     node_script += """#\n"""
437     node_script += """#\n"""
438     node_script += """__data = []\n"""
439     node_script += """if __method == "Direct":\n"""
440     node_script += """  try:\n"""
441     node_script += """      DirectOperator\n"""
442     node_script += """  except NameError:\n"""
443     node_script += """      raise ValueError("ComputationFunctionNode: DirectOperator not found in the imported user script file")\n"""
444     node_script += """  logging.debug("ComputationFunctionNode: Direct computation")\n"""
445     node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
446     node_script += """  __data = DirectOperator(numpy.matrix( __Xcurrent ).T)\n"""
447     node_script += """#\n"""
448     node_script += """if __method == "Tangent":\n"""
449     node_script += """  try:\n"""
450     node_script += """    TangentOperator\n"""
451     node_script += """  except NameError:\n"""
452     node_script += """    raise ValueError("ComputationFunctionNode:  TangentOperator not found in the imported user script file")\n"""
453     node_script += """  logging.debug("ComputationFunctionNode: Tangent computation")\n"""
454     node_script += """  __Xcurrent  = computation["inputValues"][0][0][0]\n"""
455     node_script += """  __dXcurrent = computation["inputValues"][0][0][1]\n"""
456     node_script += """  __data = TangentOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __dXcurrent ).T))\n"""
457     node_script += """#\n"""
458     node_script += """if __method == "Adjoint":\n"""
459     node_script += """  try:\n"""
460     node_script += """    AdjointOperator\n"""
461     node_script += """  except NameError:\n"""
462     node_script += """    raise ValueError("ComputationFunctionNode: AdjointOperator not found in the imported user script file")\n"""
463     node_script += """  logging.debug("ComputationFunctionNode: Adjoint computation")\n"""
464     node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
465     node_script += """  __Ycurrent = computation["inputValues"][0][0][1]\n"""
466     node_script += """  __data = AdjointOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __Ycurrent ).T))\n"""
467     node_script += """#\n"""
468     node_script += """logging.debug("ComputationFunctionNode: Formatting the output")\n"""
469     node_script += """__it = 1.*numpy.ravel(__data)\n"""
470     node_script += """outputValues = [[[[]]]]\n"""
471     node_script += """outputValues[0][0][0] = list(__it)\n"""
472     node_script += """#\n"""
473     node_script += """result = {}\n"""
474     node_script += """result["outputValues"]        = outputValues\n"""
475     node_script += """result["specificOutputInfos"] = []\n"""
476     node_script += """result["returnCode"]          = 0\n"""
477     node_script += """result["errorMessage"]        = ""\n"""
478     node_script += """# ==============================================\n"""
479     #
480     opt_script_nodeOO.setScript(node_script)
481     opt_script_nodeOO.edAddInputPort("computation", t_param_input)
482     opt_script_nodeOO.edAddOutputPort("result", t_param_output)
483
484   elif data_config["Type"] == "Function" and data_config["From"] == "ScriptWithOneFunction":
485     # Get script
486     ScriptWithOneFunction = data_config["Data"]
487     script_filename = ""
488     for FunctionName in ScriptWithOneFunction["Function"]:
489       # We currently support only one file
490       script_filename = ScriptWithOneFunction["Script"][FunctionName]
491       break
492
493     # We create a new pyscript node
494     opt_script_nodeOO = runtime.createScriptNode("", "FunctionNodeOO")
495     if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(script_filename))):
496       script_filename = os.path.join(base_repertory, os.path.basename(script_filename))
497     try:
498       script_str= open(script_filename, 'r')
499     except:
500       raise ValueError("Exception in opening function script file: " + script_filename)
501     node_script  = "#-*-coding:iso-8859-1-*-\n"
502     node_script += "import sys, os, numpy, logging\n"
503     node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
504     node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
505     node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
506     node_script += "  sys.path.insert(0,filepath)\n"
507     node_script += """# ==============================================\n"""
508     node_script += script_str.read()
509     node_script += """# ==============================================\n"""
510     node_script += """__method = None\n"""
511     node_script += """for param in computation["specificParameters"]:\n"""
512     node_script += """  if param["name"] == "method": __method = param["value"]\n"""
513     node_script += """if __method not in ["Direct", "Tangent", "Adjoint"]:\n"""
514     node_script += """  raise ValueError("ComputationFunctionNode: no valid computation method is given, it has to be Direct, Tangent or Adjoint (\'%s\' given)."%__method)\n"""
515     node_script += """logging.debug("ComputationFunctionNode: Found method is \'%s\'"%__method)\n"""
516     node_script += """#\n"""
517     node_script += """try:\n"""
518     node_script += """    DirectOperator\n"""
519     node_script += """except NameError:\n"""
520     node_script += """    raise ValueError("ComputationFunctionNode: DirectOperator not found in the imported user script file")\n"""
521     node_script += """import ApproximatedDerivatives\n"""
522     node_script += """FDA = ApproximatedDerivatives.FDApproximation(\n"""
523     node_script += """    Function   = DirectOperator,\n"""
524     node_script += """    increment  = %s,\n"""%str(ScriptWithOneFunction['DifferentialIncrement'])
525     node_script += """    centeredDF = %s,\n"""%str(ScriptWithOneFunction['CenteredFiniteDifference'])
526     if 'EnableMultiProcessing' in ScriptWithOneFunction.keys():
527         node_script += """    mpEnabled  = %s,\n"""%str(ScriptWithOneFunction['EnableMultiProcessing'])
528     if 'NumberOfProcesses' in ScriptWithOneFunction.keys():
529         node_script += """    mpWorkers  = %s,\n"""%str(ScriptWithOneFunction['NumberOfProcesses'])
530     node_script += """    )\n"""
531     node_script += """#\n"""
532     node_script += """__data = []\n"""
533     node_script += """if __method == "Direct":\n"""
534     node_script += """  logging.debug("ComputationFunctionNode: Direct computation")\n"""
535     node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
536     node_script += """  __data = FDA.DirectOperator(numpy.matrix( __Xcurrent ).T)\n"""
537     node_script += """#\n"""
538     node_script += """if __method == "Tangent":\n"""
539     node_script += """  logging.debug("ComputationFunctionNode: Tangent computation")\n"""
540     node_script += """  __Xcurrent  = computation["inputValues"][0][0][0]\n"""
541     node_script += """  __dXcurrent = computation["inputValues"][0][0][1]\n"""
542     node_script += """  __data = FDA.TangentOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __dXcurrent ).T))\n"""
543     node_script += """#\n"""
544     node_script += """if __method == "Adjoint":\n"""
545     node_script += """  logging.debug("ComputationFunctionNode: Adjoint computation")\n"""
546     node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
547     node_script += """  __Ycurrent = computation["inputValues"][0][0][1]\n"""
548     node_script += """  __data = FDA.AdjointOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __Ycurrent ).T))\n"""
549     node_script += """#\n"""
550     node_script += """logging.debug("ComputationFunctionNode: Formatting the output")\n"""
551     node_script += """__it = 1.*numpy.ravel(__data)\n"""
552     node_script += """outputValues = [[[[]]]]\n"""
553     node_script += """outputValues[0][0][0] = list(__it)\n"""
554     node_script += """#\n"""
555     node_script += """result = {}\n"""
556     node_script += """result["outputValues"]        = outputValues\n"""
557     node_script += """result["specificOutputInfos"] = []\n"""
558     node_script += """result["returnCode"]          = 0\n"""
559     node_script += """result["errorMessage"]        = ""\n"""
560     node_script += """# ==============================================\n"""
561     #
562     opt_script_nodeOO.setScript(node_script)
563     opt_script_nodeOO.edAddInputPort("computation", t_param_input)
564     opt_script_nodeOO.edAddOutputPort("result", t_param_output)
565
566   else:
567     factory_opt_script_node = catalogAd.getNodeFromNodeMap("FakeOptimizerLoopNode")
568     opt_script_nodeOO = factory_opt_script_node.cloneNode("FakeFunctionNode")
569
570   # Check if we have a python script for OptimizerLoopNode
571   if "EvolutionModel" in study_config.keys():
572     data_config = study_config["EvolutionModel"]
573     opt_script_nodeEM = None
574     if data_config["Type"] == "Function" and (data_config["From"] == "ScriptWithSwitch" or data_config["From"] == "FunctionDict"):
575       # Get script
576       TheData = data_config["Data"]
577       script_filename = ""
578       for FunctionName in TheData["Function"]:
579         # We currently support only one file
580         script_filename = TheData["Script"][FunctionName]
581         break
582       # We create a new pyscript node
583       opt_script_nodeEM = runtime.createScriptNode("", "FunctionNodeEM")
584       if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(script_filename))):
585         script_filename = os.path.join(base_repertory, os.path.basename(script_filename))
586       try:
587         script_str= open(script_filename, 'r')
588       except:
589         raise ValueError("Exception in opening function script file: " + script_filename)
590       node_script  = "#-*-coding:iso-8859-1-*-\n"
591       node_script += "import sys, os \n"
592       node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
593       node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
594       node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
595       node_script += "  sys.path.insert(0,filepath)\n"
596       node_script += script_str.read()
597       opt_script_nodeEM.setScript(node_script)
598       opt_script_nodeEM.edAddInputPort("computation", t_param_input)
599       opt_script_nodeEM.edAddOutputPort("result", t_param_output)
600
601     elif data_config["Type"] == "Function" and data_config["From"] == "ScriptWithFunctions":
602       # Get script
603       ScriptWithFunctions = data_config["Data"]
604       script_filename = ""
605       for FunctionName in ScriptWithFunctions["Function"]:
606         # We currently support only one file
607         script_filename = ScriptWithFunctions["Script"][FunctionName]
608         break
609       # We create a new pyscript node
610       opt_script_nodeEM = runtime.createScriptNode("", "FunctionNodeEM")
611       if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(script_filename))):
612         script_filename = os.path.join(base_repertory, os.path.basename(script_filename))
613       try:
614         script_str= open(script_filename, 'r')
615       except:
616         raise ValueError("Exception in opening function script file: " + script_filename)
617       node_script  = "#-*-coding:iso-8859-1-*-\n"
618       node_script += "import sys, os, numpy, logging\n"
619       node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
620       node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
621       node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
622       node_script += "  sys.path.insert(0,filepath)\n"
623       node_script += script_str.read()
624       node_script += """# ==============================================\n"""
625       node_script += """__method = None\n"""
626       node_script += """for param in computation["specificParameters"]:\n"""
627       node_script += """  if param["name"] == "method": __method = param["value"]\n"""
628       node_script += """if __method not in ["Direct", "Tangent", "Adjoint"]:\n"""
629       node_script += """  raise ValueError("ComputationFunctionNode: no valid computation method is given, it has to be Direct, Tangent or Adjoint (\'%s\' given)."%__method)\n"""
630       node_script += """logging.debug("ComputationFunctionNode: Found method is \'%s\'"%__method)\n"""
631       node_script += """#\n"""
632       node_script += """#\n"""
633       node_script += """__data = []\n"""
634       node_script += """if __method == "Direct":\n"""
635       node_script += """  try:\n"""
636       node_script += """    DirectOperator\n"""
637       node_script += """  except NameError:\n"""
638       node_script += """    raise ValueError("ComputationFunctionNode: mandatory DirectOperator not found in the imported user script file")\n"""
639       node_script += """  logging.debug("ComputationFunctionNode: Direct computation")\n"""
640       node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
641       node_script += """  if len(computation["inputValues"][0][0]) == 2:\n"""
642       node_script += """    __Ucurrent = computation["inputValues"][0][0][1]\n"""
643       node_script += """    __data = DirectOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __Ucurrent ).T))\n"""
644       node_script += """  else:\n"""
645       node_script += """    __data = DirectOperator(numpy.matrix( __Xcurrent ).T)\n"""
646       node_script += """#\n"""
647       node_script += """if __method == "Tangent":\n"""
648       node_script += """  try:\n"""
649       node_script += """    TangentOperator\n"""
650       node_script += """  except NameError:\n"""
651       node_script += """    raise ValueError("ComputationFunctionNode: mandatory TangentOperator not found in the imported user script file")\n"""
652       node_script += """  logging.debug("ComputationFunctionNode: Tangent computation")\n"""
653       node_script += """  __Xcurrent  = computation["inputValues"][0][0][0]\n"""
654       node_script += """  __dXcurrent = computation["inputValues"][0][0][1]\n"""
655       node_script += """  __data = TangentOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __dXcurrent ).T))\n"""
656       node_script += """#\n"""
657       node_script += """if __method == "Adjoint":\n"""
658       node_script += """  try:\n"""
659       node_script += """    AdjointOperator\n"""
660       node_script += """  except NameError:\n"""
661       node_script += """    raise ValueError("ComputationFunctionNode: mandatory AdjointOperator not found in the imported user script file")\n"""
662       node_script += """  logging.debug("ComputationFunctionNode: Adjoint computation")\n"""
663       node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
664       node_script += """  __Ycurrent = computation["inputValues"][0][0][1]\n"""
665       node_script += """  __data = AdjointOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __Ycurrent ).T))\n"""
666       node_script += """#\n"""
667       node_script += """logging.debug("ComputationFunctionNode: Formatting the output")\n"""
668       node_script += """__it = 1.*numpy.ravel(__data)\n"""
669       node_script += """outputValues = [[[[]]]]\n"""
670       node_script += """outputValues[0][0][0] = list(__it)\n"""
671       node_script += """#\n"""
672       node_script += """result = {}\n"""
673       node_script += """result["outputValues"]        = outputValues\n"""
674       node_script += """result["specificOutputInfos"] = []\n"""
675       node_script += """result["returnCode"]          = 0\n"""
676       node_script += """result["errorMessage"]        = ""\n"""
677       node_script += """# ==============================================\n"""
678       #
679       opt_script_nodeEM.setScript(node_script)
680       opt_script_nodeEM.edAddInputPort("computation", t_param_input)
681       opt_script_nodeEM.edAddOutputPort("result", t_param_output)
682
683     elif data_config["Type"] == "Function" and data_config["From"] == "ScriptWithOneFunction":
684       # Get script
685       ScriptWithOneFunction = data_config["Data"]
686       script_filename = ""
687       for FunctionName in ScriptWithOneFunction["Function"]:
688         # We currently support only one file
689         script_filename = ScriptWithOneFunction["Script"][FunctionName]
690         break
691       # We create a new pyscript node
692       opt_script_nodeEM = runtime.createScriptNode("", "FunctionNodeEM")
693       if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(script_filename))):
694         script_filename = os.path.join(base_repertory, os.path.basename(script_filename))
695       try:
696         script_str= open(script_filename, 'r')
697       except:
698         raise ValueError("Exception in opening function script file: " + script_filename)
699       node_script  = "#-*-coding:iso-8859-1-*-\n"
700       node_script += "import sys, os, numpy, logging\n"
701       node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
702       node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
703       node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
704       node_script += "  sys.path.insert(0,filepath)\n"
705       node_script += script_str.read()
706       node_script += """# ==============================================\n"""
707       node_script += """__method = None\n"""
708       node_script += """for param in computation["specificParameters"]:\n"""
709       node_script += """  if param["name"] == "method": __method = param["value"]\n"""
710       node_script += """if __method not in ["Direct", "Tangent", "Adjoint"]:\n"""
711       node_script += """  raise ValueError("ComputationFunctionNode: no valid computation method is given, it has to be Direct, Tangent or Adjoint (\'%s\' given)."%__method)\n"""
712       node_script += """logging.debug("ComputationFunctionNode: Found method is \'%s\'"%__method)\n"""
713       node_script += """#\n"""
714       node_script += """try:\n"""
715       node_script += """    DirectOperator\n"""
716       node_script += """except NameError:\n"""
717       node_script += """    raise ValueError("ComputationFunctionNode: DirectOperator not found in the imported user script file")\n"""
718       node_script += """import ApproximatedDerivatives\n"""
719       node_script += """FDA = ApproximatedDerivatives.FDApproximation(\n"""
720       node_script += """    Function   = DirectOperator,\n"""
721       node_script += """    increment  = %s,\n"""%str(ScriptWithOneFunction['DifferentialIncrement'])
722       node_script += """    centeredDF = %s,\n"""%str(ScriptWithOneFunction['CenteredFiniteDifference'])
723       if 'EnableMultiProcessing' in ScriptWithOneFunction.keys():
724           node_script += """    mpEnabled  = %s,\n"""%str(ScriptWithOneFunction['EnableMultiProcessing'])
725       if 'NumberOfProcesses' in ScriptWithOneFunction.keys():
726           node_script += """    mpWorkers  = %s,\n"""%str(ScriptWithOneFunction['NumberOfProcesses'])
727       node_script += """    )\n"""
728       node_script += """#\n"""
729       node_script += """__data = []\n"""
730       node_script += """if __method == "Direct":\n"""
731       node_script += """  logging.debug("ComputationFunctionNode: Direct computation")\n"""
732       node_script += """  if len(computation["inputValues"][0][0]) == 2:\n"""
733       node_script += """    raise ValueError("ComputationFunctionNode: you have to build explicitly the controled evolution model and its tangent and adjoint operators, instead of using approximate derivative.")"""
734       node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
735       node_script += """  __data = FDA.DirectOperator(numpy.matrix( __Xcurrent ).T)\n"""
736       node_script += """#\n"""
737       node_script += """if __method == "Tangent":\n"""
738       node_script += """  logging.debug("ComputationFunctionNode: Tangent computation")\n"""
739       node_script += """  __Xcurrent  = computation["inputValues"][0][0][0]\n"""
740       node_script += """  __dXcurrent = computation["inputValues"][0][0][1]\n"""
741       node_script += """  __data = FDA.TangentOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __dXcurrent ).T))\n"""
742       node_script += """#\n"""
743       node_script += """if __method == "Adjoint":\n"""
744       node_script += """  logging.debug("ComputationFunctionNode: Adjoint computation")\n"""
745       node_script += """  __Xcurrent = computation["inputValues"][0][0][0]\n"""
746       node_script += """  __Ycurrent = computation["inputValues"][0][0][1]\n"""
747       node_script += """  __data = FDA.AdjointOperator((numpy.matrix( __Xcurrent ).T, numpy.matrix( __Ycurrent ).T))\n"""
748       node_script += """#\n"""
749       node_script += """logging.debug("ComputationFunctionNode: Formatting the output")\n"""
750       node_script += """__it = 1.*numpy.ravel(__data)\n"""
751       node_script += """outputValues = [[[[]]]]\n"""
752       node_script += """outputValues[0][0][0] = list(__it)\n"""
753       node_script += """#\n"""
754       node_script += """result = {}\n"""
755       node_script += """result["outputValues"]        = outputValues\n"""
756       node_script += """result["specificOutputInfos"] = []\n"""
757       node_script += """result["returnCode"]          = 0\n"""
758       node_script += """result["errorMessage"]        = ""\n"""
759       node_script += """# ==============================================\n"""
760       #
761       opt_script_nodeEM.setScript(node_script)
762       opt_script_nodeEM.edAddInputPort("computation", t_param_input)
763       opt_script_nodeEM.edAddOutputPort("result", t_param_output)
764
765     else:
766       factory_opt_script_node = catalogAd.getNodeFromNodeMap("FakeOptimizerLoopNode")
767       opt_script_nodeEM = factory_opt_script_node.cloneNode("FakeFunctionNode")
768
769   # Add computation bloc
770   if "Observers" in study_config.keys():
771     execution_bloc = runtime.createBloc("Execution Bloc")
772     optimizer_node.edSetNode(execution_bloc)
773
774     # Add a node that permits to configure the switch
775     factory_read_for_switch_node = catalogAd.getNodeFromNodeMap("ReadForSwitchNode")
776     read_for_switch_node = factory_read_for_switch_node.cloneNode("ReadForSwitch")
777     execution_bloc.edAddChild(read_for_switch_node)
778     ADAO_Case.edAddDFLink(optimizer_node.edGetSamplePort(), read_for_switch_node.getInputPort("data"))
779
780     # Add a switch
781     switch_node = runtime.createSwitch("Execution Switch")
782     execution_bloc.edAddChild(switch_node)
783     # Connect switch
784     ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("switch_value"), switch_node.edGetConditionPort())
785
786     # First case: computation bloc
787     computation_blocOO = runtime.createBloc("computation_blocOO")
788     computation_blocOO.edAddChild(opt_script_nodeOO)
789     switch_node.edSetNode(1, computation_blocOO)
790
791     # We connect with the script
792     ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("data"), opt_script_nodeOO.getInputPort("computation"))
793     ADAO_Case.edAddDFLink(opt_script_nodeOO.getOutputPort("result"), optimizer_node.edGetPortForOutPool())
794
795     # Second case: evolution bloc
796     if "EvolutionModel" in study_config.keys():
797       computation_blocEM = runtime.createBloc("computation_blocEM")
798       computation_blocEM.edAddChild(opt_script_nodeEM)
799       switch_node.edSetNode(2, computation_blocEM)
800
801       # We connect with the script
802       ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("data"), opt_script_nodeEM.getInputPort("computation"))
803       ADAO_Case.edAddDFLink(opt_script_nodeEM.getOutputPort("result"), optimizer_node.edGetPortForOutPool())
804
805     # For each observer add a new bloc in the switch
806     observer_config = study_config["Observers"]
807     for observer_name in observer_config:
808       observer_cfg = observer_config[observer_name]
809       observer_bloc = runtime.createBloc("Observer %s" % observer_name)
810       switch_node.edSetNode(observer_cfg["number"], observer_bloc)
811
812       factory_extract_data_node = catalogAd.getNodeFromNodeMap("ExtractDataNode")
813       extract_data_node = factory_extract_data_node.cloneNode("ExtractData")
814       observer_bloc.edAddChild(extract_data_node)
815       ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("data"), extract_data_node.getInputPort("data"))
816
817       observation_node = None
818       if observer_cfg["nodetype"] == "String":
819         factory_observation_node = catalogAd.getNodeFromNodeMap("ObservationNodeString")
820         observation_node = factory_observation_node.cloneNode("Observation")
821         node_script = observation_node.getScript()
822         node_script += observer_cfg["String"]
823         observation_node.setScript(node_script)
824       else:
825         factory_observation_node = catalogAd.getNodeFromNodeMap("ObservationNodeFile")
826         observation_node = factory_observation_node.cloneNode("Observation")
827         _Internal_Add_dir_script_ports( observation_node, observer_cfg["Script"], repertory, base_repertory, t_string)
828       observer_bloc.edAddChild(observation_node)
829       ADAO_Case.edAddDFLink(extract_data_node.getOutputPort("var"), observation_node.getInputPort("var"))
830       ADAO_Case.edAddDFLink(extract_data_node.getOutputPort("info"), observation_node.getInputPort("info"))
831
832       factory_end_observation_node = catalogAd.getNodeFromNodeMap("EndObservationNode")
833       end_observation_node = factory_end_observation_node.cloneNode("EndObservation")
834       observer_bloc.edAddChild(end_observation_node)
835       ADAO_Case.edAddCFLink(observation_node, end_observation_node)
836       ADAO_Case.edAddDFLink(end_observation_node.getOutputPort("output"), optimizer_node.edGetPortForOutPool())
837
838   elif "EvolutionModel" in study_config.keys():
839     execution_bloc = runtime.createBloc("Execution Bloc")
840     optimizer_node.edSetNode(execution_bloc)
841
842     # Add a node that permits to configure the switch
843     factory_read_for_switch_node = catalogAd.getNodeFromNodeMap("ReadForSwitchNode")
844     read_for_switch_node = factory_read_for_switch_node.cloneNode("ReadForSwitch")
845     execution_bloc.edAddChild(read_for_switch_node)
846     ADAO_Case.edAddDFLink(optimizer_node.edGetSamplePort(), read_for_switch_node.getInputPort("data"))
847
848     # Add a switch
849     switch_node = runtime.createSwitch("Execution Switch")
850     execution_bloc.edAddChild(switch_node)
851     # Connect switch
852     ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("switch_value"), switch_node.edGetConditionPort())
853
854     # First case: computation bloc
855     computation_blocOO = runtime.createBloc("computation_blocOO")
856     computation_blocOO.edAddChild(opt_script_nodeOO)
857     switch_node.edSetNode(1, computation_blocOO)
858
859     # We connect with the script
860     ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("data"), opt_script_nodeOO.getInputPort("computation"))
861     ADAO_Case.edAddDFLink(opt_script_nodeOO.getOutputPort("result"), optimizer_node.edGetPortForOutPool())
862
863     # Second case: evolution bloc
864     computation_blocEM = runtime.createBloc("computation_blocEM")
865     computation_blocEM.edAddChild(opt_script_nodeEM)
866     switch_node.edSetNode(2, computation_blocEM)
867
868     # We connect with the script
869     ADAO_Case.edAddDFLink(read_for_switch_node.getOutputPort("data"), opt_script_nodeEM.getInputPort("computation"))
870     ADAO_Case.edAddDFLink(opt_script_nodeEM.getOutputPort("result"), optimizer_node.edGetPortForOutPool())
871
872   else:
873     computation_blocOO = runtime.createBloc("computation_blocOO")
874     optimizer_node.edSetNode(computation_blocOO)
875     computation_blocOO.edAddChild(opt_script_nodeOO)
876
877     # We connect Optimizer with the script
878     ADAO_Case.edAddDFLink(optimizer_node.edGetSamplePort(), opt_script_nodeOO.getInputPort("computation"))
879     ADAO_Case.edAddDFLink(opt_script_nodeOO.getOutputPort("result"), optimizer_node.edGetPortForOutPool())
880
881   # Connect node with InitUserData
882   if "ObservationOperator" in init_config["Target"]:
883     opt_node_script = opt_script_nodeOO.getScript()
884     opt_node_script = "__builtins__[\"init_data\"] = init_data\n" + opt_node_script
885     opt_script_nodeOO.setScript(opt_node_script)
886     opt_script_nodeOO.edAddInputPort("init_data", t_pyobj)
887     ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), opt_script_nodeOO.getInputPort("init_data"))
888
889   # Step 4: create post-processing from user configuration
890   if "UserPostAnalysis" in study_config.keys():
891     analysis_config = study_config["UserPostAnalysis"]
892     if analysis_config["From"] == "String":
893       factory_analysis_node = catalogAd.getNodeFromNodeMap("SimpleUserAnalysis")
894       analysis_node = factory_analysis_node.cloneNode("UsePostAnalysis")
895       default_script = analysis_node.getScript()
896       final_script = default_script + analysis_config["Data"]
897       analysis_node.setScript(final_script)
898       ADAO_Case.edAddChild(analysis_node)
899       ADAO_Case.edAddCFLink(compute_bloc, analysis_node)
900       if AlgoType[study_config["Algorithm"]] == "Optim":
901         ADAO_Case.edAddDFLink(optimizer_node.edGetAlgoResultPort(), analysis_node.getInputPort("Study"))
902       else:
903         ADAO_Case.edAddDFLink(execute_node.getOutputPort("Study"), analysis_node.getInputPort("Study"))
904
905       # Connect node with InitUserData
906       if "UserPostAnalysis" in init_config["Target"]:
907         node_script = analysis_node.getScript()
908         node_script = "__builtins__[\"init_data\"] = init_data\n" + node_script
909         analysis_node.setScript(node_script)
910         analysis_node.edAddInputPort("init_data", t_pyobj)
911         ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), analysis_node.getInputPort("init_data"))
912
913     elif analysis_config["From"] == "Script":
914       factory_analysis_node = catalogAd.getNodeFromNodeMap("SimpleUserAnalysis")
915       analysis_node = factory_analysis_node.cloneNode("UserPostAnalysis")
916       default_script = analysis_node.getScript()
917       analysis_file_name = analysis_config["Data"]
918       if repertory and os.path.exists(os.path.join(base_repertory, os.path.basename(analysis_file_name))):
919         analysis_file_name = os.path.join(base_repertory, os.path.basename(analysis_file_name))
920       try:
921         analysis_file = open(analysis_file_name, 'r')
922       except:
923         raise ValueError("Exception in opening analysis file: " + str(analysis_config["Data"]))
924       node_script  = "#-*-coding:iso-8859-1-*-\n"
925       node_script += "import sys, os \n"
926       node_script += "filepath = \"" + os.path.dirname(analysis_file_name) + "\"\n"
927       node_script += "filename = \"" + os.path.basename(analysis_file_name) + "\"\n"
928       node_script += "if sys.path.count(filepath)==0 or (sys.path.count(filepath)>0 and sys.path.index(filepath)>0):\n"
929       node_script += "  sys.path.insert(0,filepath)\n"
930       node_script += default_script
931       node_script += analysis_file.read()
932       analysis_node.setScript(node_script)
933       ADAO_Case.edAddChild(analysis_node)
934       ADAO_Case.edAddCFLink(compute_bloc, analysis_node)
935       if AlgoType[study_config["Algorithm"]] == "Optim":
936         ADAO_Case.edAddDFLink(optimizer_node.edGetAlgoResultPort(), analysis_node.getInputPort("Study"))
937       else:
938         ADAO_Case.edAddDFLink(execute_node.getOutputPort("Study"), analysis_node.getInputPort("Study"))
939       # Connect node with InitUserData
940       if "UserPostAnalysis" in init_config["Target"]:
941         node_script = analysis_node.getScript()
942         node_script = "__builtins__[\"init_data\"] = init_data\n" + node_script
943         analysis_node.setScript(node_script)
944         analysis_node.edAddInputPort("init_data", t_pyobj)
945         ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), analysis_node.getInputPort("init_data"))
946
947       pass
948
949   return proc
950
951 def write_yacs_proc(proc, yacs_schema_filename):
952
953   proc.saveSchema(yacs_schema_filename)
954