Salome HOME
Merged from BR_V51_RB (removed Batch and added libBatch as an optional prerequisite).
[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 #####################################################################
257 # SUPERVISOR module is not available since SALOME 5.0 version
258 #####################################################################
259 print
260 print "=============  Test      Supervisor      ============================="
261 print
262 import salome_version
263 versions = salome_version.getVersions()
264 if versions[0] < 5:
265         # SUPERV module is avaiable
266         comp = catalog.GetComponent("SUPERV")
267         if comp is None:
268                 raise RuntimeError,"Component SUPERV not found in Module Catalog."
269
270         from SuperV import *
271         import SALOMEDS
272         myStudy = salome.myStudy
273         myBuilder = myStudy.NewBuilder()
274
275         SuperVision = lcc.FindOrLoadComponent("SuperVisionContainer","SUPERV")
276         father = myStudy.FindComponent("SUPERV")
277         if father is None:
278                 father = myBuilder.NewComponent("SUPERV")
279                 A1 = myBuilder.FindOrCreateAttribute(father, "AttributeName");
280                 FName = A1._narrow(SALOMEDS.AttributeName)
281                 FName.SetValue( salome.sg.getComponentUserName("SUPERV") )
282                 A2 = myBuilder.FindOrCreateAttribute(father, "AttributePixMap");
283                 aPixmap = A2._narrow(SALOMEDS.AttributePixMap);
284                 aPixmap.SetPixMap( "ICON_OBJBROWSER_Supervision" );
285                 myBuilder.DefineComponentInstance(father,SuperVision)
286
287         def addStudy(ior):
288                 dataflow = SuperVision.getStreamGraph(ior)
289                 name=dataflow.Name()
290                 itr = myStudy.NewChildIterator(father)
291                 while itr.More():
292                         item=itr.Value()
293                         res,A=item.FindAttribute("AttributeName")
294                         if res:
295                                 aName = A._narrow(SALOMEDS.AttributeName)
296                                 if aName.Value() == name :
297                                         print myBuilder.FindOrCreateAttribute(item, "AttributeIOR")
298                                         A  = myBuilder.FindOrCreateAttribute(item, "AttributeIOR")
299                                         print "A = ", A
300                                         if A is not None :
301                                                 #res,A = myBuilder.FindOrCreateAttribute(item, "AttributeIOR")
302                                                 anIOR  = A._narrow(SALOMEDS.AttributeIOR);
303                                                 print "anIOR.SetValue(dataflow.getIOR())"
304                                                 anIOR.SetValue(dataflow.getIOR()) 
305                                         return
306                         itr.Next()
307                 obj = myBuilder.NewObject(father)
308                 A=myBuilder.FindOrCreateAttribute(obj, "AttributeName")
309                 aName=A._narrow(SALOMEDS.AttributeName)
310                 aName.SetValue(name)
311                 A=myBuilder.FindOrCreateAttribute(obj, "AttributeIOR")
312                 anIOR  = A._narrow(SALOMEDS.AttributeIOR)
313                 anIOR.SetValue(dataflow.getIOR())
314
315         import os
316         dir= os.getenv("DATA_DIR")
317         if dir == None:
318                 raise RuntimeError, "DATA_DIR is not defined"
319         xmlfile = dir + "/Superv/Graphs/GraphGeomEssaiGates.xml"
320         print "Load dataflow from the file : "
321         print xmlfile
322         print
323
324         myGraph = StreamGraph ( xmlfile )
325
326         # This DataFlow is "valid" : no loop, correct links between Nodes etc...
327         print "myGraph.IsValid() = ", myGraph.IsValid()
328
329         # Get Nodes
330         myGraph.PrintNodes()
331
332         # This DataFlow is "executable" : all pending Ports are defined with Datas
333         print myGraph.IsExecutable()
334
335         # Starts only execution of that DataFlow and gets control immediatly
336         print myGraph.Run()
337
338         # That DataFlow is running ==> 0 (false)
339         print myGraph.IsDone()
340
341         # Events of execution :
342         aStatus,aNode,anEvent,aState = myGraph.Event()
343         while aStatus :
344                 print aNode.Thread(),aNode.SubGraph(),aNode.Name(),anEvent,aState
345                 aStatus,aNode,anEvent,aState = myGraph.Event()
346         print "myGraph.IsDone() = ",myGraph.IsDone()
347
348         # Wait for Completion (but it is already done after event loop ...)
349         print "Done : ",myGraph.DoneW()
350
351         print " "
352         #print "Type : print myGraph.IsDone()"
353         #print "       If execution is finished ==> 1 (true)"
354         res=myGraph.IsDone()
355         if res != 1:
356                 raise RuntimeError, "myGraph.Run() is not done"
357
358         print " "
359         print "Type : myGraph.PrintPorts()"
360         print "       to see input and output values of the graph"
361         myGraph.PrintPorts()
362
363         # Export will create newsupervisionexample.xml and the corresponding .py file
364         tmpdir=os.getenv("TmpDir")
365         if tmpdir is None:
366                 tmpdir="/tmp"
367         file = tmpdir + "/newsupervisionexample"
368         print "--------------\n"+file+"\n--------------\n"
369         myGraph.Export(file)
370
371         ior = salome.orb.object_to_string(myGraph.G)
372         addStudy(ior)
373
374         GraphName = myGraph.Name()
375         print "Befor save ",
376         #nodes = myGraph.Nodes()
377         nodes = myGraph.G.Nodes().FNodes
378         length_bs = len(nodes)
379         print "ListOfNodes length = ", length_bs
380         names=[]
381         for node in nodes:
382                 names.append(node.Name())
383         print names
384
385         # Graph creation 
386         GraphInLines = StreamGraph( 'GraphInLines' )
387         GraphInLines.SetName( 'GraphInLines' )
388         GraphInLines.SetAuthor( '' )
389         GraphInLines.SetComment( '' )
390         GraphInLines.Coords( 0 , 0 )
391
392         # Creation of InLine Nodes
393         PyAdd = []
394         PyAdd.append( 'def Add(a,b) :  ' )
395         PyAdd.append( '    return a+b  ' )
396         PyAdd.append( '' )
397         Add = GraphInLines.INode( 'Add' , PyAdd )
398         Add.InPort( 'a' , 'long' )
399         Add.InPort( 'b' , 'long' )
400         Add.OutPort( 'f' , 'long' )
401         Add.SetName( 'Add' )
402         Add.SetAuthor( '' )
403         Add.SetComment( 'Python function' )
404         Add.Coords( 351 , 77 )
405         PySub = []
406         PySub.append( 'def Sub(a,b) : ' )
407         PySub.append( '    return a-b ' )
408         PySub.append( '' )
409         Sub = GraphInLines.INode( 'Sub' , PySub )
410         Sub.InPort( 'a' , 'long' )
411         Sub.InPort( 'b' , 'long' )
412         Sub.OutPort( 'f' , 'long' )
413         Sub.SetName( 'Sub' )
414         Sub.SetAuthor( '' )
415         Sub.SetComment( 'Python function' )
416         Sub.Coords( 86 , 333 )
417         PyMul = []
418         PyMul.append( 'def Mul(a,b) : ' )
419         PyMul.append( '    return a*b ' )
420         Mul = GraphInLines.INode( 'Mul' , PyMul )
421         Mul.InPort( 'a' , 'long' )
422         Mul.InPort( 'b' , 'long' )
423         Mul.OutPort( 'Result' , 'long' )
424         Mul.SetName( 'Mul' )
425         Mul.SetAuthor( '' )
426         Mul.SetComment( 'Python function' )
427         Mul.Coords( 616 , 247 )
428
429         # Creation of intermediate Output variables and of Control Links
430         Addf = Add.Port( 'f' )
431         Mula = GraphInLines.Link( Addf , Mul.Port( 'a' ) )
432         Mula.AddCoord( 1 , 570 , 356 )
433         Mula.AddCoord( 2 , 570 , 186 )
434         Subf = Sub.Port( 'f' )
435         Mulb = GraphInLines.Link( Subf , Mul.Port( 'b' ) )
436         Mulb.AddCoord( 1 , 282 , 376 )
437         Mulb.AddCoord( 2 , 282 , 442 )
438         Addb = GraphInLines.Link( Subf , Add.Port( 'b' ) )
439         Addb.AddCoord( 1 , 283 , 209 )
440         Addb.AddCoord( 2 , 283 , 374 )
441         Addb.AddCoord( 3 , 283 , 442 )
442
443         # Creation of Input datas
444         Adda = Add.Input( 'a' , 1)
445         Suba = Sub.Input( 'a' , 3)
446         Subb = Sub.Input( 'b' , 4)
447
448         # Creation of Output variables
449         MulResult = Mul.Port( 'Result' )
450
451         GraphInLines.Run()
452
453         GraphInLines.DoneW()
454
455         GraphInLines.PrintPorts()
456
457         sg.updateObjBrowser(1);
458
459         pass
460 else:
461         # SUPERV module is NOT avaiable
462         print "WARNING! Supervisor is not avaiable in this version of SALOME!"
463         pass
464
465 print
466 print "=============  Test  VISU  and MED ============================="
467 print
468
469 comp = catalog.GetComponent("VISU")
470 if comp is None:
471         raise RuntimeError,"Component VISU not found in Module Catalog."
472
473 import sys
474 import SALOMEDS
475 import SALOME
476 import SALOME_MED
477 import VISU
478
479 import visu_gui
480
481 medFileName = "pointe.med"
482 if sys.platform != "win32":
483     medFile = os.getenv('DATA_DIR') + '/MedFiles/' + medFileName
484 else:
485     medFile = os.getenv('DATA_DIR') + '\\MedFiles\\' + medFileName
486     pass
487 print "Load ", medFile
488
489 studyCurrent = salome.myStudyName
490
491 med_comp = salome.lcc.FindOrLoadComponent("FactoryServer", "MED")
492 myVisu = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU")
493
494 try:
495     if os.access(medFile, os.R_OK) :
496        if not os.access(medFile, os.W_OK) :
497                import random
498                if sys.platform != "win32":
499                  tmpDir = "/tmp/"
500                else:
501                  tmpDir = os.getenv('TEMP') + '\\'
502                medFileNew = tmpDir + str(random.randint(0,1000000)) + "_" + medFileName
503                print " -- Copy " + medFile + " to " + medFileNew
504
505                if sys.platform != "win32":
506                  copyCommand = "cp"
507                else:
508                  copyCommand = "copy /Y"
509                os.system(copyCommand + " " + medFile + " " + medFileNew)
510
511                medFile = medFileNew
512                if sys.platform != "win32":
513                    os.system("chmod 755 " + medFile)
514                    pass
515
516        if os.access(medFile, os.W_OK) :
517            med_comp.readStructFileWithFieldType(medFile,studyCurrent)
518            med_obj = visu_gui.visu.getMedObjectFromStudy()
519            print "med_obj - ", med_obj
520
521            myField1 = visu_gui.visu.getFieldObjectFromStudy(2,1)
522            aMeshName = "maa1"
523            anEntity = VISU.NODE
524            aTimeStampId = -1
525                    
526            myResult1 = myVisu.ImportMedField(myField1)
527            aMesh1 = myVisu.MeshOnEntity(myResult1, aMeshName, anEntity);
528            
529            aScalarMap1= myVisu.ScalarMapOnField(myResult1, aMeshName, anEntity, myField1.getName(), aTimeStampId)
530            
531            myResult2 = myVisu.ImportFile(medFile);
532            aMesh2 = myVisu.MeshOnEntity(myResult2, aMeshName, anEntity);
533            
534            aTimeStampId = 3
535            aScalarMap2= myVisu.ScalarMapOnField(myResult2, aMeshName, anEntity, myField1.getName(), aTimeStampId)
536                    
537            sg.updateObjBrowser(0)
538        else :  print "We have no permission to rewrite medFile, so readStructFileWithFieldType can't open this file";
539     else :  print  "We have no permission to read medFile, it will not be opened"; 
540
541 except:
542     if sys.exc_type == SALOME.SALOME_Exception :
543         print "There is no permission to read " + medFile
544     else :
545         print sys.exc_type 
546         print sys.exc_value
547         print sys.exc_traceback
548
549 sg.updateObjBrowser(1);