Salome HOME
Join modifications from branch BR_DEBUG_3_2_0b1
[modules/kernel.git] / src / KERNEL_PY / salome_test.py
1 #  SALOME SALOME_SWIG : binding of C++ implementation and Python
2 #
3 #  Copyright (C) 2003  CEA/DEN, EDF R&D
4 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
5 #
6 #
7 #  File   : salome_test.py
8 #  Module : SALOME
9
10 print "Test the application loading  GEOM, SMESH, VISU, MED, components and doing some"
11 print "operation within the components."
12
13 import salome
14 from salome import sg
15 import SALOMEDS
16 import os
17
18 import SALOME_ModuleCatalog
19
20 print "======================================================================"
21 print "           Check, that there is no data of MED component in the Study "
22 print "======================================================================"
23
24 MedComp = salome.myStudy.FindComponent("MED")
25 if MedComp is not None:
26         print ""
27         print "This script cannot work properly, because there are"
28         print "some MED component data already exists in the study."
29         print "Execution aborted."
30         print ""
31         raise RuntimeError, "Please, run this script only in a new empty study."
32
33 print "======================================================================"
34 print "           Get Catalog "
35 print "======================================================================"
36 obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
37 catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
38
39 print "======================================================================"
40 print "           Create Study "
41 print "======================================================================"
42
43 comp = catalog.GetComponent("GEOM")
44 if comp is None:
45         raise RuntimeError,"Component GEOM not found in Module Catalog."
46
47 import geompy
48
49 print "================================="
50 print "       create AttributeReal      "
51 print "================================="
52 A = geompy.myBuilder.FindOrCreateAttribute(geompy.father, "AttributeReal")
53 if A == None :
54         raise  RuntimeError, "Can't create AttributeReal attribute"
55 A = A._narrow(SALOMEDS.AttributeReal)
56 A.SetValue(0.0001)
57 if A.Value() != 0.0001:
58         raise  RuntimeError, "Error : wrong value of  AttributeReal"
59
60 print
61 print " ===========  Test Geometry  =========================="
62 print
63
64 print "==================================="
65 print "     define a box"
66 print "==================================="
67
68 box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
69 idbox = geompy.addToStudy(box,"box")
70
71 print
72 print "=============  Test SMESH  ============================="
73 print
74
75 import StdMeshers
76
77 comp = catalog.GetComponent("SMESH")
78 if comp is None:
79         raise RuntimeError,"Component SMESH not found in Module Catalog."
80
81 comp = catalog.GetComponent("MED")
82 if comp is None:
83         raise RuntimeError,"Component MED not found in Module Catalog."
84
85 import SMESH
86
87 geom = salome.lcc.FindOrLoadComponent("FactoryServer", "GEOM")
88 myBuilder = salome.myStudy.NewBuilder()
89
90 smesh = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
91 smeshgui = salome.ImportComponentGUI("SMESH")
92 smeshgui.Init(salome.myStudyId);
93
94 ShapeTypeCompSolid = 1
95 ShapeTypeSolid = 2
96 ShapeTypeShell = 3
97 ShapeTypeFace = 4
98 ShapeTypeWire = 5
99 ShapeTypeEdge = 6
100 ShapeTypeVertex = 7
101
102 # ---- define a box
103
104 box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
105 idbox = geompy.addToStudy(box,"box")
106
107 # ---- add first face of box in study
108
109 subShapeList=geompy.SubShapeAll(box,ShapeTypeFace)
110 face=subShapeList[0]
111 name = geompy.SubShapeName(face, box)
112 print name
113 idface=geompy.addToStudyInFather(box,face,name)
114
115 # ---- add shell from box  in study
116
117 subShellList=geompy.SubShapeAll(box,ShapeTypeShell)
118 shell = subShellList[0]
119 name = geompy.SubShapeName(shell, box)
120 print name
121 idshell=geompy.addToStudyInFather(box,shell,name)
122
123 # ---- add first edge of face in study
124
125 edgeList = geompy.SubShapeAll(face,ShapeTypeEdge)
126 edge=edgeList[0];
127 name = geompy.SubShapeName(edge, face)
128 print name
129 idedge=geompy.addToStudyInFather(face,edge,name)
130
131
132 # ---- SMESH 
133
134 # ---- create Hypothesis
135
136 print "-------------------------- create Hypothesis"
137 print "-------------------------- LocalLength"
138 hypLen1 = smesh.CreateHypothesis( "LocalLength", "libStdMeshersEngine.so" )
139 hypLen1.SetLength(100)
140 print hypLen1.GetName()
141 print hypLen1.GetId()
142 print hypLen1.GetLength()
143
144 smeshgui.SetName(salome.ObjectToID(hypLen1), "Local_Length_100")
145
146 print "-------------------------- NumberOfSegments"
147 hypNbSeg1= smesh.CreateHypothesis( "NumberOfSegments", "libStdMeshersEngine.so" )
148 hypNbSeg1.SetNumberOfSegments(7)
149 print hypNbSeg1.GetName()
150 print hypNbSeg1.GetId()
151 print hypNbSeg1.GetNumberOfSegments()
152
153 smeshgui.SetName(salome.ObjectToID(hypNbSeg1), "NumberOfSegments_7")
154
155 print "-------------------------- MaxElementArea"
156 hypArea1 = smesh.CreateHypothesis( "MaxElementArea", "libStdMeshersEngine.so" )
157 hypArea1.SetMaxElementArea(2500)
158 print hypArea1.GetName()
159 print hypArea1.GetId()
160 print hypArea1.GetMaxElementArea()
161
162 smeshgui.SetName(salome.ObjectToID(hypArea1), "MaxElementArea_2500")
163
164 print "-------------------------- MaxElementArea"
165 hypArea2 = smesh.CreateHypothesis( "MaxElementArea", "libStdMeshersEngine.so" )
166 hypArea2.SetMaxElementArea(500)
167 print hypArea2.GetName()
168 print hypArea2.GetId()
169 print hypArea2.GetMaxElementArea()
170
171 smeshgui.SetName(salome.ObjectToID(hypArea2), "MaxElementArea_500")
172
173 print "-------------------------- Regular_1D"
174 algoReg = smesh.CreateHypothesis( "Regular_1D", "libStdMeshersEngine.so" )
175 listHyp=algoReg.GetCompatibleHypothesis()
176 for hyp in listHyp:
177     print hyp
178 print algoReg.GetName()
179 print algoReg.GetId()
180
181 smeshgui.SetName(salome.ObjectToID(algoReg), "Regular_1D" )
182
183 print "-------------------------- MEFISTO_2D"
184 algoMef = smesh.CreateHypothesis( "MEFISTO_2D", "libStdMeshersEngine.so" )
185 listHyp=algoMef.GetCompatibleHypothesis()
186 for hyp in listHyp:
187     print hyp
188 print algoMef.GetName()
189 print algoMef.GetId()
190
191 smeshgui.SetName(salome.ObjectToID(algoMef), "MEFISTO_2D" )
192
193 # ---- add hypothesis to box
194
195 print "-------------------------- add hypothesis to box"
196 box=salome.IDToObject(idbox)
197 mesh = smesh.CreateMesh(box)
198
199 smeshgui.SetName( salome.ObjectToID(mesh), "MeshBox" );
200
201 ret=mesh.AddHypothesis(box,algoReg)
202 print ret
203 ret=mesh.AddHypothesis(box,algoMef)
204 print ret
205
206
207 ret=mesh.AddHypothesis(box,hypNbSeg1)
208 print ret
209 ret=mesh.AddHypothesis(box,hypArea1)
210 print ret
211
212
213 # ---- add hypothesis to edge
214
215 print "-------------------------- add hypothesis to edge"
216 edge=salome.IDToObject(idedge)
217 submesh=mesh.GetSubMesh(edge, "SubMeshEdge")
218
219 ret=mesh.AddHypothesis(edge,algoReg)
220 print ret
221 ret=mesh.AddHypothesis(edge,hypLen1)
222 print ret
223
224 print "-------------------------- add hypothesis to face"
225 face=salome.IDToObject(idface)
226 submesh   = mesh.GetSubMesh(face, "SubMeshFace")
227
228 ret=mesh.AddHypothesis(face,hypArea2)
229 print ret
230
231 smesh.Compute(mesh, box)
232 sg.updateObjBrowser(1);
233
234 print
235 print "=============  Test  Supervisor  ============================="
236 print
237
238 comp = catalog.GetComponent("SUPERV")
239 if comp is None:
240         raise RuntimeError,"Component SUPERV not found in Module Catalog."
241
242 from SuperV import *
243 import SALOMEDS
244 myStudy = salome.myStudy
245 myBuilder = myStudy.NewBuilder()
246
247 SuperVision = lcc.FindOrLoadComponent("SuperVisionContainer","SUPERV")
248 father = myStudy.FindComponent("SUPERV")
249 if father is None:
250         father = myBuilder.NewComponent("SUPERV")
251         A1 = myBuilder.FindOrCreateAttribute(father, "AttributeName");
252         FName = A1._narrow(SALOMEDS.AttributeName)
253         FName.SetValue( salome.sg.getComponentUserName("SUPERV") )
254         A2 = myBuilder.FindOrCreateAttribute(father, "AttributePixMap");
255         aPixmap = A2._narrow(SALOMEDS.AttributePixMap);
256         aPixmap.SetPixMap( "ICON_OBJBROWSER_Supervision" );
257         myBuilder.DefineComponentInstance(father,SuperVision)
258
259 def addStudy(ior):
260     dataflow = SuperVision.getStreamGraph(ior)
261     name=dataflow.Name()
262     itr = myStudy.NewChildIterator(father)
263     while itr.More():
264         item=itr.Value()
265         res,A=item.FindAttribute("AttributeName")
266         if res:
267             aName = A._narrow(SALOMEDS.AttributeName)
268             if aName.Value() == name :
269                 print myBuilder.FindOrCreateAttribute(item, "AttributeIOR")
270                 A  = myBuilder.FindOrCreateAttribute(item, "AttributeIOR")
271                 print "A = ", A
272                 if A is not None :
273                    #res,A = myBuilder.FindOrCreateAttribute(item, "AttributeIOR")
274                    anIOR  = A._narrow(SALOMEDS.AttributeIOR);
275                    print "anIOR.SetValue(dataflow.getIOR())"
276                    anIOR.SetValue(dataflow.getIOR()) 
277                 return
278         itr.Next()
279     obj = myBuilder.NewObject(father)
280     A=myBuilder.FindOrCreateAttribute(obj, "AttributeName")
281     aName=A._narrow(SALOMEDS.AttributeName)
282     aName.SetValue(name)
283     A=myBuilder.FindOrCreateAttribute(obj, "AttributeIOR")
284     anIOR  = A._narrow(SALOMEDS.AttributeIOR)
285     anIOR.SetValue(dataflow.getIOR())
286
287 import os
288 dir= os.getenv("DATA_DIR")
289 if dir == None:
290         raise RuntimeError, "DATA_DIR is not defined"
291 xmlfile = dir + "/Superv/Graphs/GraphGeomEssaiGates.xml"
292 print "Load dataflow from the file : "
293 print xmlfile
294 print
295
296 myGraph = StreamGraph ( xmlfile )
297
298 # This DataFlow is "valid" : no loop, correct links between Nodes etc...
299 print "myGraph.IsValid() = ", myGraph.IsValid()
300
301 # Get Nodes
302 myGraph.PrintNodes()
303
304 # This DataFlow is "executable" : all pending Ports are defined with Datas
305 print myGraph.IsExecutable()
306
307 # Starts only execution of that DataFlow and gets control immediatly
308 print myGraph.Run()
309
310 # That DataFlow is running ==> 0 (false)
311 print myGraph.IsDone()
312
313 # Events of execution :
314 aStatus,aNode,anEvent,aState = myGraph.Event()
315 while aStatus :
316     print aNode.Thread(),aNode.SubGraph(),aNode.Name(),anEvent,aState
317     aStatus,aNode,anEvent,aState = myGraph.Event()
318 print "myGraph.IsDone() = ",myGraph.IsDone()
319
320 # Wait for Completion (but it is already done after event loop ...)
321 print "Done : ",myGraph.DoneW()
322
323 print " "
324 #print "Type : print myGraph.IsDone()"
325 #print "       If execution is finished ==> 1 (true)"
326 res=myGraph.IsDone()
327 if res != 1:
328         raise RuntimeError, "myGraph.Run() is not done"
329
330 print " "
331 print "Type : myGraph.PrintPorts()"
332 print "       to see input and output values of the graph"
333 myGraph.PrintPorts()
334
335 # Export will create newsupervisionexample.xml and the corresponding .py file
336 tmpdir=os.getenv("TmpDir")
337 if tmpdir is None:
338         tmpdir="/tmp"
339 file = tmpdir + "/newsupervisionexample"
340 print "--------------\n"+file+"\n--------------\n"
341 myGraph.Export(file)
342
343 ior = salome.orb.object_to_string(myGraph.G)
344 addStudy(ior)
345
346 GraphName = myGraph.Name()
347 print "Befor save ",
348 #nodes = myGraph.Nodes()
349 nodes = myGraph.G.Nodes().FNodes
350 length_bs = len(nodes)
351 print "ListOfNodes length = ", length_bs
352 names=[]
353 for node in nodes:
354         names.append(node.Name())
355 print names
356
357 # Graph creation 
358 GraphInLines = StreamGraph( 'GraphInLines' )
359 GraphInLines.SetName( 'GraphInLines' )
360 GraphInLines.SetAuthor( '' )
361 GraphInLines.SetComment( '' )
362 GraphInLines.Coords( 0 , 0 )
363
364 # Creation of InLine Nodes
365 PyAdd = []
366 PyAdd.append( 'def Add(a,b) :  ' )
367 PyAdd.append( '    return a+b  ' )
368 PyAdd.append( '' )
369 Add = GraphInLines.INode( 'Add' , PyAdd )
370 Add.InPort( 'a' , 'long' )
371 Add.InPort( 'b' , 'long' )
372 Add.OutPort( 'f' , 'long' )
373 Add.SetName( 'Add' )
374 Add.SetAuthor( '' )
375 Add.SetComment( 'Python function' )
376 Add.Coords( 351 , 77 )
377 PySub = []
378 PySub.append( 'def Sub(a,b) : ' )
379 PySub.append( '    return a-b ' )
380 PySub.append( '' )
381 Sub = GraphInLines.INode( 'Sub' , PySub )
382 Sub.InPort( 'a' , 'long' )
383 Sub.InPort( 'b' , 'long' )
384 Sub.OutPort( 'f' , 'long' )
385 Sub.SetName( 'Sub' )
386 Sub.SetAuthor( '' )
387 Sub.SetComment( 'Python function' )
388 Sub.Coords( 86 , 333 )
389 PyMul = []
390 PyMul.append( 'def Mul(a,b) : ' )
391 PyMul.append( '    return a*b ' )
392 Mul = GraphInLines.INode( 'Mul' , PyMul )
393 Mul.InPort( 'a' , 'long' )
394 Mul.InPort( 'b' , 'long' )
395 Mul.OutPort( 'Result' , 'long' )
396 Mul.SetName( 'Mul' )
397 Mul.SetAuthor( '' )
398 Mul.SetComment( 'Python function' )
399 Mul.Coords( 616 , 247 )
400
401 # Creation of intermediate Output variables and of Control Links
402 Addf = Add.Port( 'f' )
403 Mula = GraphInLines.Link( Addf , Mul.Port( 'a' ) )
404 Mula.AddCoord( 1 , 570 , 356 )
405 Mula.AddCoord( 2 , 570 , 186 )
406 Subf = Sub.Port( 'f' )
407 Mulb = GraphInLines.Link( Subf , Mul.Port( 'b' ) )
408 Mulb.AddCoord( 1 , 282 , 376 )
409 Mulb.AddCoord( 2 , 282 , 442 )
410 Addb = GraphInLines.Link( Subf , Add.Port( 'b' ) )
411 Addb.AddCoord( 1 , 283 , 209 )
412 Addb.AddCoord( 2 , 283 , 374 )
413 Addb.AddCoord( 3 , 283 , 442 )
414
415 # Creation of Input datas
416 Adda = Add.Input( 'a' , 1)
417 Suba = Sub.Input( 'a' , 3)
418 Subb = Sub.Input( 'b' , 4)
419
420 # Creation of Output variables
421 MulResult = Mul.Port( 'Result' )
422
423 GraphInLines.Run()
424
425 GraphInLines.DoneW()
426
427 GraphInLines.PrintPorts()
428
429 sg.updateObjBrowser(1);
430
431 print
432 print "=============  Test  VISU  and MED ============================="
433 print
434
435 comp = catalog.GetComponent("VISU")
436 if comp is None:
437         raise RuntimeError,"Component VISU not found in Module Catalog."
438
439 import sys
440 import SALOMEDS
441 import SALOME
442 import SALOME_MED
443 import VISU
444
445 import visu_gui
446
447 medFileName = "pointe.med"
448 medFile = os.getenv('DATA_DIR') + '/MedFiles/' + medFileName
449 print "Load ", medFile
450
451 studyCurrent = salome.myStudyName
452
453 med_comp = salome.lcc.FindOrLoadComponent("FactoryServer", "MED")
454 myVisu = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU")
455
456 try:
457     if os.access(medFile, os.R_OK) :
458        if not os.access(medFile, os.W_OK) :
459                import random
460                medFileNew = "/tmp/" + str(random.randint(0,1000000)) + "_" + medFileName
461                print " -- Copy " + medFile + " to " + medFileNew
462                os.system("cp "+ medFile + " " + medFileNew)
463                medFile = medFileNew
464                os.system("chmod 755 " + medFile)
465
466        if os.access(medFile, os.W_OK) :
467            med_comp.readStructFileWithFieldType(medFile,studyCurrent)
468            med_obj = visu_gui.visu.getMedObjectFromStudy()
469            print "med_obj - ", med_obj
470
471            myField1 = visu_gui.visu.getFieldObjectFromStudy(2,1)
472            aMeshName = "maa1"
473            anEntity = VISU.NODE
474            aTimeStampId = -1
475                    
476            myResult1 = myVisu.ImportMedField(myField1)
477            aMesh1 = myVisu.MeshOnEntity(myResult1, aMeshName, anEntity);
478            
479            aScalarMap1= myVisu.ScalarMapOnField(myResult1, aMeshName, anEntity, myField1.getName(), aTimeStampId)
480            
481            myResult2 = myVisu.ImportFile(medFile);
482            aMesh2 = myVisu.MeshOnEntity(myResult2, aMeshName, anEntity);
483            
484            aTimeStampId = 3
485            aScalarMap2= myVisu.ScalarMapOnField(myResult2, aMeshName, anEntity, myField1.getName(), aTimeStampId)
486                    
487            sg.updateObjBrowser(0)
488        else :  print "We have no permission to rewrite medFile, so readStructFileWithFieldType can't open this file";
489     else :  print  "We have no permission to read medFile, it will not be opened"; 
490
491 except:
492     if sys.exc_type == SALOME.SALOME_Exception :
493         print "There is no permission to read " + medFile
494     else :
495         print sys.exc_type 
496         print sys.exc_value
497         print sys.exc_traceback
498
499 sg.updateObjBrowser(1);