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