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