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