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