Salome HOME
bos #29864 Irrelevant assert in test.
[modules/yacs.git] / doc / schemapy.rst
1
2 .. _schemapy:
3
4 Defining a calculation scheme with the Python programming interface
5 ============================================================================
6 A YACS calculation scheme can be defined from a program written in the Python language (http://www.python.org/).  
7 Refer to the `Python tutorial <http://docs.python.org/tut/tut.html>`_ for an introduction to the language.
8
9 The programming interface (API) is carried on three Python modules:  pilot, SALOMERuntime and loader.
10
11 The SALOMERuntime module is used to initialise YACS for SALOME.
12
13 The loader module is used to create calculation schemes by loading files in the XML format.
14
15 The pilot module is used to create calculation schemes.
16
17 These modules must be imported at the beginning of the Python program and YACS must be initialised::
18
19     import sys
20     import pilot
21     import SALOMERuntime
22     import loader
23     SALOMERuntime.RuntimeSALOME_setRuntime()
24
25 Before YACS modules can be imported, the environment must be correctly configured, as it will be if the 
26 SALOME application is used.  Otherwise, the PYTHONPATH environment variable has to be set to 
27 <YACS_ROOT_DIR>/lib/pythonX.Y/site-packages/salome.
28
29 When you build your own Salome application and use your own modules and components (using YACSGEN for example), you may need to load
30 the module catalog::
31
32     import SALOMERuntime
33     SALOMERuntime.RuntimeSALOME_setRuntime()
34     salome_runtime = SALOMERuntime.getSALOMERuntime()
35     import salome
36     salome.salome_init()
37     mc = salome.naming_service.Resolve('/Kernel/ModulCatalog')
38     ior = salome.orb.object_to_string(mc)
39     session_catalog = salome_runtime.loadCatalog("session", ior)
40     salome_runtime.addCatalog(session_catalog)
41
42
43 .. _loadxml:
44
45 Create a calculation scheme by loading an XML file
46 --------------------------------------------------------------
47 This is the easiest way of creating a calculation scheme.  If there is a file conforming with the YACS syntax (see :ref:`schemaxml`), 
48 then all that is necessary is to create an XML file loader and then to use its load method to obtain a calculation scheme object in Python.
49
50 The following shows the sufficient Python code to load an XML file::
51
52   xmlLoader = loader.YACSLoader()
53   try:
54     p = xmlLoader.load("simple1.xml")
55   except IOError,ex:
56     print "IO exception:",ex
57     sys.exit(1)
58
59 Then, if the initialisation code and the loading code are put into a file named testLoader.py, proceed as follows::
60  
61   python testLoader.py
62
63 to execute the program.  The IOError exception can be raised by the loading operation principally if the file does not exist 
64 or if it cannot be read.  If no exception has been raised, it is necessary to make sure that the file analysis took place correctly.  
65 This is done using the Logger object associated with the calculation scheme::
66
67    logger=p.getLogger("parser")
68    if not logger.isEmpty():
69      print "The imported file has errors :"
70      print logger.getStr()
71      sys.exit(1)
72
73 Finally, if the file analysis took place correctly, the validity of the scheme (completeness of connections, no unconnected 
74 input port, etc.) has to be checked.  This is done using the isValid method of the calculation scheme object, and 
75 then the p.checkConsistency method of this object as below::
76
77    if not p.isValid():
78      print "The schema is not valid and can not be executed"
79      print p.getErrorReport()
80      sys.exit(1)
81
82    info=pilot.LinkInfo(pilot.LinkInfo.ALL_DONT_STOP)
83    p.checkConsistency(info)
84    if info.areWarningsOrErrors():
85      print "The schema is not consistent and can not be executed"
86      print info.getGlobalRepr()
87      sys.exit(1)
88
89
90 If all these tests took place correctly, the scheme is ready to be executed (see :ref:`execpy`).
91
92 Create a calculation scheme from scratch
93 -------------------------------------------
94 We will use the same sequence as in :ref:`schemaxml`.
95 The first step is to obtain the runtime object that will be used for creation of objects making up the scheme, before they are created::
96
97   r = pilot.getRuntime()
98
99 Creating an empty scheme
100 ''''''''''''''''''''''''''''
101 An empty scheme is obtained using the createProc method of the runtime object with the name of the scheme as an argument::
102
103   p=r.createProc("pr")
104
105 The scheme object named “pr” was created.  It is represented by the Python variable p.
106
107 Definition of data types
108 '''''''''''''''''''''''''''''''''
109
110 .. _basictypes:
111
112 Basic types
113 ++++++++++++++++
114 A basic type cannot be defined.  These types are defined by YACS.  However, it must be possible to retrieve a Python object 
115 equivalent to a basic type so as to be able to subsequently create ports.
116  
117 A basic data type is recovered using the getTypeCode method in the calculation scheme with the name of the type as an argument.  
118 For example::
119
120    td=p.getTypeCode("double")
121
122 will obtain a double type (Python td object).  Other basic types are obtained by::
123
124    ti=p.getTypeCode("int")
125    ts=p.getTypeCode("string")
126    tb=p.getTypeCode("bool")
127    tf=p.getTypeCode("file")
128
129 Object reference
130 +++++++++++++++++++++
131 The createInterfaceTc method in the calculation scheme is used to define an object reference type.  
132 This method accepts three arguments:  the repository id of the corresponding SALOME object, the name of the type, and a 
133 list of types that will be basic types of this type.  If the repository id is equal to “”, the default value will be used.
134
135 The following is a minimal example for a reference definition of an object name Obj (default repository id, no basic type)::
136
137   tc1=p.createInterfaceTc("","Obj",[])
138
139 The same Obj type can be defined giving the repository id::
140
141   tc1=p.createInterfaceTc("IDL:GEOM/GEOM_Object","Obj",[])
142
143 A list of basic types is also provided so as to define a reference object type derived from another type.
144
145 The following gives a definition of the MyObj type derived from the Obj type::
146
147   tc2=p.createInterfaceTc("","MyObj",[tc1])
148
149 Sequence
150 +++++++++++++++++++++
151 The createSequenceTc method in the calculation scheme is used to define a sequence type.   
152 This method accepts three arguments, namely the repository id, the type name, and the type of elements in the sequence.  
153 There is generally no point in specifying the repository id.  The value “” will be given.
154
155 The following gives an example definition of the seqdbl double sequence type::
156
157   tc3=p.createSequenceTc("","seqdbl",td)
158
159 td is the double type that is obtained as above in the section on :ref:`basictypes`.
160
161 A sequence type of sequence is defined as follows::
162
163   tc4=p.createSequenceTc("","seqseqdbl",tc3)
164
165 A reference sequence type is defined as follows::
166
167   tc5=p.createSequenceTc("","seqobj",tc1)
168
169 Structure
170 ++++++++++++
171 A structure type is defined using the createStructTc method in the calculation scheme.  
172 This method accepts two arguments, namely the repository id and the type name.  For standard use, the repository id is 
173 equal to the value “”.  The structure type is the only type that is defined in two steps.  It is created empty after 
174 calling the createStructTc method.  Its members are then defined by adding them with the addMember method.
175
176 The following shows an example definition of an s1 type structure with 2 members (m1 and m2) of the double and double sequence types::
177
178   ts1=p.createStructTc("","s1")
179   ts1.addMember("m1",td)
180   ts1.addMember("m2",tc3)
181
182 Retrieve predefined types
183 +++++++++++++++++++++++++++++++++
184 By default, YACS only defines the basic types.  If more predefined types are required, they must be requested from SALOME.  
185 These other predefined types are contained in module catalogs such as GEOM or SMESH.
186
187 The following code sequence is used to obtain an image of SALOME catalogs in YACS::
188
189   try:
190     cata=r.loadCatalog("session",
191            "corbaname::localhost:2810/NameService#Kernel.dir/ModulCatalog.object")
192   except CORBA.TRANSIENT,ex:
193     print "Unable to contact server:",ex
194   except CORBA.SystemException,ex:
195     print ex,CORBA.id(ex)
196
197 The SALOME application must be running before the catalog is accessible.  
198 Predefined types are then accessible in the cata._typeMap dictionary.  
199 If the name of the required type is known (for example ‘GEOM_Shape’), it is obtained as follows::
200
201   tgeom=cata._typeMap['GEOM_Shape']
202
203 .. _typedict:
204
205 Add a type into the scheme types dictionary
206 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
207 Some operations require that types are defined in the scheme dictionary.  Proceed as follows if you want to add a type 
208 into the dictionary, for example for the seqobj type defined above::
209
210   p.typeMap["seqobj"]=tc5
211
212 where the type name is the dictionary key and the type is the value.
213
214 Definition of elementary calculation nodes
215 ''''''''''''''''''''''''''''''''''''''''''''''
216
217 .. _pyscript:
218
219 Python script node
220 +++++++++++++++++++++
221 Several steps are used to define a script node in a given context (for example the calculation scheme).  
222 The first step consists of creating the node object by calling the runtime createScriptNode method.  
223 This method uses 2 arguments, the first of which in standard use must be equal to “” and the second is the node name.  
224 The following is an example to create node node1::
225
226   n=r.createScriptNode("","node1")
227  
228 The second step consists of attaching the node to its definition context by calling the edAddChild method for the context object.  
229 This method has one argument, namely the node to be attached.  The following is an example of the attachment of the node node1 
230 to the calculation scheme::
231
232   p.edAddChild(n)
233
234 Warning: the name of the method to be used depends on the type of context node.  We will see which method should be used for other 
235 node types later.
236
237 The third step consists of defining the Python script associated with the node.  This is done using the setScript method for the node 
238 with a character string argument that contains the Python code.  The following shows an example definition of the associated code::
239
240   n.setScript("p1=p1+2.5")
241
242 The fourth step consists of defining input and output data ports.  An input port is created by calling the edAddInputPort method 
243 for the node.  An output port is created by calling the edAddOutputPort method for the node.  
244 These two methods have two arguments:  the port name and the port data type.  The following is an example creating a double 
245 type input port p1 and a double type output port p1::
246
247   n.edAddInputPort("p1",td)
248   n.edAddOutputPort("p1",td)
249
250 Our node is now fully defined with its name, script, ports and context.  It retrieves the double in the input port p1, adds 2.5 to it 
251 and puts the result into the output port p1.
252
253 If you want to execute your script node on a remote container, you have to set the execution mode of the node to **remote**
254 and to assign a container (see :ref:`py_container` to define a container) to the node as in the following example::
255
256   n.setExecutionMode("remote")
257   n.setContainer(cont1)
258
259 The default option for the execution mode is **local** where the node will run
260 on the same container as the scheme executor.
261
262 .. _pyfunc:
263
264 Python function node
265 ++++++++++++++++++++++
266 The same procedure is used to define a function node.  The only differences apply to creation, in using the createFuncNode 
267 method and defining the function:  the setFname method must also be called to give the name of the function to be executed.  
268 The following is a complete example for the definition of a function node that is functionally identical to the previous script node::
269
270   n2=r.createFuncNode("","node2")
271   p.edAddChild(n2)
272   n2.setScript("""
273   def f(p1):
274     p1=p1+2.5
275     return p1
276   """)
277   n2.setFname("f")
278   n2.edAddInputPort("p1",td)
279   n2.edAddOutputPort("p1",td)
280
281 If you want to execute your function node on a remote container, you have to set the execution mode of the node to **remote**
282 and to assign a container (see :ref:`py_container` to define a container) to the node as in the following example::
283
284   n2.setExecutionMode("remote")
285   n2.setContainer(cont1)
286
287 The default option for the execution mode is **local** where the node will run
288 on the same container as the scheme executor.
289
290 .. _pyservice:
291
292 SALOME service node
293 ++++++++++++++++++++++++++
294 There are two definition forms for a SALOME service node.
295
296 The first form in which the component name is given, uses the createCompoNode method to create the node.  The name of the 
297 component is given as an argument to the setRef method for the node.  The service name is given as an argument for the 
298 setMethod method for the node.  The remainder of the definition is exactly the same as for the previous Python nodes.
299
300 The following is an example of a node that calls the makeBanner service for a PYHELLO component::
301
302   n3=r.createCompoNode("","node3")
303   p.edAddChild(n3)
304   n3.setRef("PYHELLO")
305   n3.setMethod("makeBanner")
306   n3.edAddInputPort("p1",ts)
307   n3.edAddOutputPort("p1",ts)
308
309 The second form is used to define a node that uses the same component as another node uses the createNode method of this other node.  
310 This method only has one argument, which is the node name.  
311 The remainder of the definition is identical to the definition for the previous form.
312
313 The following gives an example of a service node that makes a second call to the makeBanner service for the same component 
314 instance as the previous node::
315
316   n4=n3.createNode("node4")
317   p.edAddChild(n4)
318   n4.setMethod("makeBanner")
319   n4.edAddInputPort("p1",ts)
320   n4.edAddOutputPort("p1",ts)
321
322 Definition of connections
323 ''''''''''''''''''''''''''''
324 Obtaining a node port 
325 ++++++++++++++++++++++++++++
326 Before links can be defined, it is almost always necessary to have Python objects representing the output port to be 
327 connected to the input port.  There are two ways of obtaining this object.
328
329 The first way is to retrieve the port when it is created using the edAddInputPort and edAddOutputPort methods.  
330 For example, we can then write::
331
332   pin=n4.edAddInputPort("p1",ts)
333   pout=n4.edAddOutputPort("p1",ts)
334
335 pin and pout are then the objects necessary to define links.
336
337 The second way is to interrogate the node and ask it for one of its ports by its name.  
338 This is done using the getInputPort and getOutputPort methods.
339 pin and pout can then be obtained as follows::
340
341   pin=n4.getInputPort("p1")
342   pout=n4.getOutputPort("p1")
343
344 Control link
345 ++++++++++++++++++++++++++++
346 The edAddCFLink method for the context is used to define a control link between two nodes, transferring the two nodes to be 
347 connected to it as arguments.  For example, a control link between nodes n3 and n4 will be written::
348
349   p.edAddCFLink(n3,n4)
350
351 Node n3 will be executed before node n4.
352
353 Dataflow link
354 ++++++++++++++++++++++++++++
355 The first step in defining a dataflow link is to obtain port objects using one of the methods described above.
356 Then, the edAddLink method links an output port to an input port::
357
358   pout=n3.getOutputPort("p1")
359   pin=n4.getInputPort("p1")
360   p.edAddLink(pout,pin)
361
362 Most of the time, when you need a dataflow link between two ports, you also need a control link between the nodes
363 of the ports. In this case you can use the method edAddDFLink::
364
365   pout=n3.getOutputPort("p1")
366   pin=n4.getInputPort("p1")
367   p.edAddDFLink(pout,pin)
368
369 edAddDFLink is equivalent to edAddCFLink followed by edAddLink.
370
371 Initialising an input data port
372 '''''''''''''''''''''''''''''''''''''''''''''''
373 An input data port is initialised firstly by obtaining the corresponding port object.  There are then two methods of initialising it.
374
375 The first method initialises the port with a value encoded in XML-RPC.  The edInitXML method for the port is then used.  
376 The following is an example that initialises the port with the integer value 5::
377
378   pin.edInitXML("<value><int>5</int></value>")
379
380 The second method initialises the port with a Python value.  The edInitPy method is then used.  
381 The following is an example that initialises this port with the same value::
382
383   pin.edInitPy(5)
384
385 Specific methods can also be used for basic types:
386
387 - ``edInitInt`` for the int type
388 - ``edInitDbl`` for the double type
389 - ``edInitBool`` for the bool type
390 - ``edInitString`` for the string type
391
392 First example starting from the previous elements
393 '''''''''''''''''''''''''''''''''''''''''''''''''''
394 By collecting all previous definition elements, a complete calculation scheme identical to that given in the :ref:`schemaxml` chapter 
395 will appear as follows::
396
397   import sys
398   import pilot
399   import SALOMERuntime
400   import loader
401   SALOMERuntime.RuntimeSALOME_setRuntime()
402   r = pilot.getRuntime()
403   p=r.createProc("pr")
404   ti=p.getTypeCode("int")
405   td=p.getTypeCode("double")
406   #node1
407   n1=r.createScriptNode("","node1")
408   p.edAddChild(n1)
409   n1.setScript("p1=p1+10")
410   n1.edAddInputPort("p1",ti)
411   n1.edAddOutputPort("p1",ti)
412   #node2
413   n2=r.createScriptNode("","node2")
414   p.edAddChild(n2)
415   n2.setScript("p1=2*p1")
416   n2.edAddInputPort("p1",ti)
417   n2.edAddOutputPort("p1",ti)
418   #node4
419   n4=r.createCompoNode("","node4")
420   p.edAddChild(n4)
421   n4.setRef("ECHO")
422   n4.setMethod("echoDouble")
423   n4.edAddInputPort("p1",td)
424   n4.edAddOutputPort("p1",td)
425   #control links
426   p.edAddCFLink(n1,n2)
427   p.edAddCFLink(n1,n4)
428   #dataflow links
429   p.edAddLink(n1.getOutputPort("p1"),n2.getInputPort("p1"))
430   p.edAddLink(n1.getOutputPort("p1"),n4.getInputPort("p1"))
431   #initialisation ports
432   n1.getInputPort("p1").edInitPy(5)
433
434 Definition of composite nodes
435 '''''''''''''''''''''''''''''''''
436
437 .. _py_block:
438
439 Block
440 +++++++
441 A block is defined using the runtime createBloc method transferring the Block name to it as an argument.  The node is then 
442 attached to its definition context as an elementary node.  The following is an example Block definition in a calculation scheme::
443
444   b=r.createBloc("b1")
445   p.edAddChild(b)
446
447 Once the block has been created, all nodes and links possible in its context can be added.  
448 Repeating a part of the example above, we will get::
449
450   n1=r.createScriptNode("","node1")
451   b.edAddChild(n1)
452   n1.setScript("p1=p1+10")
453   n1.edAddInputPort("p1",ti)
454   n1.edAddOutputPort("p1",ti)
455   n2=r.createScriptNode("","node2")
456   b.edAddChild(n2)
457   n2.setScript("p1=2*p1")
458   n2.edAddInputPort("p1",ti)
459   n2.edAddOutputPort("p1",ti)
460   b.edAddDFLink(n1.getOutputPort("p1"),n2.getInputPort("p1"))
461
462 .. _py_forloop:
463
464 ForLoop
465 ++++++++
466 A Forloop is defined using the runtime createForLoop method, transferring the node name to it as an argument.  
467 The node is then attached to its definition context.  The following is an example ForLoop definition in a calculation scheme::
468
469   l=r.createForLoop("l1")
470   p.edAddChild(l)
471
472 The number of iterations in the loop to be executed will be initialised using the “nsteps” port that is initialised 
473 with an integer.  For example::
474
475   ip=l.getInputPort("nsteps") 
476   ip.edInitPy(3)
477
478 There is a special method for obtaining the “nsteps” port for the loop, namely edGetNbOfTimesInputPort.  Therefore, it can also be 
479 written as follows::
480
481   ip=l.edGetNbOfTimesInputPort()
482   ip.edInitPy(3)
483
484 Finally, a method called edSetNode will be used in the context of a loop, instead of the edAddChild method, so as to add one (and only one) node.  
485 The following is a small example definition of a node inside a loop::
486
487   n1=r.createScriptNode("","node1")
488   l.edSetNode(n1)
489   n1.setScript("p1=p1+10")
490   n1.edAddInputPort("p1",ti)
491   n1.edAddOutputPort("p1",ti)
492
493 .. _py_whileloop:
494
495 WhileLoop
496 ++++++++++
497 WhileLoop node is defined in practically the same way as a ForLoop node.  The only differences apply to creation and assignment 
498 of the end of loop condition.  The createWhileLoop method is used for creation.  The “condition” port is used for the condition.  
499 If looping takes place on a node, it is important to use a data link instead of a dataflow link.  
500 The following is an example of WhileLoop node definition with a Python script internal node.  
501 The condition is initialised to True and is then changed to False by the internal node.  This results in a link loop::
502
503   wh=r.createWhileLoop("w1")
504   p.edAddChild(wh)
505   n=r.createScriptNode("","node3")
506   n.setScript("p1=0")
507   n.edAddOutputPort("p1",ti)
508   wh.edSetNode(n)
509   cport=wh.getInputPort("condition")
510   cport.edInitBool(True)
511   p.edAddLink(n.getOutputPort("p1"),cport)
512
513 There is a special method for obtaining the loop “condition” port:  edGetConditionPort.
514
515 .. _py_foreachloop:
516
517 ForEach loop
518 ++++++++++++++++
519 A ForEach node is basically defined in the same way as any other loop node.  There are several differences.  
520 The node is created with the createForEachLoop method that has an additional argument, namely the data type managed by the ForEach.  
521 The number of ForEach branches is specified with the “nbBranches” port.  The collection on which the ForEach iterates is managed by 
522 connection of the “evalSamples” and “SmplsCollection” ports.
523
524 The following is an example definition of the ForEach node with a Python script internal node that increments 
525 the element of the collection by 3::
526
527   fe=r.createForEachLoop("fe1",td)
528   p.edAddChild(fe)
529   n=r.createScriptNode("","node3")
530   n.setScript("p1=p1+3.")
531   n.edAddInputPort("p1",td)
532   n.edAddOutputPort("p1",td)
533   fe.edSetNode(n)
534   p.edAddLink(fe.getOutputPort("evalSamples"),n.getInputPort("p1"))
535   fe.getInputPort("nbBranches").edInitPy(3)
536   fe.getInputPort("SmplsCollection").edInitPy([2.,3.,4.])
537
538 Special ports for the ForEach can be obtained using the following methods instead of getInputPort and getOutputPort:
539
540 - edGetNbOfBranchesPort for the “nbBranches” port
541 - edGetSamplePort for the “evalSamples” port
542 - edGetSeqOfSamplesPort for the “SmplsCollection” port
543
544 .. _py_switch:
545
546 Switch
547 ++++++++
548 A switch node is defined in several steps.  The first two steps are creation and attachment to the context node.  
549 The node is created by calling the runtime createSwitch method with the name of the node as an argument.  The node is attached 
550 to the context node by calling the edAddChild method for a scheme or a block or edSetNode for a loop node.
551
552 The following is an example of a creation followed by an attachment::
553
554   sw=r.createSwitch("sw1")
555   p.edAddChild(sw)
556
557 The next step is to create an internal elementary or composite node by case.  The node for the default case is attached to 
558 the switch using the edSetDefaultNode method.  Nodes for other cases are attached to the switch using the edSetNode method, in 
559 which the first argument is equal to the value of the case (integer) and the second argument is equal to the internal node.
560
561 The following is an example of a switch with one script node for case “1” and another script node for the “default” case 
562 and a script node to initialise an exchanged variable::
563
564   #init
565   n=r.createScriptNode("","node3")
566   n.setScript("p1=3.5")
567   n.edAddOutputPort("p1",td)
568   p.edAddChild(n)
569   #switch
570   sw=r.createSwitch("sw1")
571   p.edAddChild(sw)
572   nk1=r.createScriptNode("","ncas1")
573   nk1.setScript("p1=p1+3.")
574   nk1.edAddInputPort("p1",td)
575   nk1.edAddOutputPort("p1",td)
576   sw.edSetNode(1,nk1)
577   ndef=r.createScriptNode("","ndefault")
578   ndef.setScript("p1=p1+5.")
579   ndef.edAddInputPort("p1",td)
580   ndef.edAddOutputPort("p1",td)
581   sw.edSetDefaultNode(ndef)
582   #initialise the select port
583   sw.getInputPort("select").edInitPy(1)
584   #connection of internal nodes
585   p.edAddDFLink(n.getOutputPort("p1"),nk1.getInputPort("p1"))
586   p.edAddDFLink(n.getOutputPort("p1"),ndef.getInputPort("p1"))
587
588 The edGetConditionPort method can be used instead of getInputPort, to obtain the special “select” port for the Switch.
589
590 .. _py_optimizerloop:
591
592 OptimizerLoop
593 +++++++++++++++++++
594
595 The following is an example of OptimizerLoop with one python script as internal node. The algorithm
596 is defined by the class async in the python module myalgo2.py::
597
598   ol=r.createOptimizerLoop("ol1","myalgo2.py","async",True)
599   p.edAddChild(ol)
600   n=r.createScriptNode("","node3")
601   n.setScript("p1=3")
602   n.edAddInputPort("p1",td)
603   n.edAddOutputPort("p1",ti)
604   ol.edSetNode(n)
605   ol.getInputPort("nbBranches").edInitPy(3)
606   ol.getInputPort("algoInit").edInitPy("coucou")
607   p.edAddLink(ol.getOutputPort("evalSamples"),n.getInputPort("p1"))
608   p.edAddLink(n.getOutputPort("p1"),ol.getInputPort("evalResults"))
609
610 .. _py_container:
611
612 Definition of containers
613 ''''''''''''''''''''''''''''
614
615 This example shows how to add a container to a scheme::
616
617   c1=p.createContainer("MyContainer")
618
619 A property is added to a container using its setProperty method that uses 2 arguments (character strings).  
620 The first is the property name.  The second is its value.  
621 The following is an example of how to set constraints on the container::
622
623   c1.setProperty("container_name","FactoryServer")
624   c1.setProperty("hostname","localhost")
625   c1.setProperty("mem_mb","1000")
626
627 Once the containers have been defined, SALOME components can be placed on this container.  The first step to place the component 
628 of a SALOME service node is to obtain the component instance of this service node using the getComponent method for this node.  
629 The previously defined container is then assigned to this component instance using the setContainer method of the component instance.
630
631 If it is required to place the SALOME service defined above (node “node3”) on
632 “MyContainer”, we will write::
633
634   n3.getComponent().setContainer(c1)
635
636 It is also possible to place python nodes on containers, but the code is a
637 little different (see :ref:`pyscript`)::
638
639   n1.setExecutionMode("remote")
640   n1.setContainer(c1)
641
642 Since SALOME v7.5, there is a new type of container:
643 *Homogeneous Pool of SALOME containers* (HP container).
644 It is possible to create this type of container this way::
645
646    my_hp_cont=r.createContainer("MyHPCont","HPSalome")
647
648 - "MyHPCont" : name of the container. Same result as my_hp_cont.setName("MyHPCont").
649 - "HPSalome" : type of container. Possible values are "HPSalome" (for a HP container)
650   or "Salome" (for a classic container).
651
652 Node properties
653 '''''''''''''''''''''''''''
654 A property is added to an elementary or composite node (or is modified) using its setProperty method that has two 
655 arguments (character strings).  The first is the name of the property.  The second is its value.
656 The following is an example for the previous node “node3”::
657
658   n3.setProperty("VERBOSE","2")
659
660 Datastream connections
661 '''''''''''''''''''''''''''
662 Datastream connections are only possible for SALOME service nodes as we have seen in :ref:`principes`.  
663 We firstly need to define the datastream ports in the service node.  An input datastream port is defined using 
664 the edAddInputDataStreamPort method.  An output datastream port is defined using the edAddOutputDataStreamPort method.  
665 These methods use the port name and the datastream type as arguments.
666
667 Some datastream ports (for example CALCIUM ports) must be configured with properties.  The port setProperty method will 
668 be used to configure them.
669 The following is an example definition of the SALOME service node with datastream ports.  This is the DSCCODC component 
670 located in the DSCCODES module in the EXAMPLES base.  The datastream ports are of the “CALCIUM_integer” type 
671 with time dependency::
672
673   calcium_int=cata._typeMap['CALCIUM_integer']
674   n5=r.createCompoNode("","node5")
675   p.edAddChild(n5)
676   n5.setRef("DSCCODC")
677   n5.setMethod("prun")
678   pin=n5.edAddInputDataStreamPort("ETP_EN",calcium_int)
679   pin.setProperty("DependencyType","TIME_DEPENDENCY")
680   pout=n5.edAddOutputDataStreamPort("STP_EN",calcium_int)
681   pout.setProperty("DependencyType","TIME_DEPENDENCY")
682
683 Once the service nodes have been provided with datastream ports, all that remains is to connect them.  
684 This connection is made using the edAddLink method for the context node in the same way as for data links.  
685 The only difference is the type of ports transferred as arguments.
686
687 To complete our example, we will define a second service node and connect the datastream ports for these services::
688
689   n6=r.createCompoNode("","node6")
690   p.edAddChild(n6)
691   n6.setRef("DSCCODD")
692   n6.setMethod("prun")
693   pin=n6.edAddInputDataStreamPort("ETP_EN",calcium_int)
694   pin.setProperty("DependencyType","TIME_DEPENDENCY")
695   pout=n6.edAddOutputDataStreamPort("STP_EN",calcium_int)
696   pout.setProperty("DependencyType","TIME_DEPENDENCY")
697   p.edAddLink(n5.getOutputDataStreamPort("STP_EN"),n6.getInputDataStreamPort("ETP_EN"))
698   p.edAddLink(n6.getOutputDataStreamPort("STP_EN"),n5.getInputDataStreamPort("ETP_EN"))
699
700 Other elementary nodes
701 '''''''''''''''''''''''''''''''
702 SalomePython node
703 +++++++++++++++++++
704 A SalomePython node is defined in practically exactly the same way as a :ref:`pyfunc`.  The runtime createSInlineNode method is used 
705 instead of the createFuncNode and information about placement on a container is added in the same way as for a 
706 SALOME service node (setContainer method).
707
708 The following is an example similar to that given in :ref:`schemaxml`::
709
710   n2=r.createSInlineNode("","node2")
711   p.edAddChild(n2)
712   n2.setScript("""
713   import salome
714   salome.salome_init()
715   import PYHELLO_ORB
716   def f(p1):
717     print __container__from__YACS__
718     machine,container=__container__from__YACS__.split('/')
719     param={'hostname':machine,'container_name':container}
720     compo=salome.lcc.LoadComponent(param, "PYHELLO")
721     print compo.makeBanner(p1)
722     print p1
723   """)
724   n2.setFname("f")
725   n2.edAddInputPort("p1",ts)
726   n2.getComponent().setContainer(c1)
727
728 .. _py_datain:
729
730 DataIn node
731 +++++++++++++++
732 A DataIn node is defined using the runtime createInDataNode method.  It uses two arguments, the first of which must be “” and 
733 the second the node name.  Node data are defined by adding output data ports to it using the edAddOutputPort method 
734 and transferring the data name and its type to it as arguments.  
735 The value of the data is initialised using the port setData method thus created by transferring the value encoded in 
736 XML-RPC to it (see :ref:`initialisation`).
737
738 The following is an example of the DataIn node that defines 2 double type data (b and c) and one file type data (f)::
739
740   n=r.createInDataNode("","data1")
741   p.edAddChild(n)
742   pout=n.edAddOutputPort('a',td)
743   pout.setData("<value><double>-1.</double></value>")
744   pout=n.edAddOutputPort('b',td)
745   pout.setData("<value><double>5.</double></value>")
746   pout=n.edAddOutputPort('f',tf)
747   pout.setData("<value><objref>f.data</objref></value>")
748   
749 A value can be directly assigned to a data with a Python object, using the setDataPy method.  Example for a sequence::
750
751   pout.setDataPy([1.,5.])
752
753 .. _py_dataout:
754
755 DataOut node
756 +++++++++++++++++
757 A DataOut node is defined using the runtime createOutDataNode method.  It uses two arguments, the first of which 
758 must be “” and the second the node name .  Node results are defined by adding input data ports to it using the edAddInputPort 
759 method with the result name and its type as arguments.  The results are saved in a file using the node setRef method with the 
760 file name as an argument.  
761 A result file is copied into a local file using the setData method for the port corresponding to the result with the 
762 file name as an argument.
763
764 The following is an example of the DataOut node that defines different types (double, int, string, doubles vector, file) of 
765 results (a, b, c, d, f) and writes the corresponding values in the g.data file.  
766 The result file will be copied into the local file myfile::
767
768   n=r.createOutDataNode("","data2")
769   n.setRef("g.data")
770   p.edAddChild(n)
771   n.edAddInputPort('a',td)
772   n.edAddInputPort('b',ti)
773   n.edAddInputPort('c',ts)
774   n.edAddInputPort('d',tc3)
775   pin=n.edAddInputPort('f',tf)
776   pin.setData("monfich")
777
778 .. _py_studyin:
779
780 StudyIn node
781 ++++++++++++++
782 A StudyIn node is defined using the runtime createInDataNode method.  It uses two arguments, the first of which must be “study” 
783 and the second the node name.  Node data are defined by adding output data ports using the edAddOutputPOrt method, transferring 
784 the name of the data and its type as arguments.  The data is initialised with the reference in the study, using the setData method 
785 for the port thus created, transferring a character string to it containing either the SALOME Entry or the path in the study 
786 tree structure.
787
788 The following is an example of the StudyIn node that defines 2 GEOM_Object type data (a and b).  The study is assumed to be 
789 loaded into memory by SALOME.  Data a is referenced by one SALOME Entry.  Data b is referenced by a path in the 
790 study tree structure::
791
792   n=r.createInDataNode("study","study1")
793   p.edAddChild(n)
794   pout=n.edAddOutputPort('a',tgeom)
795   pout.setData("0:1:1:1")
796   pout=n.edAddOutputPort('b',tgeom)
797   pout.setData("/Geometry/Sphere_1")
798
799 .. _py_studyout:
800
801 StudyOut node
802 ++++++++++++++
803 A StudyOut node is defined using the runtime createOutDataNode method.  It uses two arguments, the first of 
804 which must be “study” and the second the node name. The name of the file in which the study will be 
805 saved is specified using the node SetRef method with the file name as an argument.  
806 The node results are defined by adding input data ports to it using the edAddInputPort method, transferring the data name 
807 and type as arguments.  The setData method for the port is used to associate the entry into the study to the result, transferring 
808 a character string to it that contains either the SALOME Entry or the path in the study tree structure.
809
810 The following contains an example of the StudyOut node that defines two GEOM_Object type results (a and b).  
811 Result a is referenced by a SALOME Entry.  The result b is referenced by a path.  
812 The complete study is saved in the study1.hdf file at the end of the calculation::
813
814   n=r.createOutDataNode("study","study2")
815   n.setRef("study1.hdf")
816   p.edAddChild(n)
817   pout=n.edAddInputPort('a',tgeom)
818   pout.setData("0:1:2:1")
819   pout=n.edAddInputPort('b',tgeom)
820   pout.setData("/Save/Sphere_2")
821
822 Save a calculation scheme in an XML file
823 ------------------------------------------------------
824 A calculation scheme is saved in a file in the XML format using the saveSchema method for the calculation 
825 scheme, transferring the file name to it as an argument.  Before a calculation scheme constructed under Python 
826 can be saved in a consistent form in an XML file, all types defined in Python have to be added to the scheme types 
827 dictionary (see :ref:`typedict`).  The save will not do this automatically.
828
829 Proceed as follows to save the scheme p constructed above in the myscheme.xml file::
830
831   p.saveSchema("monschema.xml")
832
833 The file thus obtained can then be loaded as in :ref:`loadxml`.
834
835 Several useful operations
836 ------------------------------
837
838 Finding a node by its name
839 '''''''''''''''''''''''''''''''''''
840 A node (Python object) can be found, when all that is available is the calculation scheme object and 
841 the absolute name of the node, by calling the scheme getChildByName method, transferring the absolute name to it.
842
843 To find the Python script node defined in :ref:`pyscript`::
844
845   n=p.getChildByName("node1")
846
847 To find node “node1” node in block “b1”::
848
849   n=p.getChildByName("b1.node1")
850
851 This operation can also be used starting from a composite node provided that the relative node name is used.  
852 The previous example can be rewritten::
853
854   n=b.getChildByName("node1")
855
856 Finding a port by its name
857 '''''''''''''''''''''''''''''''''''
858 The first step to find a node port by its name is to retrieve the node by its name.  An input data port is then found 
859 using the getInputPort method, and an output data port is found using the getOutputPort method.
860
861 The following is an example starting from the previous node n::
862
863   pin=n.getOutputPort("p1")
864   pout=n.getInputPort("p2")
865
866 Obtaining a port value
867 '''''''''''''''''''''''''''''''''''
868 The value of a port is obtained using its getPyObj method.  For example::
869
870   print pin.getPyObj()
871   print pout.getPyObj()
872
873 Obtaining the state of a node
874 '''''''''''''''''''''''''''''''''''
875 The state of a node is obtained using its getEffectiveState method (see possible values in :ref:`etats`).
876
877 Removing a node from its context
878 '''''''''''''''''''''''''''''''''''
879 A node can be removed from its context node using a context method.  The method name will be different 
880 depending on the context type.
881
882 - For a block or a calculation scheme, the edRemoveChild method will be used with the node to be removed as an argument::
883
884     p.edRemoveChild(n)
885
886 - For a loop (ForLoop, WhileLoop or ForEachLoop) the edRemoveNode method will be used without any argument::
887  
888     l.edRemoveNode()
889
890 - The edRemoveChild method will be used for a Switch, with the internal node concerned as an argument::
891
892     sw.edRemoveChild(nk1)
893