Salome HOME
0022107: EDF 2502 SMESH: Publish the result of show bad mesh in a group
[modules/smesh.git] / src / SMESH_SWIG / smeshBuilder.py
1 # Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 #  File   : smeshBuilder.py
20 #  Author : Francis KLOSS, OCC
21 #  Module : SMESH
22
23 ## @package smeshBuilder
24 #  Python API for SALOME %Mesh module
25
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating  Creating meshes
28 ## @{
29 ##   @defgroup l2_impexp     Importing and exporting meshes
30 ##   @defgroup l2_construct  Constructing meshes
31 ##   @defgroup l2_algorithms Defining Algorithms
32 ##   @{
33 ##     @defgroup l3_algos_basic   Basic meshing algorithms
34 ##     @defgroup l3_algos_proj    Projection Algorithms
35 ##     @defgroup l3_algos_radialp Radial Prism
36 ##     @defgroup l3_algos_segmarv Segments around Vertex
37 ##     @defgroup l3_algos_3dextr  3D extrusion meshing algorithm
38
39 ##   @}
40 ##   @defgroup l2_hypotheses Defining hypotheses
41 ##   @{
42 ##     @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ##     @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ##     @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ##     @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ##     @defgroup l3_hypos_additi Additional Hypotheses
47
48 ##   @}
49 ##   @defgroup l2_submeshes Constructing submeshes
50 ##   @defgroup l2_compounds Building Compounds
51 ##   @defgroup l2_editing   Editing Meshes
52
53 ## @}
54 ## @defgroup l1_meshinfo  Mesh Information
55 ## @defgroup l1_controls  Quality controls and Filtering
56 ## @defgroup l1_grouping  Grouping elements
57 ## @{
58 ##   @defgroup l2_grps_create Creating groups
59 ##   @defgroup l2_grps_edit   Editing groups
60 ##   @defgroup l2_grps_operon Using operations on groups
61 ##   @defgroup l2_grps_delete Deleting Groups
62
63 ## @}
64 ## @defgroup l1_modifying Modifying meshes
65 ## @{
66 ##   @defgroup l2_modif_add      Adding nodes and elements
67 ##   @defgroup l2_modif_del      Removing nodes and elements
68 ##   @defgroup l2_modif_edit     Modifying nodes and elements
69 ##   @defgroup l2_modif_renumber Renumbering nodes and elements
70 ##   @defgroup l2_modif_trsf     Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ##   @defgroup l2_modif_movenode Moving nodes
72 ##   @defgroup l2_modif_throughp Mesh through point
73 ##   @defgroup l2_modif_invdiag  Diagonal inversion of elements
74 ##   @defgroup l2_modif_unitetri Uniting triangles
75 ##   @defgroup l2_modif_changori Changing orientation of elements
76 ##   @defgroup l2_modif_cutquadr Cutting quadrangles
77 ##   @defgroup l2_modif_smooth   Smoothing
78 ##   @defgroup l2_modif_extrurev Extrusion and Revolution
79 ##   @defgroup l2_modif_patterns Pattern mapping
80 ##   @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
81
82 ## @}
83 ## @defgroup l1_measurements Measurements
84
85 import salome
86 from salome.geom import geomBuilder
87
88 import SMESH # This is necessary for back compatibility
89 from   SMESH import *
90 from   salome.smesh.smesh_algorithm import Mesh_Algorithm
91
92 import SALOME
93 import SALOMEDS
94 import os
95
96 ## @addtogroup l1_auxiliary
97 ## @{
98
99 ## Converts an angle from degrees to radians
100 def DegreesToRadians(AngleInDegrees):
101     from math import pi
102     return AngleInDegrees * pi / 180.0
103
104 import salome_notebook
105 notebook = salome_notebook.notebook
106 # Salome notebook variable separator
107 var_separator = ":"
108
109 ## Return list of variable values from salome notebook.
110 #  The last argument, if is callable, is used to modify values got from notebook
111 def ParseParameters(*args):
112     Result = []
113     Parameters = ""
114     hasVariables = False
115     varModifFun=None
116     if args and callable( args[-1] ):
117         args, varModifFun = args[:-1], args[-1]
118     for parameter in args:
119
120         Parameters += str(parameter) + var_separator
121
122         if isinstance(parameter,str):
123             # check if there is an inexistent variable name
124             if not notebook.isVariable(parameter):
125                 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
126             parameter = notebook.get(parameter)
127             hasVariables = True
128             if varModifFun:
129                 parameter = varModifFun(parameter)
130                 pass
131             pass
132         Result.append(parameter)
133
134         pass
135     Parameters = Parameters[:-1]
136     Result.append( Parameters )
137     Result.append( hasVariables )
138     return Result
139
140 # Parse parameters converting variables to radians
141 def ParseAngles(*args):
142     return ParseParameters( *( args + (DegreesToRadians, )))
143
144 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
145 # Parameters are stored in PointStruct.parameters attribute
146 def __initPointStruct(point,*args):
147     point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
148     pass
149 SMESH.PointStruct.__init__ = __initPointStruct
150
151 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
152 # Parameters are stored in AxisStruct.parameters attribute
153 def __initAxisStruct(ax,*args):
154     ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
155     pass
156 SMESH.AxisStruct.__init__ = __initAxisStruct
157
158 smeshPrecisionConfusion = 1.e-07
159 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
160     if abs(val1 - val2) < tol:
161         return True
162     return False
163
164 NO_NAME = "NoName"
165
166 ## Gets object name
167 def GetName(obj):
168     if obj:
169         # object not null
170         if isinstance(obj, SALOMEDS._objref_SObject):
171             # study object
172             return obj.GetName()
173         try:
174             ior  = salome.orb.object_to_string(obj)
175         except:
176             ior = None
177         if ior:
178             # CORBA object
179             studies = salome.myStudyManager.GetOpenStudies()
180             for sname in studies:
181                 s = salome.myStudyManager.GetStudyByName(sname)
182                 if not s: continue
183                 sobj = s.FindObjectIOR(ior)
184                 if not sobj: continue
185                 return sobj.GetName()
186             if hasattr(obj, "GetName"):
187                 # unknown CORBA object, having GetName() method
188                 return obj.GetName()
189             else:
190                 # unknown CORBA object, no GetName() method
191                 return NO_NAME
192             pass
193         if hasattr(obj, "GetName"):
194             # unknown non-CORBA object, having GetName() method
195             return obj.GetName()
196         pass
197     raise RuntimeError, "Null or invalid object"
198
199 ## Prints error message if a hypothesis was not assigned.
200 def TreatHypoStatus(status, hypName, geomName, isAlgo):
201     if isAlgo:
202         hypType = "algorithm"
203     else:
204         hypType = "hypothesis"
205         pass
206     if status == HYP_UNKNOWN_FATAL :
207         reason = "for unknown reason"
208     elif status == HYP_INCOMPATIBLE :
209         reason = "this hypothesis mismatches the algorithm"
210     elif status == HYP_NOTCONFORM :
211         reason = "a non-conform mesh would be built"
212     elif status == HYP_ALREADY_EXIST :
213         if isAlgo: return # it does not influence anything
214         reason = hypType + " of the same dimension is already assigned to this shape"
215     elif status == HYP_BAD_DIM :
216         reason = hypType + " mismatches the shape"
217     elif status == HYP_CONCURENT :
218         reason = "there are concurrent hypotheses on sub-shapes"
219     elif status == HYP_BAD_SUBSHAPE :
220         reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
221     elif status == HYP_BAD_GEOMETRY:
222         reason = "geometry mismatches the expectation of the algorithm"
223     elif status == HYP_HIDDEN_ALGO:
224         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
225     elif status == HYP_HIDING_ALGO:
226         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
227     elif status == HYP_NEED_SHAPE:
228         reason = "Algorithm can't work without shape"
229     else:
230         return
231     hypName = '"' + hypName + '"'
232     geomName= '"' + geomName+ '"'
233     if status < HYP_UNKNOWN_FATAL and not geomName =='""':
234         print hypName, "was assigned to",    geomName,"but", reason
235     elif not geomName == '""':
236         print hypName, "was not assigned to",geomName,":", reason
237     else:
238         print hypName, "was not assigned:", reason
239         pass
240
241 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
242 def AssureGeomPublished(mesh, geom, name=''):
243     if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
244         return
245     if not geom.GetStudyEntry() and \
246            mesh.smeshpyD.GetCurrentStudy():
247         ## set the study
248         studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
249         if studyID != mesh.geompyD.myStudyId:
250             mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
251         ## get a name
252         if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
253             # for all groups SubShapeName() returns "Compound_-1"
254             name = mesh.geompyD.SubShapeName(geom, mesh.geom)
255         if not name:
256             name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
257         ## publish
258         mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
259     return
260
261 ## Return the first vertex of a geometrical edge by ignoring orientation
262 def FirstVertexOnCurve(mesh, edge):
263     vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
264     if not vv:
265         raise TypeError, "Given object has no vertices"
266     if len( vv ) == 1: return vv[0]
267     v0   = mesh.geompyD.MakeVertexOnCurve(edge,0.)
268     xyz  = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
269     xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
270     xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
271     dist1, dist2 = 0,0
272     for i in range(3):
273         dist1 += abs( xyz[i] - xyz1[i] )
274         dist2 += abs( xyz[i] - xyz2[i] )
275     if dist1 < dist2:
276         return vv[0]
277     else:
278         return vv[1]
279
280 # end of l1_auxiliary
281 ## @}
282
283
284 # Warning: smeshInst is a singleton
285 smeshInst = None
286 engine = None
287 doLcc = False
288 created = False
289
290 ## This class allows to create, load or manipulate meshes
291 #  It has a set of methods to create load or copy meshes, to combine several meshes.
292 #  It also has methods to get infos on meshes.
293 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
294
295     # MirrorType enumeration
296     POINT = SMESH_MeshEditor.POINT
297     AXIS =  SMESH_MeshEditor.AXIS
298     PLANE = SMESH_MeshEditor.PLANE
299
300     # Smooth_Method enumeration
301     LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
302     CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
303
304     PrecisionConfusion = smeshPrecisionConfusion
305
306     # TopAbs_State enumeration
307     [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
308
309     # Methods of splitting a hexahedron into tetrahedra
310     Hex_5Tet, Hex_6Tet, Hex_24Tet = 1, 2, 3
311
312     def __new__(cls):
313         global engine
314         global smeshInst
315         global doLcc
316         #print "==== __new__", engine, smeshInst, doLcc
317
318         if smeshInst is None:
319             # smesh engine is either retrieved from engine, or created
320             smeshInst = engine
321             # Following test avoids a recursive loop
322             if doLcc:
323                 if smeshInst is not None:
324                     # smesh engine not created: existing engine found
325                     doLcc = False
326                 if doLcc:
327                     doLcc = False
328                     # FindOrLoadComponent called:
329                     # 1. CORBA resolution of server
330                     # 2. the __new__ method is called again
331                     #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
332                     smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
333             else:
334                 # FindOrLoadComponent not called
335                 if smeshInst is None:
336                     # smeshBuilder instance is created from lcc.FindOrLoadComponent
337                     #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
338                     smeshInst = super(smeshBuilder,cls).__new__(cls)
339                 else:
340                     # smesh engine not created: existing engine found
341                     #print "==== existing ", engine, smeshInst, doLcc
342                     pass
343             #print "====1 ", smeshInst
344             return smeshInst
345
346         #print "====2 ", smeshInst
347         return smeshInst
348
349     def __init__(self):
350         global created
351         #print "--------------- smeshbuilder __init__ ---", created
352         if not created:
353           created = True
354           SMESH._objref_SMESH_Gen.__init__(self)
355
356     ## Dump component to the Python script
357     #  This method overrides IDL function to allow default values for the parameters.
358     def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
359         return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
360
361     ## Set mode of DumpPython(), \a historical or \a snapshot.
362     # In the \a historical mode, the Python Dump script includes all commands
363     # performed by SMESH engine. In the \a snapshot mode, commands
364     # relating to objects removed from the Study are excluded from the script
365     # as well as commands not influencing the current state of meshes
366     def SetDumpPythonHistorical(self, isHistorical):
367         if isHistorical: val = "true"
368         else:            val = "false"
369         SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
370
371     ## Sets the current study and Geometry component
372     #  @ingroup l1_auxiliary
373     def init_smesh(self,theStudy,geompyD = None):
374         #print "init_smesh"
375         self.SetCurrentStudy(theStudy,geompyD)
376
377     ## Creates an empty Mesh. This mesh can have an underlying geometry.
378     #  @param obj the Geometrical object on which the mesh is built. If not defined,
379     #             the mesh will have no underlying geometry.
380     #  @param name the name for the new mesh.
381     #  @return an instance of Mesh class.
382     #  @ingroup l2_construct
383     def Mesh(self, obj=0, name=0):
384         if isinstance(obj,str):
385             obj,name = name,obj
386         return Mesh(self,self.geompyD,obj,name)
387
388     ## Returns a long value from enumeration
389     #  @ingroup l1_controls
390     def EnumToLong(self,theItem):
391         return theItem._v
392
393     ## Returns a string representation of the color.
394     #  To be used with filters.
395     #  @param c color value (SALOMEDS.Color)
396     #  @ingroup l1_controls
397     def ColorToString(self,c):
398         val = ""
399         if isinstance(c, SALOMEDS.Color):
400             val = "%s;%s;%s" % (c.R, c.G, c.B)
401         elif isinstance(c, str):
402             val = c
403         else:
404             raise ValueError, "Color value should be of string or SALOMEDS.Color type"
405         return val
406
407     ## Gets PointStruct from vertex
408     #  @param theVertex a GEOM object(vertex)
409     #  @return SMESH.PointStruct
410     #  @ingroup l1_auxiliary
411     def GetPointStruct(self,theVertex):
412         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
413         return PointStruct(x,y,z)
414
415     ## Gets DirStruct from vector
416     #  @param theVector a GEOM object(vector)
417     #  @return SMESH.DirStruct
418     #  @ingroup l1_auxiliary
419     def GetDirStruct(self,theVector):
420         vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
421         if(len(vertices) != 2):
422             print "Error: vector object is incorrect."
423             return None
424         p1 = self.geompyD.PointCoordinates(vertices[0])
425         p2 = self.geompyD.PointCoordinates(vertices[1])
426         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
427         dirst = DirStruct(pnt)
428         return dirst
429
430     ## Makes DirStruct from a triplet
431     #  @param x,y,z vector components
432     #  @return SMESH.DirStruct
433     #  @ingroup l1_auxiliary
434     def MakeDirStruct(self,x,y,z):
435         pnt = PointStruct(x,y,z)
436         return DirStruct(pnt)
437
438     ## Get AxisStruct from object
439     #  @param theObj a GEOM object (line or plane)
440     #  @return SMESH.AxisStruct
441     #  @ingroup l1_auxiliary
442     def GetAxisStruct(self,theObj):
443         edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
444         if len(edges) > 1:
445             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
446             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
447             vertex1 = self.geompyD.PointCoordinates(vertex1)
448             vertex2 = self.geompyD.PointCoordinates(vertex2)
449             vertex3 = self.geompyD.PointCoordinates(vertex3)
450             vertex4 = self.geompyD.PointCoordinates(vertex4)
451             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
452             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
453             normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
454             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
455             return axis
456         elif len(edges) == 1:
457             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
458             p1 = self.geompyD.PointCoordinates( vertex1 )
459             p2 = self.geompyD.PointCoordinates( vertex2 )
460             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
461             return axis
462         return None
463
464     # From SMESH_Gen interface:
465     # ------------------------
466
467     ## Sets the given name to the object
468     #  @param obj the object to rename
469     #  @param name a new object name
470     #  @ingroup l1_auxiliary
471     def SetName(self, obj, name):
472         if isinstance( obj, Mesh ):
473             obj = obj.GetMesh()
474         elif isinstance( obj, Mesh_Algorithm ):
475             obj = obj.GetAlgorithm()
476         ior  = salome.orb.object_to_string(obj)
477         SMESH._objref_SMESH_Gen.SetName(self, ior, name)
478
479     ## Sets the current mode
480     #  @ingroup l1_auxiliary
481     def SetEmbeddedMode( self,theMode ):
482         #self.SetEmbeddedMode(theMode)
483         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
484
485     ## Gets the current mode
486     #  @ingroup l1_auxiliary
487     def IsEmbeddedMode(self):
488         #return self.IsEmbeddedMode()
489         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
490
491     ## Sets the current study
492     #  @ingroup l1_auxiliary
493     def SetCurrentStudy( self, theStudy, geompyD = None ):
494         #self.SetCurrentStudy(theStudy)
495         if not geompyD:
496             from salome.geom import geomBuilder
497             geompyD = geomBuilder.geom
498             pass
499         self.geompyD=geompyD
500         self.SetGeomEngine(geompyD)
501         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
502         global notebook
503         if theStudy:
504             notebook = salome_notebook.NoteBook( theStudy )
505         else:
506             notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
507
508     ## Gets the current study
509     #  @ingroup l1_auxiliary
510     def GetCurrentStudy(self):
511         #return self.GetCurrentStudy()
512         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
513
514     ## Creates a Mesh object importing data from the given UNV file
515     #  @return an instance of Mesh class
516     #  @ingroup l2_impexp
517     def CreateMeshesFromUNV( self,theFileName ):
518         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
519         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
520         return aMesh
521
522     ## Creates a Mesh object(s) importing data from the given MED file
523     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
524     #  @ingroup l2_impexp
525     def CreateMeshesFromMED( self,theFileName ):
526         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
527         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
528         return aMeshes, aStatus
529
530     ## Creates a Mesh object(s) importing data from the given SAUV file
531     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
532     #  @ingroup l2_impexp
533     def CreateMeshesFromSAUV( self,theFileName ):
534         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
535         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
536         return aMeshes, aStatus
537
538     ## Creates a Mesh object importing data from the given STL file
539     #  @return an instance of Mesh class
540     #  @ingroup l2_impexp
541     def CreateMeshesFromSTL( self, theFileName ):
542         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
543         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
544         return aMesh
545
546     ## Creates Mesh objects importing data from the given CGNS file
547     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
548     #  @ingroup l2_impexp
549     def CreateMeshesFromCGNS( self, theFileName ):
550         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
551         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
552         return aMeshes, aStatus
553
554     ## Creates a Mesh object importing data from the given GMF file
555     #  @return [ an instance of Mesh class, SMESH.ComputeError ]
556     #  @ingroup l2_impexp
557     def CreateMeshesFromGMF( self, theFileName ):
558         aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
559                                                                         theFileName,
560                                                                         True)
561         if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
562         return Mesh(self, self.geompyD, aSmeshMesh), error
563
564     ## Concatenate the given meshes into one mesh.
565     #  @return an instance of Mesh class
566     #  @param meshes the meshes to combine into one mesh
567     #  @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
568     #  @param mergeNodesAndElements if true, equal nodes and elements aremerged
569     #  @param mergeTolerance tolerance for merging nodes
570     #  @param allGroups forces creation of groups of all elements
571     #  @param name name of a new mesh
572     def Concatenate( self, meshes, uniteIdenticalGroups,
573                      mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
574                      name = ""):
575         if not meshes: return None
576         for i,m in enumerate(meshes):
577             if isinstance(m, Mesh):
578                 meshes[i] = m.GetMesh()
579         mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
580         meshes[0].SetParameters(Parameters)
581         if allGroups:
582             aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
583                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
584         else:
585             aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
586                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
587         aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
588         return aMesh
589
590     ## Create a mesh by copying a part of another mesh.
591     #  @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
592     #                  to copy nodes or elements not contained in any mesh object,
593     #                  pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
594     #  @param meshName a name of the new mesh
595     #  @param toCopyGroups to create in the new mesh groups the copied elements belongs to
596     #  @param toKeepIDs to preserve IDs of the copied elements or not
597     #  @return an instance of Mesh class
598     def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
599         if (isinstance( meshPart, Mesh )):
600             meshPart = meshPart.GetMesh()
601         mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
602         return Mesh(self, self.geompyD, mesh)
603
604     ## From SMESH_Gen interface
605     #  @return the list of integer values
606     #  @ingroup l1_auxiliary
607     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
608         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
609
610     ## From SMESH_Gen interface. Creates a pattern
611     #  @return an instance of SMESH_Pattern
612     #
613     #  <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
614     #  @ingroup l2_modif_patterns
615     def GetPattern(self):
616         return SMESH._objref_SMESH_Gen.GetPattern(self)
617
618     ## Sets number of segments per diagonal of boundary box of geometry by which
619     #  default segment length of appropriate 1D hypotheses is defined.
620     #  Default value is 10
621     #  @ingroup l1_auxiliary
622     def SetBoundaryBoxSegmentation(self, nbSegments):
623         SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
624
625     # Filtering. Auxiliary functions:
626     # ------------------------------
627
628     ## Creates an empty criterion
629     #  @return SMESH.Filter.Criterion
630     #  @ingroup l1_controls
631     def GetEmptyCriterion(self):
632         Type = self.EnumToLong(FT_Undefined)
633         Compare = self.EnumToLong(FT_Undefined)
634         Threshold = 0
635         ThresholdStr = ""
636         ThresholdID = ""
637         UnaryOp = self.EnumToLong(FT_Undefined)
638         BinaryOp = self.EnumToLong(FT_Undefined)
639         Tolerance = 1e-07
640         TypeOfElement = ALL
641         Precision = -1 ##@1e-07
642         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
643                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
644
645     ## Creates a criterion by the given parameters
646     #  \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
647     #  @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
648     #  @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
649     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
650     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
651     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
652     #  @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
653     #                  FT_Undefined (must be for the last criterion of all criteria)
654     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
655     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
656     #  @return SMESH.Filter.Criterion
657     #
658     #  <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
659     #  @ingroup l1_controls
660     def GetCriterion(self,elementType,
661                      CritType,
662                      Compare = FT_EqualTo,
663                      Threshold="",
664                      UnaryOp=FT_Undefined,
665                      BinaryOp=FT_Undefined,
666                      Tolerance=1e-07):
667         if not CritType in SMESH.FunctorType._items:
668             raise TypeError, "CritType should be of SMESH.FunctorType"
669         aCriterion               = self.GetEmptyCriterion()
670         aCriterion.TypeOfElement = elementType
671         aCriterion.Type          = self.EnumToLong(CritType)
672         aCriterion.Tolerance     = Tolerance
673
674         aThreshold = Threshold
675
676         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
677             aCriterion.Compare = self.EnumToLong(Compare)
678         elif Compare == "=" or Compare == "==":
679             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
680         elif Compare == "<":
681             aCriterion.Compare = self.EnumToLong(FT_LessThan)
682         elif Compare == ">":
683             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
684         elif Compare != FT_Undefined:
685             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
686             aThreshold = Compare
687
688         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
689                         FT_BelongToCylinder, FT_LyingOnGeom]:
690             # Checks that Threshold is GEOM object
691             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
692                 aCriterion.ThresholdStr = GetName(aThreshold)
693                 aCriterion.ThresholdID  = aThreshold.GetStudyEntry()
694                 if not aCriterion.ThresholdID:
695                     name = aCriterion.ThresholdStr
696                     if not name:
697                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
698                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
699                     #raise RuntimeError, "Threshold shape must be published"
700             else:
701                 print "Error: The Threshold should be a shape."
702                 return None
703             if isinstance(UnaryOp,float):
704                 aCriterion.Tolerance = UnaryOp
705                 UnaryOp = FT_Undefined
706                 pass
707         elif CritType == FT_RangeOfIds:
708             # Checks that Threshold is string
709             if isinstance(aThreshold, str):
710                 aCriterion.ThresholdStr = aThreshold
711             else:
712                 print "Error: The Threshold should be a string."
713                 return None
714         elif CritType == FT_CoplanarFaces:
715             # Checks the Threshold
716             if isinstance(aThreshold, int):
717                 aCriterion.ThresholdID = str(aThreshold)
718             elif isinstance(aThreshold, str):
719                 ID = int(aThreshold)
720                 if ID < 1:
721                     raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
722                 aCriterion.ThresholdID = aThreshold
723             else:
724                 raise ValueError,\
725                       "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
726         elif CritType == FT_ConnectedElements:
727             # Checks the Threshold
728             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
729                 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
730                 if not aCriterion.ThresholdID:
731                     name = aThreshold.GetName()
732                     if not name:
733                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
734                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
735             elif isinstance(aThreshold, int): # node id
736                 aCriterion.Threshold = aThreshold
737             elif isinstance(aThreshold, list): # 3 point coordinates
738                 if len( aThreshold ) < 3:
739                     raise ValueError, "too few point coordinates, must be 3"
740                 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
741             elif isinstance(aThreshold, str):
742                 if aThreshold.isdigit():
743                     aCriterion.Threshold = aThreshold # node id
744                 else:
745                     aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
746             else:
747                 raise ValueError,\
748                       "The Threshold should either a VERTEX, or a node ID, "\
749                       "or a list of point coordinates and not '%s'"%aThreshold
750         elif CritType == FT_ElemGeomType:
751             # Checks the Threshold
752             try:
753                 aCriterion.Threshold = self.EnumToLong(aThreshold)
754                 assert( aThreshold in SMESH.GeometryType._items )
755             except:
756                 if isinstance(aThreshold, int):
757                     aCriterion.Threshold = aThreshold
758                 else:
759                     print "Error: The Threshold should be an integer or SMESH.GeometryType."
760                     return None
761                 pass
762             pass
763         elif CritType == FT_EntityType:
764             # Checks the Threshold
765             try:
766                 aCriterion.Threshold = self.EnumToLong(aThreshold)
767                 assert( aThreshold in SMESH.EntityType._items )
768             except:
769                 if isinstance(aThreshold, int):
770                     aCriterion.Threshold = aThreshold
771                 else:
772                     print "Error: The Threshold should be an integer or SMESH.EntityType."
773                     return None
774                 pass
775             pass
776         
777         elif CritType == FT_GroupColor:
778             # Checks the Threshold
779             try:
780                 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
781             except:
782                 print "Error: The threshold value should be of SALOMEDS.Color type"
783                 return None
784             pass
785         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
786                           FT_LinearOrQuadratic, FT_BadOrientedVolume,
787                           FT_BareBorderFace, FT_BareBorderVolume,
788                           FT_OverConstrainedFace, FT_OverConstrainedVolume,
789                           FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
790             # At this point the Threshold is unnecessary
791             if aThreshold ==  FT_LogicalNOT:
792                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
793             elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
794                 aCriterion.BinaryOp = aThreshold
795         else:
796             # Check Threshold
797             try:
798                 aThreshold = float(aThreshold)
799                 aCriterion.Threshold = aThreshold
800             except:
801                 print "Error: The Threshold should be a number."
802                 return None
803
804         if Threshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
805             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
806
807         if Threshold in [FT_LogicalAND, FT_LogicalOR]:
808             aCriterion.BinaryOp = self.EnumToLong(Threshold)
809
810         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
811             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
812
813         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
814             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
815
816         return aCriterion
817
818     ## Creates a filter with the given parameters
819     #  @param elementType the type of elements in the group
820     #  @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
821     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
822     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
823     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
824     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
825     #         FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
826     #  @param mesh the mesh to initialize the filter with
827     #  @return SMESH_Filter
828     #
829     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
830     #  @ingroup l1_controls
831     def GetFilter(self,elementType,
832                   CritType=FT_Undefined,
833                   Compare=FT_EqualTo,
834                   Threshold="",
835                   UnaryOp=FT_Undefined,
836                   Tolerance=1e-07,
837                   mesh=None):
838         aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
839         aFilterMgr = self.CreateFilterManager()
840         aFilter = aFilterMgr.CreateFilter()
841         aCriteria = []
842         aCriteria.append(aCriterion)
843         aFilter.SetCriteria(aCriteria)
844         if mesh:
845             if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
846             else                       : aFilter.SetMesh( mesh )
847         aFilterMgr.UnRegister()
848         return aFilter
849
850     ## Creates a filter from criteria
851     #  @param criteria a list of criteria
852     #  @return SMESH_Filter
853     #
854     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
855     #  @ingroup l1_controls
856     def GetFilterFromCriteria(self,criteria):
857         aFilterMgr = self.CreateFilterManager()
858         aFilter = aFilterMgr.CreateFilter()
859         aFilter.SetCriteria(criteria)
860         aFilterMgr.UnRegister()
861         return aFilter
862
863     ## Creates a numerical functor by its type
864     #  @param theCriterion FT_...; functor type
865     #  @return SMESH_NumericalFunctor
866     #  @ingroup l1_controls
867     def GetFunctor(self,theCriterion):
868         if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
869             return theCriterion
870         aFilterMgr = self.CreateFilterManager()
871         functor = None
872         if theCriterion == FT_AspectRatio:
873             functor = aFilterMgr.CreateAspectRatio()
874         elif theCriterion == FT_AspectRatio3D:
875             functor = aFilterMgr.CreateAspectRatio3D()
876         elif theCriterion == FT_Warping:
877             functor = aFilterMgr.CreateWarping()
878         elif theCriterion == FT_MinimumAngle:
879             functor = aFilterMgr.CreateMinimumAngle()
880         elif theCriterion == FT_Taper:
881             functor = aFilterMgr.CreateTaper()
882         elif theCriterion == FT_Skew:
883             functor = aFilterMgr.CreateSkew()
884         elif theCriterion == FT_Area:
885             functor = aFilterMgr.CreateArea()
886         elif theCriterion == FT_Volume3D:
887             functor = aFilterMgr.CreateVolume3D()
888         elif theCriterion == FT_MaxElementLength2D:
889             functor = aFilterMgr.CreateMaxElementLength2D()
890         elif theCriterion == FT_MaxElementLength3D:
891             functor = aFilterMgr.CreateMaxElementLength3D()
892         elif theCriterion == FT_MultiConnection:
893             functor = aFilterMgr.CreateMultiConnection()
894         elif theCriterion == FT_MultiConnection2D:
895             functor = aFilterMgr.CreateMultiConnection2D()
896         elif theCriterion == FT_Length:
897             functor = aFilterMgr.CreateLength()
898         elif theCriterion == FT_Length2D:
899             functor = aFilterMgr.CreateLength2D()
900         else:
901             print "Error: given parameter is not numerical functor type."
902         aFilterMgr.UnRegister()
903         return functor
904
905     ## Creates hypothesis
906     #  @param theHType mesh hypothesis type (string)
907     #  @param theLibName mesh plug-in library name
908     #  @return created hypothesis instance
909     def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
910         hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
911
912         if isinstance( hyp, SMESH._objref_SMESH_Algo ):
913             return hyp
914
915         # wrap hypothesis methods
916         #print "HYPOTHESIS", theHType
917         for meth_name in dir( hyp.__class__ ):
918             if not meth_name.startswith("Get") and \
919                not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
920                 method = getattr ( hyp.__class__, meth_name )
921                 if callable(method):
922                     setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
923
924         return hyp
925
926     ## Gets the mesh statistic
927     #  @return dictionary "element type" - "count of elements"
928     #  @ingroup l1_meshinfo
929     def GetMeshInfo(self, obj):
930         if isinstance( obj, Mesh ):
931             obj = obj.GetMesh()
932         d = {}
933         if hasattr(obj, "GetMeshInfo"):
934             values = obj.GetMeshInfo()
935             for i in range(SMESH.Entity_Last._v):
936                 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
937             pass
938         return d
939
940     ## Get minimum distance between two objects
941     #
942     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
943     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
944     #
945     #  @param src1 first source object
946     #  @param src2 second source object
947     #  @param id1 node/element id from the first source
948     #  @param id2 node/element id from the second (or first) source
949     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
950     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
951     #  @return minimum distance value
952     #  @sa GetMinDistance()
953     #  @ingroup l1_measurements
954     def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
955         result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
956         if result is None:
957             result = 0.0
958         else:
959             result = result.value
960         return result
961
962     ## Get measure structure specifying minimum distance data between two objects
963     #
964     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
965     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
966     #
967     #  @param src1 first source object
968     #  @param src2 second source object
969     #  @param id1 node/element id from the first source
970     #  @param id2 node/element id from the second (or first) source
971     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
972     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
973     #  @return Measure structure or None if input data is invalid
974     #  @sa MinDistance()
975     #  @ingroup l1_measurements
976     def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
977         if isinstance(src1, Mesh): src1 = src1.mesh
978         if isinstance(src2, Mesh): src2 = src2.mesh
979         if src2 is None and id2 != 0: src2 = src1
980         if not hasattr(src1, "_narrow"): return None
981         src1 = src1._narrow(SMESH.SMESH_IDSource)
982         if not src1: return None
983         if id1 != 0:
984             m = src1.GetMesh()
985             e = m.GetMeshEditor()
986             if isElem1:
987                 src1 = e.MakeIDSource([id1], SMESH.FACE)
988             else:
989                 src1 = e.MakeIDSource([id1], SMESH.NODE)
990             pass
991         if hasattr(src2, "_narrow"):
992             src2 = src2._narrow(SMESH.SMESH_IDSource)
993             if src2 and id2 != 0:
994                 m = src2.GetMesh()
995                 e = m.GetMeshEditor()
996                 if isElem2:
997                     src2 = e.MakeIDSource([id2], SMESH.FACE)
998                 else:
999                     src2 = e.MakeIDSource([id2], SMESH.NODE)
1000                 pass
1001             pass
1002         aMeasurements = self.CreateMeasurements()
1003         result = aMeasurements.MinDistance(src1, src2)
1004         aMeasurements.UnRegister()
1005         return result
1006
1007     ## Get bounding box of the specified object(s)
1008     #  @param objects single source object or list of source objects
1009     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1010     #  @sa GetBoundingBox()
1011     #  @ingroup l1_measurements
1012     def BoundingBox(self, objects):
1013         result = self.GetBoundingBox(objects)
1014         if result is None:
1015             result = (0.0,)*6
1016         else:
1017             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1018         return result
1019
1020     ## Get measure structure specifying bounding box data of the specified object(s)
1021     #  @param objects single source object or list of source objects
1022     #  @return Measure structure
1023     #  @sa BoundingBox()
1024     #  @ingroup l1_measurements
1025     def GetBoundingBox(self, objects):
1026         if isinstance(objects, tuple):
1027             objects = list(objects)
1028         if not isinstance(objects, list):
1029             objects = [objects]
1030         srclist = []
1031         for o in objects:
1032             if isinstance(o, Mesh):
1033                 srclist.append(o.mesh)
1034             elif hasattr(o, "_narrow"):
1035                 src = o._narrow(SMESH.SMESH_IDSource)
1036                 if src: srclist.append(src)
1037                 pass
1038             pass
1039         aMeasurements = self.CreateMeasurements()
1040         result = aMeasurements.BoundingBox(srclist)
1041         aMeasurements.UnRegister()
1042         return result
1043
1044 import omniORB
1045 #Registering the new proxy for SMESH_Gen
1046 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1047
1048 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1049 #  interface to create or load meshes.
1050 #
1051 #  Typical use is:
1052 #  \code
1053 #    import salome
1054 #    salome.salome_init()
1055 #    from salome.smesh import smeshBuilder
1056 #    smesh = smeshBuilder.New(theStudy)
1057 #  \endcode
1058 #  @param  study     SALOME study, generally obtained by salome.myStudy.
1059 #  @param  instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1060 #  @return smeshBuilder instance
1061
1062 def New( study, instance=None):
1063     """
1064     Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1065     interface to create or load meshes.
1066
1067     Typical use is:
1068         import salome
1069         salome.salome_init()
1070         from salome.smesh import smeshBuilder
1071         smesh = smeshBuilder.New(theStudy)
1072
1073     Parameters:
1074         study     SALOME study, generally obtained by salome.myStudy.
1075         instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1076     Returns:
1077         smeshBuilder instance
1078     """
1079     global engine
1080     global smeshInst
1081     global doLcc
1082     engine = instance
1083     if engine is None:
1084       doLcc = True
1085     smeshInst = smeshBuilder()
1086     assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1087     smeshInst.init_smesh(study)
1088     return smeshInst
1089
1090
1091 # Public class: Mesh
1092 # ==================
1093
1094 ## This class allows defining and managing a mesh.
1095 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1096 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1097 #  new nodes and elements and by changing the existing entities), to get information
1098 #  about a mesh and to export a mesh into different formats.
1099 class Mesh:
1100
1101     geom = 0
1102     mesh = 0
1103     editor = 0
1104
1105     ## Constructor
1106     #
1107     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1108     #  sets the GUI name of this mesh to \a name.
1109     #  @param smeshpyD an instance of smeshBuilder class
1110     #  @param geompyD an instance of geomBuilder class
1111     #  @param obj Shape to be meshed or SMESH_Mesh object
1112     #  @param name Study name of the mesh
1113     #  @ingroup l2_construct
1114     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1115         self.smeshpyD=smeshpyD
1116         self.geompyD=geompyD
1117         if obj is None:
1118             obj = 0
1119         objHasName = False
1120         if obj != 0:
1121             if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1122                 self.geom = obj
1123                 objHasName = True
1124                 # publish geom of mesh (issue 0021122)
1125                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1126                     objHasName = False
1127                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1128                     if studyID != geompyD.myStudyId:
1129                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
1130                         pass
1131                     if name:
1132                         geo_name = name + " shape"
1133                     else:
1134                         geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1135                     geompyD.addToStudy( self.geom, geo_name )
1136                 self.mesh = self.smeshpyD.CreateMesh(self.geom)
1137
1138             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1139                 self.SetMesh(obj)
1140         else:
1141             self.mesh = self.smeshpyD.CreateEmptyMesh()
1142         if name:
1143             self.smeshpyD.SetName(self.mesh, name)
1144         elif objHasName:
1145             self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1146
1147         if not self.geom:
1148             self.geom = self.mesh.GetShapeToMesh()
1149
1150         self.editor   = self.mesh.GetMeshEditor()
1151         self.functors = [None] * SMESH.FT_Undefined._v
1152
1153         # set self to algoCreator's
1154         for attrName in dir(self):
1155             attr = getattr( self, attrName )
1156             if isinstance( attr, algoCreator ):
1157                 #print "algoCreator ", attrName
1158                 setattr( self, attrName, attr.copy( self ))
1159
1160     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1161     #  @param theMesh a SMESH_Mesh object
1162     #  @ingroup l2_construct
1163     def SetMesh(self, theMesh):
1164         if self.mesh: self.mesh.UnRegister()
1165         self.mesh = theMesh
1166         if self.mesh:
1167             self.mesh.Register()
1168             self.geom = self.mesh.GetShapeToMesh()
1169
1170     ## Returns the mesh, that is an instance of SMESH_Mesh interface
1171     #  @return a SMESH_Mesh object
1172     #  @ingroup l2_construct
1173     def GetMesh(self):
1174         return self.mesh
1175
1176     ## Gets the name of the mesh
1177     #  @return the name of the mesh as a string
1178     #  @ingroup l2_construct
1179     def GetName(self):
1180         name = GetName(self.GetMesh())
1181         return name
1182
1183     ## Sets a name to the mesh
1184     #  @param name a new name of the mesh
1185     #  @ingroup l2_construct
1186     def SetName(self, name):
1187         self.smeshpyD.SetName(self.GetMesh(), name)
1188
1189     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1190     #  The subMesh object gives access to the IDs of nodes and elements.
1191     #  @param geom a geometrical object (shape)
1192     #  @param name a name for the submesh
1193     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1194     #  @ingroup l2_submeshes
1195     def GetSubMesh(self, geom, name):
1196         AssureGeomPublished( self, geom, name )
1197         submesh = self.mesh.GetSubMesh( geom, name )
1198         return submesh
1199
1200     ## Returns the shape associated to the mesh
1201     #  @return a GEOM_Object
1202     #  @ingroup l2_construct
1203     def GetShape(self):
1204         return self.geom
1205
1206     ## Associates the given shape to the mesh (entails the recreation of the mesh)
1207     #  @param geom the shape to be meshed (GEOM_Object)
1208     #  @ingroup l2_construct
1209     def SetShape(self, geom):
1210         self.mesh = self.smeshpyD.CreateMesh(geom)
1211
1212     ## Loads mesh from the study after opening the study
1213     def Load(self):
1214         self.mesh.Load()
1215
1216     ## Returns true if the hypotheses are defined well
1217     #  @param theSubObject a sub-shape of a mesh shape
1218     #  @return True or False
1219     #  @ingroup l2_construct
1220     def IsReadyToCompute(self, theSubObject):
1221         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1222
1223     ## Returns errors of hypotheses definition.
1224     #  The list of errors is empty if everything is OK.
1225     #  @param theSubObject a sub-shape of a mesh shape
1226     #  @return a list of errors
1227     #  @ingroup l2_construct
1228     def GetAlgoState(self, theSubObject):
1229         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1230
1231     ## Returns a geometrical object on which the given element was built.
1232     #  The returned geometrical object, if not nil, is either found in the
1233     #  study or published by this method with the given name
1234     #  @param theElementID the id of the mesh element
1235     #  @param theGeomName the user-defined name of the geometrical object
1236     #  @return GEOM::GEOM_Object instance
1237     #  @ingroup l2_construct
1238     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1239         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1240
1241     ## Returns the mesh dimension depending on the dimension of the underlying shape
1242     #  or, if the mesh is not based on any shape, basing on deimension of elements
1243     #  @return mesh dimension as an integer value [0,3]
1244     #  @ingroup l1_auxiliary
1245     def MeshDimension(self):
1246         if self.mesh.HasShapeToMesh():
1247             shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1248             if len( shells ) > 0 :
1249                 return 3
1250             elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1251                 return 2
1252             elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1253                 return 1
1254             else:
1255                 return 0;
1256         else:
1257             if self.NbVolumes() > 0: return 3
1258             if self.NbFaces()   > 0: return 2
1259             if self.NbEdges()   > 0: return 1
1260         return 0
1261
1262     ## Evaluates size of prospective mesh on a shape
1263     #  @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1264     #  To know predicted number of e.g. edges, inquire it this way
1265     #  Evaluate()[ EnumToLong( Entity_Edge )]
1266     def Evaluate(self, geom=0):
1267         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1268             if self.geom == 0:
1269                 geom = self.mesh.GetShapeToMesh()
1270             else:
1271                 geom = self.geom
1272         return self.smeshpyD.Evaluate(self.mesh, geom)
1273
1274
1275     ## Computes the mesh and returns the status of the computation
1276     #  @param geom geomtrical shape on which mesh data should be computed
1277     #  @param discardModifs if True and the mesh has been edited since
1278     #         a last total re-compute and that may prevent successful partial re-compute,
1279     #         then the mesh is cleaned before Compute()
1280     #  @return True or False
1281     #  @ingroup l2_construct
1282     def Compute(self, geom=0, discardModifs=False):
1283         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1284             if self.geom == 0:
1285                 geom = self.mesh.GetShapeToMesh()
1286             else:
1287                 geom = self.geom
1288         ok = False
1289         try:
1290             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1291                 self.mesh.Clear()
1292             ok = self.smeshpyD.Compute(self.mesh, geom)
1293         except SALOME.SALOME_Exception, ex:
1294             print "Mesh computation failed, exception caught:"
1295             print "    ", ex.details.text
1296         except:
1297             import traceback
1298             print "Mesh computation failed, exception caught:"
1299             traceback.print_exc()
1300         if True:#not ok:
1301             allReasons = ""
1302
1303             # Treat compute errors
1304             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1305             for err in computeErrors:
1306                 shapeText = ""
1307                 if self.mesh.HasShapeToMesh():
1308                     try:
1309                         mainIOR  = salome.orb.object_to_string(geom)
1310                         for sname in salome.myStudyManager.GetOpenStudies():
1311                             s = salome.myStudyManager.GetStudyByName(sname)
1312                             if not s: continue
1313                             mainSO = s.FindObjectIOR(mainIOR)
1314                             if not mainSO: continue
1315                             if err.subShapeID == 1:
1316                                 shapeText = ' on "%s"' % mainSO.GetName()
1317                             subIt = s.NewChildIterator(mainSO)
1318                             while subIt.More():
1319                                 subSO = subIt.Value()
1320                                 subIt.Next()
1321                                 obj = subSO.GetObject()
1322                                 if not obj: continue
1323                                 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1324                                 if not go: continue
1325                                 ids = go.GetSubShapeIndices()
1326                                 if len(ids) == 1 and ids[0] == err.subShapeID:
1327                                     shapeText = ' on "%s"' % subSO.GetName()
1328                                     break
1329                         if not shapeText:
1330                             shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1331                             if shape:
1332                                 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1333                             else:
1334                                 shapeText = " on subshape #%s" % (err.subShapeID)
1335                     except:
1336                         shapeText = " on subshape #%s" % (err.subShapeID)
1337                 errText = ""
1338                 stdErrors = ["OK",                   #COMPERR_OK
1339                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1340                              "std::exception",       #COMPERR_STD_EXCEPTION
1341                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1342                              "..",                   #COMPERR_SLM_EXCEPTION
1343                              "Unknown exception",    #COMPERR_EXCEPTION
1344                              "Memory allocation problem", #COMPERR_MEMORY_PB
1345                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1346                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1347                              "Warning",              #COMPERR_WARNING
1348                              "Computation cancelled",#COMPERR_CANCELED
1349                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1350                 if err.code > 0:
1351                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1352                 else:
1353                     errText = "code %s" % -err.code
1354                 if errText: errText += ". "
1355                 errText += err.comment
1356                 if allReasons != "":allReasons += "\n"
1357                 allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1358                 pass
1359
1360             # Treat hyp errors
1361             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1362             for err in errors:
1363                 if err.isGlobalAlgo:
1364                     glob = "global"
1365                 else:
1366                     glob = "local"
1367                     pass
1368                 dim = err.algoDim
1369                 name = err.algoName
1370                 if len(name) == 0:
1371                     reason = '%s %sD algorithm is missing' % (glob, dim)
1372                 elif err.state == HYP_MISSING:
1373                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1374                               % (glob, dim, name, dim))
1375                 elif err.state == HYP_NOTCONFORM:
1376                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1377                 elif err.state == HYP_BAD_PARAMETER:
1378                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1379                               % ( glob, dim, name ))
1380                 elif err.state == HYP_BAD_GEOMETRY:
1381                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1382                               'geometry' % ( glob, dim, name ))
1383                 elif err.state == HYP_HIDDEN_ALGO:
1384                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1385                               'algorithm of upper dimension generating %sD mesh'
1386                               % ( glob, dim, name, glob, dim ))
1387                 else:
1388                     reason = ("For unknown reason. "
1389                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1390                     pass
1391                 if allReasons != "":allReasons += "\n"
1392                 allReasons += "-  " + reason
1393                 pass
1394             if not ok or allReasons != "":
1395                 msg = '"' + GetName(self.mesh) + '"'
1396                 if ok: msg += " has been computed with warnings"
1397                 else:  msg += " has not been computed"
1398                 if allReasons != "": msg += ":"
1399                 else:                msg += "."
1400                 print msg
1401                 print allReasons
1402             pass
1403         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1404             smeshgui = salome.ImportComponentGUI("SMESH")
1405             smeshgui.Init(self.mesh.GetStudyId())
1406             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1407             salome.sg.updateObjBrowser(1)
1408             pass
1409         return ok
1410
1411     ## Return submesh objects list in meshing order
1412     #  @return list of list of submesh objects
1413     #  @ingroup l2_construct
1414     def GetMeshOrder(self):
1415         return self.mesh.GetMeshOrder()
1416
1417     ## Return submesh objects list in meshing order
1418     #  @return list of list of submesh objects
1419     #  @ingroup l2_construct
1420     def SetMeshOrder(self, submeshes):
1421         return self.mesh.SetMeshOrder(submeshes)
1422
1423     ## Removes all nodes and elements
1424     #  @ingroup l2_construct
1425     def Clear(self):
1426         self.mesh.Clear()
1427         if ( salome.sg.hasDesktop() and 
1428              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1429             smeshgui = salome.ImportComponentGUI("SMESH")
1430             smeshgui.Init(self.mesh.GetStudyId())
1431             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1432             salome.sg.updateObjBrowser(1)
1433
1434     ## Removes all nodes and elements of indicated shape
1435     #  @ingroup l2_construct
1436     def ClearSubMesh(self, geomId):
1437         self.mesh.ClearSubMesh(geomId)
1438         if salome.sg.hasDesktop():
1439             smeshgui = salome.ImportComponentGUI("SMESH")
1440             smeshgui.Init(self.mesh.GetStudyId())
1441             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1442             salome.sg.updateObjBrowser(1)
1443
1444     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1445     #  @param fineness [0.0,1.0] defines mesh fineness
1446     #  @return True or False
1447     #  @ingroup l3_algos_basic
1448     def AutomaticTetrahedralization(self, fineness=0):
1449         dim = self.MeshDimension()
1450         # assign hypotheses
1451         self.RemoveGlobalHypotheses()
1452         self.Segment().AutomaticLength(fineness)
1453         if dim > 1 :
1454             self.Triangle().LengthFromEdges()
1455             pass
1456         if dim > 2 :
1457             from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1458             self.Tetrahedron(NETGEN)
1459             pass
1460         return self.Compute()
1461
1462     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1463     #  @param fineness [0.0, 1.0] defines mesh fineness
1464     #  @return True or False
1465     #  @ingroup l3_algos_basic
1466     def AutomaticHexahedralization(self, fineness=0):
1467         dim = self.MeshDimension()
1468         # assign the hypotheses
1469         self.RemoveGlobalHypotheses()
1470         self.Segment().AutomaticLength(fineness)
1471         if dim > 1 :
1472             self.Quadrangle()
1473             pass
1474         if dim > 2 :
1475             self.Hexahedron()
1476             pass
1477         return self.Compute()
1478
1479     ## Assigns a hypothesis
1480     #  @param hyp a hypothesis to assign
1481     #  @param geom a subhape of mesh geometry
1482     #  @return SMESH.Hypothesis_Status
1483     #  @ingroup l2_hypotheses
1484     def AddHypothesis(self, hyp, geom=0):
1485         if isinstance( hyp, Mesh_Algorithm ):
1486             hyp = hyp.GetAlgorithm()
1487             pass
1488         if not geom:
1489             geom = self.geom
1490             if not geom:
1491                 geom = self.mesh.GetShapeToMesh()
1492             pass
1493         AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1494         status = self.mesh.AddHypothesis(geom, hyp)
1495         isAlgo = hyp._narrow( SMESH_Algo )
1496         hyp_name = GetName( hyp )
1497         geom_name = ""
1498         if geom:
1499             geom_name = GetName( geom )
1500         TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1501         return status
1502
1503     ## Return True if an algorithm of hypothesis is assigned to a given shape
1504     #  @param hyp a hypothesis to check
1505     #  @param geom a subhape of mesh geometry
1506     #  @return True of False
1507     #  @ingroup l2_hypotheses
1508     def IsUsedHypothesis(self, hyp, geom):
1509         if not hyp: # or not geom
1510             return False
1511         if isinstance( hyp, Mesh_Algorithm ):
1512             hyp = hyp.GetAlgorithm()
1513             pass
1514         hyps = self.GetHypothesisList(geom)
1515         for h in hyps:
1516             if h.GetId() == hyp.GetId():
1517                 return True
1518         return False
1519
1520     ## Unassigns a hypothesis
1521     #  @param hyp a hypothesis to unassign
1522     #  @param geom a sub-shape of mesh geometry
1523     #  @return SMESH.Hypothesis_Status
1524     #  @ingroup l2_hypotheses
1525     def RemoveHypothesis(self, hyp, geom=0):
1526         if not hyp:
1527             return None
1528         if isinstance( hyp, Mesh_Algorithm ):
1529             hyp = hyp.GetAlgorithm()
1530             pass
1531         shape = geom
1532         if not shape:
1533             shape = self.geom
1534             pass
1535         if self.IsUsedHypothesis( hyp, shape ):
1536             return self.mesh.RemoveHypothesis( shape, hyp )
1537         hypName = GetName( hyp )
1538         geoName = GetName( shape )
1539         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1540         return None
1541
1542     ## Gets the list of hypotheses added on a geometry
1543     #  @param geom a sub-shape of mesh geometry
1544     #  @return the sequence of SMESH_Hypothesis
1545     #  @ingroup l2_hypotheses
1546     def GetHypothesisList(self, geom):
1547         return self.mesh.GetHypothesisList( geom )
1548
1549     ## Removes all global hypotheses
1550     #  @ingroup l2_hypotheses
1551     def RemoveGlobalHypotheses(self):
1552         current_hyps = self.mesh.GetHypothesisList( self.geom )
1553         for hyp in current_hyps:
1554             self.mesh.RemoveHypothesis( self.geom, hyp )
1555             pass
1556         pass
1557
1558    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1559     ## allowing to overwrite the file if it exists or add the exported data to its contents
1560     #  @param f is the file name
1561     #  @param auto_groups boolean parameter for creating/not creating
1562     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1563     #  the typical use is auto_groups=false.
1564     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1565     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1566     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1567     #  @ingroup l2_impexp
1568     def ExportMED(self, f, auto_groups=0, version=MED_V2_2, overwrite=1, meshPart=None):
1569         if meshPart:
1570             if isinstance( meshPart, list ):
1571                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1572             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite )
1573         else:
1574             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite)
1575
1576     ## Exports the mesh in a file in SAUV format
1577     #  @param f is the file name
1578     #  @param auto_groups boolean parameter for creating/not creating
1579     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1580     #  the typical use is auto_groups=false.
1581     #  @ingroup l2_impexp
1582     def ExportSAUV(self, f, auto_groups=0):
1583         self.mesh.ExportSAUV(f, auto_groups)
1584
1585     ## Exports the mesh in a file in DAT format
1586     #  @param f the file name
1587     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1588     #  @ingroup l2_impexp
1589     def ExportDAT(self, f, meshPart=None):
1590         if meshPart:
1591             if isinstance( meshPart, list ):
1592                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1593             self.mesh.ExportPartToDAT( meshPart, f )
1594         else:
1595             self.mesh.ExportDAT(f)
1596
1597     ## Exports the mesh in a file in UNV format
1598     #  @param f the file name
1599     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1600     #  @ingroup l2_impexp
1601     def ExportUNV(self, f, meshPart=None):
1602         if meshPart:
1603             if isinstance( meshPart, list ):
1604                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1605             self.mesh.ExportPartToUNV( meshPart, f )
1606         else:
1607             self.mesh.ExportUNV(f)
1608
1609     ## Export the mesh in a file in STL format
1610     #  @param f the file name
1611     #  @param ascii defines the file encoding
1612     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1613     #  @ingroup l2_impexp
1614     def ExportSTL(self, f, ascii=1, meshPart=None):
1615         if meshPart:
1616             if isinstance( meshPart, list ):
1617                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1618             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1619         else:
1620             self.mesh.ExportSTL(f, ascii)
1621
1622     ## Exports the mesh in a file in CGNS format
1623     #  @param f is the file name
1624     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1625     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1626     #  @ingroup l2_impexp
1627     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1628         if isinstance( meshPart, list ):
1629             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1630         if isinstance( meshPart, Mesh ):
1631             meshPart = meshPart.mesh
1632         elif not meshPart:
1633             meshPart = self.mesh
1634         self.mesh.ExportCGNS(meshPart, f, overwrite)
1635
1636     ## Exports the mesh in a file in GMF format
1637     #  @param f is the file name
1638     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1639     #  @ingroup l2_impexp
1640     def ExportGMF(self, f, meshPart=None):
1641         if isinstance( meshPart, list ):
1642             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1643         if isinstance( meshPart, Mesh ):
1644             meshPart = meshPart.mesh
1645         elif not meshPart:
1646             meshPart = self.mesh
1647         self.mesh.ExportGMF(meshPart, f, True)
1648
1649     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1650     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1651     ## allowing to overwrite the file if it exists or add the exported data to its contents
1652     #  @param f the file name
1653     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1654     #  @param opt boolean parameter for creating/not creating
1655     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1656     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1657     #  @ingroup l2_impexp
1658     def ExportToMED(self, f, version, opt=0, overwrite=1):
1659         self.mesh.ExportToMEDX(f, opt, version, overwrite)
1660
1661     # Operations with groups:
1662     # ----------------------
1663
1664     ## Creates an empty mesh group
1665     #  @param elementType the type of elements in the group
1666     #  @param name the name of the mesh group
1667     #  @return SMESH_Group
1668     #  @ingroup l2_grps_create
1669     def CreateEmptyGroup(self, elementType, name):
1670         return self.mesh.CreateGroup(elementType, name)
1671
1672     ## Creates a mesh group based on the geometric object \a grp
1673     #  and gives a \a name, \n if this parameter is not defined
1674     #  the name is the same as the geometric group name \n
1675     #  Note: Works like GroupOnGeom().
1676     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1677     #  @param name the name of the mesh group
1678     #  @return SMESH_GroupOnGeom
1679     #  @ingroup l2_grps_create
1680     def Group(self, grp, name=""):
1681         return self.GroupOnGeom(grp, name)
1682
1683     ## Creates a mesh group based on the geometrical object \a grp
1684     #  and gives a \a name, \n if this parameter is not defined
1685     #  the name is the same as the geometrical group name
1686     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1687     #  @param name the name of the mesh group
1688     #  @param typ  the type of elements in the group. If not set, it is
1689     #              automatically detected by the type of the geometry
1690     #  @return SMESH_GroupOnGeom
1691     #  @ingroup l2_grps_create
1692     def GroupOnGeom(self, grp, name="", typ=None):
1693         AssureGeomPublished( self, grp, name )
1694         if name == "":
1695             name = grp.GetName()
1696         if not typ:
1697             typ = self._groupTypeFromShape( grp )
1698         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1699
1700     ## Pivate method to get a type of group on geometry
1701     def _groupTypeFromShape( self, shape ):
1702         tgeo = str(shape.GetShapeType())
1703         if tgeo == "VERTEX":
1704             typ = NODE
1705         elif tgeo == "EDGE":
1706             typ = EDGE
1707         elif tgeo == "FACE" or tgeo == "SHELL":
1708             typ = FACE
1709         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1710             typ = VOLUME
1711         elif tgeo == "COMPOUND":
1712             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1713             if not sub:
1714                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1715             return self._groupTypeFromShape( sub[0] )
1716         else:
1717             raise ValueError, \
1718                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1719         return typ
1720
1721     ## Creates a mesh group with given \a name based on the \a filter which
1722     ## is a special type of group dynamically updating it's contents during
1723     ## mesh modification
1724     #  @param typ  the type of elements in the group
1725     #  @param name the name of the mesh group
1726     #  @param filter the filter defining group contents
1727     #  @return SMESH_GroupOnFilter
1728     #  @ingroup l2_grps_create
1729     def GroupOnFilter(self, typ, name, filter):
1730         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1731
1732     ## Creates a mesh group by the given ids of elements
1733     #  @param groupName the name of the mesh group
1734     #  @param elementType the type of elements in the group
1735     #  @param elemIDs the list of ids
1736     #  @return SMESH_Group
1737     #  @ingroup l2_grps_create
1738     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1739         group = self.mesh.CreateGroup(elementType, groupName)
1740         group.Add(elemIDs)
1741         return group
1742
1743     ## Creates a mesh group by the given conditions
1744     #  @param groupName the name of the mesh group
1745     #  @param elementType the type of elements in the group
1746     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1747     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1748     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
1749     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
1750     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1751     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
1752     #  @return SMESH_Group
1753     #  @ingroup l2_grps_create
1754     def MakeGroup(self,
1755                   groupName,
1756                   elementType,
1757                   CritType=FT_Undefined,
1758                   Compare=FT_EqualTo,
1759                   Threshold="",
1760                   UnaryOp=FT_Undefined,
1761                   Tolerance=1e-07):
1762         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1763         group = self.MakeGroupByCriterion(groupName, aCriterion)
1764         return group
1765
1766     ## Creates a mesh group by the given criterion
1767     #  @param groupName the name of the mesh group
1768     #  @param Criterion the instance of Criterion class
1769     #  @return SMESH_Group
1770     #  @ingroup l2_grps_create
1771     def MakeGroupByCriterion(self, groupName, Criterion):
1772         aFilterMgr = self.smeshpyD.CreateFilterManager()
1773         aFilter = aFilterMgr.CreateFilter()
1774         aCriteria = []
1775         aCriteria.append(Criterion)
1776         aFilter.SetCriteria(aCriteria)
1777         group = self.MakeGroupByFilter(groupName, aFilter)
1778         aFilterMgr.UnRegister()
1779         return group
1780
1781     ## Creates a mesh group by the given criteria (list of criteria)
1782     #  @param groupName the name of the mesh group
1783     #  @param theCriteria the list of criteria
1784     #  @return SMESH_Group
1785     #  @ingroup l2_grps_create
1786     def MakeGroupByCriteria(self, groupName, theCriteria):
1787         aFilterMgr = self.smeshpyD.CreateFilterManager()
1788         aFilter = aFilterMgr.CreateFilter()
1789         aFilter.SetCriteria(theCriteria)
1790         group = self.MakeGroupByFilter(groupName, aFilter)
1791         aFilterMgr.UnRegister()
1792         return group
1793
1794     ## Creates a mesh group by the given filter
1795     #  @param groupName the name of the mesh group
1796     #  @param theFilter the instance of Filter class
1797     #  @return SMESH_Group
1798     #  @ingroup l2_grps_create
1799     def MakeGroupByFilter(self, groupName, theFilter):
1800         group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1801         theFilter.SetMesh( self.mesh )
1802         group.AddFrom( theFilter )
1803         return group
1804
1805     ## Removes a group
1806     #  @ingroup l2_grps_delete
1807     def RemoveGroup(self, group):
1808         self.mesh.RemoveGroup(group)
1809
1810     ## Removes a group with its contents
1811     #  @ingroup l2_grps_delete
1812     def RemoveGroupWithContents(self, group):
1813         self.mesh.RemoveGroupWithContents(group)
1814
1815     ## Gets the list of groups existing in the mesh
1816     #  @return a sequence of SMESH_GroupBase
1817     #  @ingroup l2_grps_create
1818     def GetGroups(self):
1819         return self.mesh.GetGroups()
1820
1821     ## Gets the number of groups existing in the mesh
1822     #  @return the quantity of groups as an integer value
1823     #  @ingroup l2_grps_create
1824     def NbGroups(self):
1825         return self.mesh.NbGroups()
1826
1827     ## Gets the list of names of groups existing in the mesh
1828     #  @return list of strings
1829     #  @ingroup l2_grps_create
1830     def GetGroupNames(self):
1831         groups = self.GetGroups()
1832         names = []
1833         for group in groups:
1834             names.append(group.GetName())
1835         return names
1836
1837     ## Produces a union of two groups
1838     #  A new group is created. All mesh elements that are
1839     #  present in the initial groups are added to the new one
1840     #  @return an instance of SMESH_Group
1841     #  @ingroup l2_grps_operon
1842     def UnionGroups(self, group1, group2, name):
1843         return self.mesh.UnionGroups(group1, group2, name)
1844
1845     ## Produces a union list of groups
1846     #  New group is created. All mesh elements that are present in
1847     #  initial groups are added to the new one
1848     #  @return an instance of SMESH_Group
1849     #  @ingroup l2_grps_operon
1850     def UnionListOfGroups(self, groups, name):
1851       return self.mesh.UnionListOfGroups(groups, name)
1852
1853     ## Prodices an intersection of two groups
1854     #  A new group is created. All mesh elements that are common
1855     #  for the two initial groups are added to the new one.
1856     #  @return an instance of SMESH_Group
1857     #  @ingroup l2_grps_operon
1858     def IntersectGroups(self, group1, group2, name):
1859         return self.mesh.IntersectGroups(group1, group2, name)
1860
1861     ## Produces an intersection of groups
1862     #  New group is created. All mesh elements that are present in all
1863     #  initial groups simultaneously are added to the new one
1864     #  @return an instance of SMESH_Group
1865     #  @ingroup l2_grps_operon
1866     def IntersectListOfGroups(self, groups, name):
1867       return self.mesh.IntersectListOfGroups(groups, name)
1868
1869     ## Produces a cut of two groups
1870     #  A new group is created. All mesh elements that are present in
1871     #  the main group but are not present in the tool group are added to the new one
1872     #  @return an instance of SMESH_Group
1873     #  @ingroup l2_grps_operon
1874     def CutGroups(self, main_group, tool_group, name):
1875         return self.mesh.CutGroups(main_group, tool_group, name)
1876
1877     ## Produces a cut of groups
1878     #  A new group is created. All mesh elements that are present in main groups
1879     #  but do not present in tool groups are added to the new one
1880     #  @return an instance of SMESH_Group
1881     #  @ingroup l2_grps_operon
1882     def CutListOfGroups(self, main_groups, tool_groups, name):
1883       return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1884
1885     ## Produces a group of elements of specified type using list of existing groups
1886     #  A new group is created. System
1887     #  1) extracts all nodes on which groups elements are built
1888     #  2) combines all elements of specified dimension laying on these nodes
1889     #  @return an instance of SMESH_Group
1890     #  @ingroup l2_grps_operon
1891     def CreateDimGroup(self, groups, elem_type, name):
1892       return self.mesh.CreateDimGroup(groups, elem_type, name)
1893
1894
1895     ## Convert group on geom into standalone group
1896     #  @ingroup l2_grps_delete
1897     def ConvertToStandalone(self, group):
1898         return self.mesh.ConvertToStandalone(group)
1899
1900     # Get some info about mesh:
1901     # ------------------------
1902
1903     ## Returns the log of nodes and elements added or removed
1904     #  since the previous clear of the log.
1905     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
1906     #  @return list of log_block structures:
1907     #                                        commandType
1908     #                                        number
1909     #                                        coords
1910     #                                        indexes
1911     #  @ingroup l1_auxiliary
1912     def GetLog(self, clearAfterGet):
1913         return self.mesh.GetLog(clearAfterGet)
1914
1915     ## Clears the log of nodes and elements added or removed since the previous
1916     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
1917     #  @ingroup l1_auxiliary
1918     def ClearLog(self):
1919         self.mesh.ClearLog()
1920
1921     ## Toggles auto color mode on the object.
1922     #  @param theAutoColor the flag which toggles auto color mode.
1923     #  @ingroup l1_auxiliary
1924     def SetAutoColor(self, theAutoColor):
1925         self.mesh.SetAutoColor(theAutoColor)
1926
1927     ## Gets flag of object auto color mode.
1928     #  @return True or False
1929     #  @ingroup l1_auxiliary
1930     def GetAutoColor(self):
1931         return self.mesh.GetAutoColor()
1932
1933     ## Gets the internal ID
1934     #  @return integer value, which is the internal Id of the mesh
1935     #  @ingroup l1_auxiliary
1936     def GetId(self):
1937         return self.mesh.GetId()
1938
1939     ## Get the study Id
1940     #  @return integer value, which is the study Id of the mesh
1941     #  @ingroup l1_auxiliary
1942     def GetStudyId(self):
1943         return self.mesh.GetStudyId()
1944
1945     ## Checks the group names for duplications.
1946     #  Consider the maximum group name length stored in MED file.
1947     #  @return True or False
1948     #  @ingroup l1_auxiliary
1949     def HasDuplicatedGroupNamesMED(self):
1950         return self.mesh.HasDuplicatedGroupNamesMED()
1951
1952     ## Obtains the mesh editor tool
1953     #  @return an instance of SMESH_MeshEditor
1954     #  @ingroup l1_modifying
1955     def GetMeshEditor(self):
1956         return self.editor
1957
1958     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
1959     #  can be passed as argument to a method accepting mesh, group or sub-mesh
1960     #  @return an instance of SMESH_IDSource
1961     #  @ingroup l1_auxiliary
1962     def GetIDSource(self, ids, elemType):
1963         return self.editor.MakeIDSource(ids, elemType)
1964
1965     ## Gets MED Mesh
1966     #  @return an instance of SALOME_MED::MESH
1967     #  @ingroup l1_auxiliary
1968     def GetMEDMesh(self):
1969         return self.mesh.GetMEDMesh()
1970
1971
1972     # Get informations about mesh contents:
1973     # ------------------------------------
1974
1975     ## Gets the mesh stattistic
1976     #  @return dictionary type element - count of elements
1977     #  @ingroup l1_meshinfo
1978     def GetMeshInfo(self, obj = None):
1979         if not obj: obj = self.mesh
1980         return self.smeshpyD.GetMeshInfo(obj)
1981
1982     ## Returns the number of nodes in the mesh
1983     #  @return an integer value
1984     #  @ingroup l1_meshinfo
1985     def NbNodes(self):
1986         return self.mesh.NbNodes()
1987
1988     ## Returns the number of elements in the mesh
1989     #  @return an integer value
1990     #  @ingroup l1_meshinfo
1991     def NbElements(self):
1992         return self.mesh.NbElements()
1993
1994     ## Returns the number of 0d elements in the mesh
1995     #  @return an integer value
1996     #  @ingroup l1_meshinfo
1997     def Nb0DElements(self):
1998         return self.mesh.Nb0DElements()
1999
2000     ## Returns the number of ball discrete elements in the mesh
2001     #  @return an integer value
2002     #  @ingroup l1_meshinfo
2003     def NbBalls(self):
2004         return self.mesh.NbBalls()
2005
2006     ## Returns the number of edges in the mesh
2007     #  @return an integer value
2008     #  @ingroup l1_meshinfo
2009     def NbEdges(self):
2010         return self.mesh.NbEdges()
2011
2012     ## Returns the number of edges with the given order in the mesh
2013     #  @param elementOrder the order of elements:
2014     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2015     #  @return an integer value
2016     #  @ingroup l1_meshinfo
2017     def NbEdgesOfOrder(self, elementOrder):
2018         return self.mesh.NbEdgesOfOrder(elementOrder)
2019
2020     ## Returns the number of faces in the mesh
2021     #  @return an integer value
2022     #  @ingroup l1_meshinfo
2023     def NbFaces(self):
2024         return self.mesh.NbFaces()
2025
2026     ## Returns the number of faces with the given order in the mesh
2027     #  @param elementOrder the order of elements:
2028     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2029     #  @return an integer value
2030     #  @ingroup l1_meshinfo
2031     def NbFacesOfOrder(self, elementOrder):
2032         return self.mesh.NbFacesOfOrder(elementOrder)
2033
2034     ## Returns the number of triangles in the mesh
2035     #  @return an integer value
2036     #  @ingroup l1_meshinfo
2037     def NbTriangles(self):
2038         return self.mesh.NbTriangles()
2039
2040     ## Returns the number of triangles with the given order in the mesh
2041     #  @param elementOrder is the order of elements:
2042     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2043     #  @return an integer value
2044     #  @ingroup l1_meshinfo
2045     def NbTrianglesOfOrder(self, elementOrder):
2046         return self.mesh.NbTrianglesOfOrder(elementOrder)
2047
2048     ## Returns the number of biquadratic triangles in the mesh
2049     #  @return an integer value
2050     #  @ingroup l1_meshinfo
2051     def NbBiQuadTriangles(self):
2052         return self.mesh.NbBiQuadTriangles()
2053
2054     ## Returns the number of quadrangles in the mesh
2055     #  @return an integer value
2056     #  @ingroup l1_meshinfo
2057     def NbQuadrangles(self):
2058         return self.mesh.NbQuadrangles()
2059
2060     ## Returns the number of quadrangles with the given order in the mesh
2061     #  @param elementOrder the order of elements:
2062     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2063     #  @return an integer value
2064     #  @ingroup l1_meshinfo
2065     def NbQuadranglesOfOrder(self, elementOrder):
2066         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2067
2068     ## Returns the number of biquadratic quadrangles in the mesh
2069     #  @return an integer value
2070     #  @ingroup l1_meshinfo
2071     def NbBiQuadQuadrangles(self):
2072         return self.mesh.NbBiQuadQuadrangles()
2073
2074     ## Returns the number of polygons in the mesh
2075     #  @return an integer value
2076     #  @ingroup l1_meshinfo
2077     def NbPolygons(self):
2078         return self.mesh.NbPolygons()
2079
2080     ## Returns the number of volumes in the mesh
2081     #  @return an integer value
2082     #  @ingroup l1_meshinfo
2083     def NbVolumes(self):
2084         return self.mesh.NbVolumes()
2085
2086     ## Returns the number of volumes with the given order in the mesh
2087     #  @param elementOrder  the order of elements:
2088     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2089     #  @return an integer value
2090     #  @ingroup l1_meshinfo
2091     def NbVolumesOfOrder(self, elementOrder):
2092         return self.mesh.NbVolumesOfOrder(elementOrder)
2093
2094     ## Returns the number of tetrahedrons in the mesh
2095     #  @return an integer value
2096     #  @ingroup l1_meshinfo
2097     def NbTetras(self):
2098         return self.mesh.NbTetras()
2099
2100     ## Returns the number of tetrahedrons with the given order in the mesh
2101     #  @param elementOrder  the order of elements:
2102     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2103     #  @return an integer value
2104     #  @ingroup l1_meshinfo
2105     def NbTetrasOfOrder(self, elementOrder):
2106         return self.mesh.NbTetrasOfOrder(elementOrder)
2107
2108     ## Returns the number of hexahedrons in the mesh
2109     #  @return an integer value
2110     #  @ingroup l1_meshinfo
2111     def NbHexas(self):
2112         return self.mesh.NbHexas()
2113
2114     ## Returns the number of hexahedrons with the given order in the mesh
2115     #  @param elementOrder  the order of elements:
2116     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2117     #  @return an integer value
2118     #  @ingroup l1_meshinfo
2119     def NbHexasOfOrder(self, elementOrder):
2120         return self.mesh.NbHexasOfOrder(elementOrder)
2121
2122     ## Returns the number of triquadratic hexahedrons in the mesh
2123     #  @return an integer value
2124     #  @ingroup l1_meshinfo
2125     def NbTriQuadraticHexas(self):
2126         return self.mesh.NbTriQuadraticHexas()
2127
2128     ## Returns the number of pyramids in the mesh
2129     #  @return an integer value
2130     #  @ingroup l1_meshinfo
2131     def NbPyramids(self):
2132         return self.mesh.NbPyramids()
2133
2134     ## Returns the number of pyramids with the given order in the mesh
2135     #  @param elementOrder  the order of elements:
2136     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2137     #  @return an integer value
2138     #  @ingroup l1_meshinfo
2139     def NbPyramidsOfOrder(self, elementOrder):
2140         return self.mesh.NbPyramidsOfOrder(elementOrder)
2141
2142     ## Returns the number of prisms in the mesh
2143     #  @return an integer value
2144     #  @ingroup l1_meshinfo
2145     def NbPrisms(self):
2146         return self.mesh.NbPrisms()
2147
2148     ## Returns the number of prisms with the given order in the mesh
2149     #  @param elementOrder  the order of elements:
2150     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2151     #  @return an integer value
2152     #  @ingroup l1_meshinfo
2153     def NbPrismsOfOrder(self, elementOrder):
2154         return self.mesh.NbPrismsOfOrder(elementOrder)
2155
2156     ## Returns the number of hexagonal prisms in the mesh
2157     #  @return an integer value
2158     #  @ingroup l1_meshinfo
2159     def NbHexagonalPrisms(self):
2160         return self.mesh.NbHexagonalPrisms()
2161
2162     ## Returns the number of polyhedrons in the mesh
2163     #  @return an integer value
2164     #  @ingroup l1_meshinfo
2165     def NbPolyhedrons(self):
2166         return self.mesh.NbPolyhedrons()
2167
2168     ## Returns the number of submeshes in the mesh
2169     #  @return an integer value
2170     #  @ingroup l1_meshinfo
2171     def NbSubMesh(self):
2172         return self.mesh.NbSubMesh()
2173
2174     ## Returns the list of mesh elements IDs
2175     #  @return the list of integer values
2176     #  @ingroup l1_meshinfo
2177     def GetElementsId(self):
2178         return self.mesh.GetElementsId()
2179
2180     ## Returns the list of IDs of mesh elements with the given type
2181     #  @param elementType  the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2182     #  @return list of integer values
2183     #  @ingroup l1_meshinfo
2184     def GetElementsByType(self, elementType):
2185         return self.mesh.GetElementsByType(elementType)
2186
2187     ## Returns the list of mesh nodes IDs
2188     #  @return the list of integer values
2189     #  @ingroup l1_meshinfo
2190     def GetNodesId(self):
2191         return self.mesh.GetNodesId()
2192
2193     # Get the information about mesh elements:
2194     # ------------------------------------
2195
2196     ## Returns the type of mesh element
2197     #  @return the value from SMESH::ElementType enumeration
2198     #  @ingroup l1_meshinfo
2199     def GetElementType(self, id, iselem):
2200         return self.mesh.GetElementType(id, iselem)
2201
2202     ## Returns the geometric type of mesh element
2203     #  @return the value from SMESH::EntityType enumeration
2204     #  @ingroup l1_meshinfo
2205     def GetElementGeomType(self, id):
2206         return self.mesh.GetElementGeomType(id)
2207
2208     ## Returns the list of submesh elements IDs
2209     #  @param Shape a geom object(sub-shape) IOR
2210     #         Shape must be the sub-shape of a ShapeToMesh()
2211     #  @return the list of integer values
2212     #  @ingroup l1_meshinfo
2213     def GetSubMeshElementsId(self, Shape):
2214         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2215             ShapeID = Shape.GetSubShapeIndices()[0]
2216         else:
2217             ShapeID = Shape
2218         return self.mesh.GetSubMeshElementsId(ShapeID)
2219
2220     ## Returns the list of submesh nodes IDs
2221     #  @param Shape a geom object(sub-shape) IOR
2222     #         Shape must be the sub-shape of a ShapeToMesh()
2223     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2224     #  @return the list of integer values
2225     #  @ingroup l1_meshinfo
2226     def GetSubMeshNodesId(self, Shape, all):
2227         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2228             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2229         else:
2230             ShapeID = Shape
2231         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2232
2233     ## Returns type of elements on given shape
2234     #  @param Shape a geom object(sub-shape) IOR
2235     #         Shape must be a sub-shape of a ShapeToMesh()
2236     #  @return element type
2237     #  @ingroup l1_meshinfo
2238     def GetSubMeshElementType(self, Shape):
2239         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2240             ShapeID = Shape.GetSubShapeIndices()[0]
2241         else:
2242             ShapeID = Shape
2243         return self.mesh.GetSubMeshElementType(ShapeID)
2244
2245     ## Gets the mesh description
2246     #  @return string value
2247     #  @ingroup l1_meshinfo
2248     def Dump(self):
2249         return self.mesh.Dump()
2250
2251
2252     # Get the information about nodes and elements of a mesh by its IDs:
2253     # -----------------------------------------------------------
2254
2255     ## Gets XYZ coordinates of a node
2256     #  \n If there is no nodes for the given ID - returns an empty list
2257     #  @return a list of double precision values
2258     #  @ingroup l1_meshinfo
2259     def GetNodeXYZ(self, id):
2260         return self.mesh.GetNodeXYZ(id)
2261
2262     ## Returns list of IDs of inverse elements for the given node
2263     #  \n If there is no node for the given ID - returns an empty list
2264     #  @return a list of integer values
2265     #  @ingroup l1_meshinfo
2266     def GetNodeInverseElements(self, id):
2267         return self.mesh.GetNodeInverseElements(id)
2268
2269     ## @brief Returns the position of a node on the shape
2270     #  @return SMESH::NodePosition
2271     #  @ingroup l1_meshinfo
2272     def GetNodePosition(self,NodeID):
2273         return self.mesh.GetNodePosition(NodeID)
2274
2275     ## @brief Returns the position of an element on the shape
2276     #  @return SMESH::ElementPosition
2277     #  @ingroup l1_meshinfo
2278     def GetElementPosition(self,ElemID):
2279         return self.mesh.GetElementPosition(ElemID)
2280
2281     ## If the given element is a node, returns the ID of shape
2282     #  \n If there is no node for the given ID - returns -1
2283     #  @return an integer value
2284     #  @ingroup l1_meshinfo
2285     def GetShapeID(self, id):
2286         return self.mesh.GetShapeID(id)
2287
2288     ## Returns the ID of the result shape after
2289     #  FindShape() from SMESH_MeshEditor for the given element
2290     #  \n If there is no element for the given ID - returns -1
2291     #  @return an integer value
2292     #  @ingroup l1_meshinfo
2293     def GetShapeIDForElem(self,id):
2294         return self.mesh.GetShapeIDForElem(id)
2295
2296     ## Returns the number of nodes for the given element
2297     #  \n If there is no element for the given ID - returns -1
2298     #  @return an integer value
2299     #  @ingroup l1_meshinfo
2300     def GetElemNbNodes(self, id):
2301         return self.mesh.GetElemNbNodes(id)
2302
2303     ## Returns the node ID the given (zero based) index for the given element
2304     #  \n If there is no element for the given ID - returns -1
2305     #  \n If there is no node for the given index - returns -2
2306     #  @return an integer value
2307     #  @ingroup l1_meshinfo
2308     def GetElemNode(self, id, index):
2309         return self.mesh.GetElemNode(id, index)
2310
2311     ## Returns the IDs of nodes of the given element
2312     #  @return a list of integer values
2313     #  @ingroup l1_meshinfo
2314     def GetElemNodes(self, id):
2315         return self.mesh.GetElemNodes(id)
2316
2317     ## Returns true if the given node is the medium node in the given quadratic element
2318     #  @ingroup l1_meshinfo
2319     def IsMediumNode(self, elementID, nodeID):
2320         return self.mesh.IsMediumNode(elementID, nodeID)
2321
2322     ## Returns true if the given node is the medium node in one of quadratic elements
2323     #  @ingroup l1_meshinfo
2324     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2325         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2326
2327     ## Returns the number of edges for the given element
2328     #  @ingroup l1_meshinfo
2329     def ElemNbEdges(self, id):
2330         return self.mesh.ElemNbEdges(id)
2331
2332     ## Returns the number of faces for the given element
2333     #  @ingroup l1_meshinfo
2334     def ElemNbFaces(self, id):
2335         return self.mesh.ElemNbFaces(id)
2336
2337     ## Returns nodes of given face (counted from zero) for given volumic element.
2338     #  @ingroup l1_meshinfo
2339     def GetElemFaceNodes(self,elemId, faceIndex):
2340         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2341
2342     ## Returns an element based on all given nodes.
2343     #  @ingroup l1_meshinfo
2344     def FindElementByNodes(self,nodes):
2345         return self.mesh.FindElementByNodes(nodes)
2346
2347     ## Returns true if the given element is a polygon
2348     #  @ingroup l1_meshinfo
2349     def IsPoly(self, id):
2350         return self.mesh.IsPoly(id)
2351
2352     ## Returns true if the given element is quadratic
2353     #  @ingroup l1_meshinfo
2354     def IsQuadratic(self, id):
2355         return self.mesh.IsQuadratic(id)
2356
2357     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2358     #  @ingroup l1_meshinfo
2359     def GetBallDiameter(self, id):
2360         return self.mesh.GetBallDiameter(id)
2361
2362     ## Returns XYZ coordinates of the barycenter of the given element
2363     #  \n If there is no element for the given ID - returns an empty list
2364     #  @return a list of three double values
2365     #  @ingroup l1_meshinfo
2366     def BaryCenter(self, id):
2367         return self.mesh.BaryCenter(id)
2368
2369     ## Passes mesh elements through the given filter and return IDs of fitting elements
2370     #  @param theFilter SMESH_Filter
2371     #  @return a list of ids
2372     #  @ingroup l1_controls
2373     def GetIdsFromFilter(self, theFilter):
2374         theFilter.SetMesh( self.mesh )
2375         return theFilter.GetIDs()
2376
2377     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2378     #  Returns a list of special structures (borders).
2379     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2380     #  @ingroup l1_controls
2381     def GetFreeBorders(self):
2382         aFilterMgr = self.smeshpyD.CreateFilterManager()
2383         aPredicate = aFilterMgr.CreateFreeEdges()
2384         aPredicate.SetMesh(self.mesh)
2385         aBorders = aPredicate.GetBorders()
2386         aFilterMgr.UnRegister()
2387         return aBorders
2388
2389
2390     # Get mesh measurements information:
2391     # ------------------------------------
2392
2393     ## Get minimum distance between two nodes, elements or distance to the origin
2394     #  @param id1 first node/element id
2395     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2396     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2397     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2398     #  @return minimum distance value
2399     #  @sa GetMinDistance()
2400     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2401         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2402         return aMeasure.value
2403
2404     ## Get measure structure specifying minimum distance data between two objects
2405     #  @param id1 first node/element id
2406     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2407     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2408     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2409     #  @return Measure structure
2410     #  @sa MinDistance()
2411     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2412         if isElem1:
2413             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2414         else:
2415             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2416         if id2 != 0:
2417             if isElem2:
2418                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2419             else:
2420                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2421             pass
2422         else:
2423             id2 = None
2424
2425         aMeasurements = self.smeshpyD.CreateMeasurements()
2426         aMeasure = aMeasurements.MinDistance(id1, id2)
2427         aMeasurements.UnRegister()
2428         return aMeasure
2429
2430     ## Get bounding box of the specified object(s)
2431     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2432     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2433     #  @c False specifies that @a objects are nodes
2434     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2435     #  @sa GetBoundingBox()
2436     def BoundingBox(self, objects=None, isElem=False):
2437         result = self.GetBoundingBox(objects, isElem)
2438         if result is None:
2439             result = (0.0,)*6
2440         else:
2441             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2442         return result
2443
2444     ## Get measure structure specifying bounding box data of the specified object(s)
2445     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2446     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2447     #  @c False specifies that @a objects are nodes
2448     #  @return Measure structure
2449     #  @sa BoundingBox()
2450     def GetBoundingBox(self, IDs=None, isElem=False):
2451         if IDs is None:
2452             IDs = [self.mesh]
2453         elif isinstance(IDs, tuple):
2454             IDs = list(IDs)
2455         if not isinstance(IDs, list):
2456             IDs = [IDs]
2457         if len(IDs) > 0 and isinstance(IDs[0], int):
2458             IDs = [IDs]
2459         srclist = []
2460         for o in IDs:
2461             if isinstance(o, Mesh):
2462                 srclist.append(o.mesh)
2463             elif hasattr(o, "_narrow"):
2464                 src = o._narrow(SMESH.SMESH_IDSource)
2465                 if src: srclist.append(src)
2466                 pass
2467             elif isinstance(o, list):
2468                 if isElem:
2469                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2470                 else:
2471                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2472                 pass
2473             pass
2474         aMeasurements = self.smeshpyD.CreateMeasurements()
2475         aMeasure = aMeasurements.BoundingBox(srclist)
2476         aMeasurements.UnRegister()
2477         return aMeasure
2478
2479     # Mesh edition (SMESH_MeshEditor functionality):
2480     # ---------------------------------------------
2481
2482     ## Removes the elements from the mesh by ids
2483     #  @param IDsOfElements is a list of ids of elements to remove
2484     #  @return True or False
2485     #  @ingroup l2_modif_del
2486     def RemoveElements(self, IDsOfElements):
2487         return self.editor.RemoveElements(IDsOfElements)
2488
2489     ## Removes nodes from mesh by ids
2490     #  @param IDsOfNodes is a list of ids of nodes to remove
2491     #  @return True or False
2492     #  @ingroup l2_modif_del
2493     def RemoveNodes(self, IDsOfNodes):
2494         return self.editor.RemoveNodes(IDsOfNodes)
2495
2496     ## Removes all orphan (free) nodes from mesh
2497     #  @return number of the removed nodes
2498     #  @ingroup l2_modif_del
2499     def RemoveOrphanNodes(self):
2500         return self.editor.RemoveOrphanNodes()
2501
2502     ## Add a node to the mesh by coordinates
2503     #  @return Id of the new node
2504     #  @ingroup l2_modif_add
2505     def AddNode(self, x, y, z):
2506         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2507         if hasVars: self.mesh.SetParameters(Parameters)
2508         return self.editor.AddNode( x, y, z)
2509
2510     ## Creates a 0D element on a node with given number.
2511     #  @param IDOfNode the ID of node for creation of the element.
2512     #  @return the Id of the new 0D element
2513     #  @ingroup l2_modif_add
2514     def Add0DElement(self, IDOfNode):
2515         return self.editor.Add0DElement(IDOfNode)
2516
2517     ## Create 0D elements on all nodes of the given elements except those 
2518     #  nodes on which a 0D element already exists.
2519     #  @param theObject an object on whose nodes 0D elements will be created.
2520     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2521     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2522     #  @param theGroupName optional name of a group to add 0D elements created
2523     #         and/or found on nodes of \a theObject.
2524     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2525     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2526     #          can be retrieved from the returned object by calling GetIDs()
2527     #  @ingroup l2_modif_add
2528     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2529         if isinstance( theObject, Mesh ):
2530             theObject = theObject.GetMesh()
2531         if isinstance( theObject, list ):
2532             theObject = self.GetIDSource( theObject, SMESH.ALL )
2533         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2534
2535     ## Creates a ball element on a node with given ID.
2536     #  @param IDOfNode the ID of node for creation of the element.
2537     #  @param diameter the bal diameter.
2538     #  @return the Id of the new ball element
2539     #  @ingroup l2_modif_add
2540     def AddBall(self, IDOfNode, diameter):
2541         return self.editor.AddBall( IDOfNode, diameter )
2542
2543     ## Creates a linear or quadratic edge (this is determined
2544     #  by the number of given nodes).
2545     #  @param IDsOfNodes the list of node IDs for creation of the element.
2546     #  The order of nodes in this list should correspond to the description
2547     #  of MED. \n This description is located by the following link:
2548     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2549     #  @return the Id of the new edge
2550     #  @ingroup l2_modif_add
2551     def AddEdge(self, IDsOfNodes):
2552         return self.editor.AddEdge(IDsOfNodes)
2553
2554     ## Creates a linear or quadratic face (this is determined
2555     #  by the number of given nodes).
2556     #  @param IDsOfNodes the list of node IDs for creation of the element.
2557     #  The order of nodes in this list should correspond to the description
2558     #  of MED. \n This description is located by the following link:
2559     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2560     #  @return the Id of the new face
2561     #  @ingroup l2_modif_add
2562     def AddFace(self, IDsOfNodes):
2563         return self.editor.AddFace(IDsOfNodes)
2564
2565     ## Adds a polygonal face to the mesh by the list of node IDs
2566     #  @param IdsOfNodes the list of node IDs for creation of the element.
2567     #  @return the Id of the new face
2568     #  @ingroup l2_modif_add
2569     def AddPolygonalFace(self, IdsOfNodes):
2570         return self.editor.AddPolygonalFace(IdsOfNodes)
2571
2572     ## Creates both simple and quadratic volume (this is determined
2573     #  by the number of given nodes).
2574     #  @param IDsOfNodes the list of node IDs for creation of the element.
2575     #  The order of nodes in this list should correspond to the description
2576     #  of MED. \n This description is located by the following link:
2577     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2578     #  @return the Id of the new volumic element
2579     #  @ingroup l2_modif_add
2580     def AddVolume(self, IDsOfNodes):
2581         return self.editor.AddVolume(IDsOfNodes)
2582
2583     ## Creates a volume of many faces, giving nodes for each face.
2584     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2585     #  @param Quantities the list of integer values, Quantities[i]
2586     #         gives the quantity of nodes in face number i.
2587     #  @return the Id of the new volumic element
2588     #  @ingroup l2_modif_add
2589     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2590         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2591
2592     ## Creates a volume of many faces, giving the IDs of the existing faces.
2593     #  @param IdsOfFaces the list of face IDs for volume creation.
2594     #
2595     #  Note:  The created volume will refer only to the nodes
2596     #         of the given faces, not to the faces themselves.
2597     #  @return the Id of the new volumic element
2598     #  @ingroup l2_modif_add
2599     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2600         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2601
2602
2603     ## @brief Binds a node to a vertex
2604     #  @param NodeID a node ID
2605     #  @param Vertex a vertex or vertex ID
2606     #  @return True if succeed else raises an exception
2607     #  @ingroup l2_modif_add
2608     def SetNodeOnVertex(self, NodeID, Vertex):
2609         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2610             VertexID = Vertex.GetSubShapeIndices()[0]
2611         else:
2612             VertexID = Vertex
2613         try:
2614             self.editor.SetNodeOnVertex(NodeID, VertexID)
2615         except SALOME.SALOME_Exception, inst:
2616             raise ValueError, inst.details.text
2617         return True
2618
2619
2620     ## @brief Stores the node position on an edge
2621     #  @param NodeID a node ID
2622     #  @param Edge an edge or edge ID
2623     #  @param paramOnEdge a parameter on the edge where the node is located
2624     #  @return True if succeed else raises an exception
2625     #  @ingroup l2_modif_add
2626     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2627         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2628             EdgeID = Edge.GetSubShapeIndices()[0]
2629         else:
2630             EdgeID = Edge
2631         try:
2632             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2633         except SALOME.SALOME_Exception, inst:
2634             raise ValueError, inst.details.text
2635         return True
2636
2637     ## @brief Stores node position on a face
2638     #  @param NodeID a node ID
2639     #  @param Face a face or face ID
2640     #  @param u U parameter on the face where the node is located
2641     #  @param v V parameter on the face where the node is located
2642     #  @return True if succeed else raises an exception
2643     #  @ingroup l2_modif_add
2644     def SetNodeOnFace(self, NodeID, Face, u, v):
2645         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2646             FaceID = Face.GetSubShapeIndices()[0]
2647         else:
2648             FaceID = Face
2649         try:
2650             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2651         except SALOME.SALOME_Exception, inst:
2652             raise ValueError, inst.details.text
2653         return True
2654
2655     ## @brief Binds a node to a solid
2656     #  @param NodeID a node ID
2657     #  @param Solid  a solid or solid ID
2658     #  @return True if succeed else raises an exception
2659     #  @ingroup l2_modif_add
2660     def SetNodeInVolume(self, NodeID, Solid):
2661         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2662             SolidID = Solid.GetSubShapeIndices()[0]
2663         else:
2664             SolidID = Solid
2665         try:
2666             self.editor.SetNodeInVolume(NodeID, SolidID)
2667         except SALOME.SALOME_Exception, inst:
2668             raise ValueError, inst.details.text
2669         return True
2670
2671     ## @brief Bind an element to a shape
2672     #  @param ElementID an element ID
2673     #  @param Shape a shape or shape ID
2674     #  @return True if succeed else raises an exception
2675     #  @ingroup l2_modif_add
2676     def SetMeshElementOnShape(self, ElementID, Shape):
2677         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2678             ShapeID = Shape.GetSubShapeIndices()[0]
2679         else:
2680             ShapeID = Shape
2681         try:
2682             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2683         except SALOME.SALOME_Exception, inst:
2684             raise ValueError, inst.details.text
2685         return True
2686
2687
2688     ## Moves the node with the given id
2689     #  @param NodeID the id of the node
2690     #  @param x  a new X coordinate
2691     #  @param y  a new Y coordinate
2692     #  @param z  a new Z coordinate
2693     #  @return True if succeed else False
2694     #  @ingroup l2_modif_movenode
2695     def MoveNode(self, NodeID, x, y, z):
2696         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2697         if hasVars: self.mesh.SetParameters(Parameters)
2698         return self.editor.MoveNode(NodeID, x, y, z)
2699
2700     ## Finds the node closest to a point and moves it to a point location
2701     #  @param x  the X coordinate of a point
2702     #  @param y  the Y coordinate of a point
2703     #  @param z  the Z coordinate of a point
2704     #  @param NodeID if specified (>0), the node with this ID is moved,
2705     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
2706     #  @return the ID of a node
2707     #  @ingroup l2_modif_throughp
2708     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2709         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2710         if hasVars: self.mesh.SetParameters(Parameters)
2711         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2712
2713     ## Finds the node closest to a point
2714     #  @param x  the X coordinate of a point
2715     #  @param y  the Y coordinate of a point
2716     #  @param z  the Z coordinate of a point
2717     #  @return the ID of a node
2718     #  @ingroup l2_modif_throughp
2719     def FindNodeClosestTo(self, x, y, z):
2720         #preview = self.mesh.GetMeshEditPreviewer()
2721         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2722         return self.editor.FindNodeClosestTo(x, y, z)
2723
2724     ## Finds the elements where a point lays IN or ON
2725     #  @param x  the X coordinate of a point
2726     #  @param y  the Y coordinate of a point
2727     #  @param z  the Z coordinate of a point
2728     #  @param elementType type of elements to find (SMESH.ALL type
2729     #         means elements of any type excluding nodes, discrete and 0D elements)
2730     #  @param meshPart a part of mesh (group, sub-mesh) to search within
2731     #  @return list of IDs of found elements
2732     #  @ingroup l2_modif_throughp
2733     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2734         if meshPart:
2735             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2736         else:
2737             return self.editor.FindElementsByPoint(x, y, z, elementType)
2738
2739     # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2740     # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2741     # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2742
2743     def GetPointState(self, x, y, z):
2744         return self.editor.GetPointState(x, y, z)
2745
2746     ## Finds the node closest to a point and moves it to a point location
2747     #  @param x  the X coordinate of a point
2748     #  @param y  the Y coordinate of a point
2749     #  @param z  the Z coordinate of a point
2750     #  @return the ID of a moved node
2751     #  @ingroup l2_modif_throughp
2752     def MeshToPassThroughAPoint(self, x, y, z):
2753         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2754
2755     ## Replaces two neighbour triangles sharing Node1-Node2 link
2756     #  with the triangles built on the same 4 nodes but having other common link.
2757     #  @param NodeID1  the ID of the first node
2758     #  @param NodeID2  the ID of the second node
2759     #  @return false if proper faces were not found
2760     #  @ingroup l2_modif_invdiag
2761     def InverseDiag(self, NodeID1, NodeID2):
2762         return self.editor.InverseDiag(NodeID1, NodeID2)
2763
2764     ## Replaces two neighbour triangles sharing Node1-Node2 link
2765     #  with a quadrangle built on the same 4 nodes.
2766     #  @param NodeID1  the ID of the first node
2767     #  @param NodeID2  the ID of the second node
2768     #  @return false if proper faces were not found
2769     #  @ingroup l2_modif_unitetri
2770     def DeleteDiag(self, NodeID1, NodeID2):
2771         return self.editor.DeleteDiag(NodeID1, NodeID2)
2772
2773     ## Reorients elements by ids
2774     #  @param IDsOfElements if undefined reorients all mesh elements
2775     #  @return True if succeed else False
2776     #  @ingroup l2_modif_changori
2777     def Reorient(self, IDsOfElements=None):
2778         if IDsOfElements == None:
2779             IDsOfElements = self.GetElementsId()
2780         return self.editor.Reorient(IDsOfElements)
2781
2782     ## Reorients all elements of the object
2783     #  @param theObject mesh, submesh or group
2784     #  @return True if succeed else False
2785     #  @ingroup l2_modif_changori
2786     def ReorientObject(self, theObject):
2787         if ( isinstance( theObject, Mesh )):
2788             theObject = theObject.GetMesh()
2789         return self.editor.ReorientObject(theObject)
2790
2791     ## Reorient faces contained in \a the2DObject.
2792     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2793     #  @param theDirection is a desired direction of normal of \a theFace.
2794     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
2795     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2796     #         compared with theDirection. It can be either ID of face or a point
2797     #         by which the face will be found. The point can be given as either
2798     #         a GEOM vertex or a list of point coordinates.
2799     #  @return number of reoriented faces
2800     #  @ingroup l2_modif_changori
2801     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2802         # check the2DObject
2803         if isinstance( the2DObject, Mesh ):
2804             the2DObject = the2DObject.GetMesh()
2805         if isinstance( the2DObject, list ):
2806             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2807         # check theDirection
2808         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2809             theDirection = self.smeshpyD.GetDirStruct( theDirection )
2810         if isinstance( theDirection, list ):
2811             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
2812         # prepare theFace and thePoint
2813         theFace = theFaceOrPoint
2814         thePoint = PointStruct(0,0,0)
2815         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2816             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2817             theFace = -1
2818         if isinstance( theFaceOrPoint, list ):
2819             thePoint = PointStruct( *theFaceOrPoint )
2820             theFace = -1
2821         if isinstance( theFaceOrPoint, PointStruct ):
2822             thePoint = theFaceOrPoint
2823             theFace = -1
2824         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2825
2826     ## Fuses the neighbouring triangles into quadrangles.
2827     #  @param IDsOfElements The triangles to be fused,
2828     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
2829     #                       choose a neighbour to fuse with.
2830     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
2831     #                       is still performed; theMaxAngle is mesured in radians.
2832     #                       Also it could be a name of variable which defines angle in degrees.
2833     #  @return TRUE in case of success, FALSE otherwise.
2834     #  @ingroup l2_modif_unitetri
2835     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2836         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2837         self.mesh.SetParameters(Parameters)
2838         if not IDsOfElements:
2839             IDsOfElements = self.GetElementsId()
2840         Functor = self.smeshpyD.GetFunctor(theCriterion)
2841         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2842
2843     ## Fuses the neighbouring triangles of the object into quadrangles
2844     #  @param theObject is mesh, submesh or group
2845     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2846     #         choose a neighbour to fuse with.
2847     #  @param MaxAngle   a max angle between element normals at which the fusion
2848     #                   is still performed; theMaxAngle is mesured in radians.
2849     #  @return TRUE in case of success, FALSE otherwise.
2850     #  @ingroup l2_modif_unitetri
2851     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2852         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2853         self.mesh.SetParameters(Parameters)
2854         if isinstance( theObject, Mesh ):
2855             theObject = theObject.GetMesh()
2856         Functor = self.smeshpyD.GetFunctor(theCriterion)
2857         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2858
2859     ## Splits quadrangles into triangles.
2860     #
2861     #  @param IDsOfElements the faces to be splitted.
2862     #  @param theCriterion   is a numerical functor, in terms of enum SMESH.FunctorType, used to
2863     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
2864     #         value, then quadrangles will be split by the smallest diagonal.
2865     #  @return TRUE in case of success, FALSE otherwise.
2866     #  @ingroup l2_modif_cutquadr
2867     def QuadToTri (self, IDsOfElements, theCriterion = None):
2868         if IDsOfElements == []:
2869             IDsOfElements = self.GetElementsId()
2870         if theCriterion is None:
2871             theCriterion = FT_MaxElementLength2D
2872         Functor = self.smeshpyD.GetFunctor(theCriterion)
2873         return self.editor.QuadToTri(IDsOfElements, Functor)
2874
2875     ## Splits quadrangles into triangles.
2876     #  @param theObject the object from which the list of elements is taken,
2877     #         this is mesh, submesh or group
2878     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2879     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
2880     #         value, then quadrangles will be split by the smallest diagonal.
2881     #  @return TRUE in case of success, FALSE otherwise.
2882     #  @ingroup l2_modif_cutquadr
2883     def QuadToTriObject (self, theObject, theCriterion = None):
2884         if ( isinstance( theObject, Mesh )):
2885             theObject = theObject.GetMesh()
2886         if theCriterion is None:
2887             theCriterion = FT_MaxElementLength2D
2888         Functor = self.smeshpyD.GetFunctor(theCriterion)
2889         return self.editor.QuadToTriObject(theObject, Functor)
2890
2891     ## Splits quadrangles into triangles.
2892     #  @param IDsOfElements the faces to be splitted
2893     #  @param Diag13        is used to choose a diagonal for splitting.
2894     #  @return TRUE in case of success, FALSE otherwise.
2895     #  @ingroup l2_modif_cutquadr
2896     def SplitQuad (self, IDsOfElements, Diag13):
2897         if IDsOfElements == []:
2898             IDsOfElements = self.GetElementsId()
2899         return self.editor.SplitQuad(IDsOfElements, Diag13)
2900
2901     ## Splits quadrangles into triangles.
2902     #  @param theObject the object from which the list of elements is taken,
2903     #         this is mesh, submesh or group
2904     #  @param Diag13    is used to choose a diagonal for splitting.
2905     #  @return TRUE in case of success, FALSE otherwise.
2906     #  @ingroup l2_modif_cutquadr
2907     def SplitQuadObject (self, theObject, Diag13):
2908         if ( isinstance( theObject, Mesh )):
2909             theObject = theObject.GetMesh()
2910         return self.editor.SplitQuadObject(theObject, Diag13)
2911
2912     ## Finds a better splitting of the given quadrangle.
2913     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
2914     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
2915     #         choose a diagonal for splitting.
2916     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
2917     #          diagonal is better, 0 if error occurs.
2918     #  @ingroup l2_modif_cutquadr
2919     def BestSplit (self, IDOfQuad, theCriterion):
2920         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
2921
2922     ## Splits volumic elements into tetrahedrons
2923     #  @param elemIDs either list of elements or mesh or group or submesh
2924     #  @param method  flags passing splitting method: Hex_5Tet, Hex_6Tet, Hex_24Tet
2925     #         Hex_5Tet - split the hexahedron into 5 tetrahedrons, etc
2926     #  @ingroup l2_modif_cutquadr
2927     def SplitVolumesIntoTetra(self, elemIDs, method=smeshBuilder.Hex_5Tet ):
2928         if isinstance( elemIDs, Mesh ):
2929             elemIDs = elemIDs.GetMesh()
2930         if ( isinstance( elemIDs, list )):
2931             elemIDs = self.editor.MakeIDSource(elemIDs, SMESH.VOLUME)
2932         self.editor.SplitVolumesIntoTetra(elemIDs, method)
2933
2934     ## Splits quadrangle faces near triangular facets of volumes
2935     #
2936     #  @ingroup l1_auxiliary
2937     def SplitQuadsNearTriangularFacets(self):
2938         faces_array = self.GetElementsByType(SMESH.FACE)
2939         for face_id in faces_array:
2940             if self.GetElemNbNodes(face_id) == 4: # quadrangle
2941                 quad_nodes = self.mesh.GetElemNodes(face_id)
2942                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2943                 isVolumeFound = False
2944                 for node1_elem in node1_elems:
2945                     if not isVolumeFound:
2946                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2947                             nb_nodes = self.GetElemNbNodes(node1_elem)
2948                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
2949                                 volume_elem = node1_elem
2950                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
2951                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
2952                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
2953                                         isVolumeFound = True
2954                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
2955                                             self.SplitQuad([face_id], False) # diagonal 2-4
2956                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
2957                                         isVolumeFound = True
2958                                         self.SplitQuad([face_id], True) # diagonal 1-3
2959                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
2960                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
2961                                         isVolumeFound = True
2962                                         self.SplitQuad([face_id], True) # diagonal 1-3
2963
2964     ## @brief Splits hexahedrons into tetrahedrons.
2965     #
2966     #  This operation uses pattern mapping functionality for splitting.
2967     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
2968     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
2969     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
2970     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
2971     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
2972     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
2973     #  @return TRUE in case of success, FALSE otherwise.
2974     #  @ingroup l1_auxiliary
2975     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
2976         # Pattern:     5.---------.6
2977         #              /|#*      /|
2978         #             / | #*    / |
2979         #            /  |  # * /  |
2980         #           /   |   # /*  |
2981         # (0,0,1) 4.---------.7 * |
2982         #          |#*  |1   | # *|
2983         #          | # *.----|---#.2
2984         #          |  #/ *   |   /
2985         #          |  /#  *  |  /
2986         #          | /   # * | /
2987         #          |/      #*|/
2988         # (0,0,0) 0.---------.3
2989         pattern_tetra = "!!! Nb of points: \n 8 \n\
2990         !!! Points: \n\
2991         0 0 0  !- 0 \n\
2992         0 1 0  !- 1 \n\
2993         1 1 0  !- 2 \n\
2994         1 0 0  !- 3 \n\
2995         0 0 1  !- 4 \n\
2996         0 1 1  !- 5 \n\
2997         1 1 1  !- 6 \n\
2998         1 0 1  !- 7 \n\
2999         !!! Indices of points of 6 tetras: \n\
3000         0 3 4 1 \n\
3001         7 4 3 1 \n\
3002         4 7 5 1 \n\
3003         6 2 5 7 \n\
3004         1 5 2 7 \n\
3005         2 3 1 7 \n"
3006
3007         pattern = self.smeshpyD.GetPattern()
3008         isDone  = pattern.LoadFromFile(pattern_tetra)
3009         if not isDone:
3010             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3011             return isDone
3012
3013         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3014         isDone = pattern.MakeMesh(self.mesh, False, False)
3015         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3016
3017         # split quafrangle faces near triangular facets of volumes
3018         self.SplitQuadsNearTriangularFacets()
3019
3020         return isDone
3021
3022     ## @brief Split hexahedrons into prisms.
3023     #
3024     #  Uses the pattern mapping functionality for splitting.
3025     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3026     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3027     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3028     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3029     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3030     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3031     #  @return TRUE in case of success, FALSE otherwise.
3032     #  @ingroup l1_auxiliary
3033     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3034         # Pattern:     5.---------.6
3035         #              /|#       /|
3036         #             / | #     / |
3037         #            /  |  #   /  |
3038         #           /   |   # /   |
3039         # (0,0,1) 4.---------.7   |
3040         #          |    |    |    |
3041         #          |   1.----|----.2
3042         #          |   / *   |   /
3043         #          |  /   *  |  /
3044         #          | /     * | /
3045         #          |/       *|/
3046         # (0,0,0) 0.---------.3
3047         pattern_prism = "!!! Nb of points: \n 8 \n\
3048         !!! Points: \n\
3049         0 0 0  !- 0 \n\
3050         0 1 0  !- 1 \n\
3051         1 1 0  !- 2 \n\
3052         1 0 0  !- 3 \n\
3053         0 0 1  !- 4 \n\
3054         0 1 1  !- 5 \n\
3055         1 1 1  !- 6 \n\
3056         1 0 1  !- 7 \n\
3057         !!! Indices of points of 2 prisms: \n\
3058         0 1 3 4 5 7 \n\
3059         2 3 1 6 7 5 \n"
3060
3061         pattern = self.smeshpyD.GetPattern()
3062         isDone  = pattern.LoadFromFile(pattern_prism)
3063         if not isDone:
3064             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3065             return isDone
3066
3067         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3068         isDone = pattern.MakeMesh(self.mesh, False, False)
3069         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3070
3071         # Splits quafrangle faces near triangular facets of volumes
3072         self.SplitQuadsNearTriangularFacets()
3073
3074         return isDone
3075
3076     ## Smoothes elements
3077     #  @param IDsOfElements the list if ids of elements to smooth
3078     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3079     #  Note that nodes built on edges and boundary nodes are always fixed.
3080     #  @param MaxNbOfIterations the maximum number of iterations
3081     #  @param MaxAspectRatio varies in range [1.0, inf]
3082     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3083     #  @return TRUE in case of success, FALSE otherwise.
3084     #  @ingroup l2_modif_smooth
3085     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3086                MaxNbOfIterations, MaxAspectRatio, Method):
3087         if IDsOfElements == []:
3088             IDsOfElements = self.GetElementsId()
3089         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3090         self.mesh.SetParameters(Parameters)
3091         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3092                                   MaxNbOfIterations, MaxAspectRatio, Method)
3093
3094     ## Smoothes elements which belong to the given object
3095     #  @param theObject the object to smooth
3096     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3097     #  Note that nodes built on edges and boundary nodes are always fixed.
3098     #  @param MaxNbOfIterations the maximum number of iterations
3099     #  @param MaxAspectRatio varies in range [1.0, inf]
3100     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3101     #  @return TRUE in case of success, FALSE otherwise.
3102     #  @ingroup l2_modif_smooth
3103     def SmoothObject(self, theObject, IDsOfFixedNodes,
3104                      MaxNbOfIterations, MaxAspectRatio, Method):
3105         if ( isinstance( theObject, Mesh )):
3106             theObject = theObject.GetMesh()
3107         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3108                                         MaxNbOfIterations, MaxAspectRatio, Method)
3109
3110     ## Parametrically smoothes the given elements
3111     #  @param IDsOfElements the list if ids of elements to smooth
3112     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3113     #  Note that nodes built on edges and boundary nodes are always fixed.
3114     #  @param MaxNbOfIterations the maximum number of iterations
3115     #  @param MaxAspectRatio varies in range [1.0, inf]
3116     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3117     #  @return TRUE in case of success, FALSE otherwise.
3118     #  @ingroup l2_modif_smooth
3119     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3120                          MaxNbOfIterations, MaxAspectRatio, Method):
3121         if IDsOfElements == []:
3122             IDsOfElements = self.GetElementsId()
3123         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3124         self.mesh.SetParameters(Parameters)
3125         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3126                                             MaxNbOfIterations, MaxAspectRatio, Method)
3127
3128     ## Parametrically smoothes the elements which belong to the given object
3129     #  @param theObject the object to smooth
3130     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3131     #  Note that nodes built on edges and boundary nodes are always fixed.
3132     #  @param MaxNbOfIterations the maximum number of iterations
3133     #  @param MaxAspectRatio varies in range [1.0, inf]
3134     #  @param Method Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3135     #  @return TRUE in case of success, FALSE otherwise.
3136     #  @ingroup l2_modif_smooth
3137     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3138                                MaxNbOfIterations, MaxAspectRatio, Method):
3139         if ( isinstance( theObject, Mesh )):
3140             theObject = theObject.GetMesh()
3141         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3142                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3143
3144     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3145     #  them with quadratic with the same id.
3146     #  @param theForce3d new node creation method:
3147     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3148     #         1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3149     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3150     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3151     #  @ingroup l2_modif_tofromqu
3152     def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3153         if theToBiQuad:
3154             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3155         else:
3156             if theSubMesh:
3157                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3158             else:
3159                 self.editor.ConvertToQuadratic(theForce3d)
3160             
3161     ## Converts the mesh from quadratic to ordinary,
3162     #  deletes old quadratic elements, \n replacing
3163     #  them with ordinary mesh elements with the same id.
3164     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3165     #  @ingroup l2_modif_tofromqu
3166     def ConvertFromQuadratic(self, theSubMesh=None):
3167         if theSubMesh:
3168             self.editor.ConvertFromQuadraticObject(theSubMesh)
3169         else:
3170             return self.editor.ConvertFromQuadratic()
3171
3172     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3173     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3174     #  @ingroup l2_modif_edit
3175     def  Make2DMeshFrom3D(self):
3176         return self.editor. Make2DMeshFrom3D()
3177
3178     ## Creates missing boundary elements
3179     #  @param elements - elements whose boundary is to be checked:
3180     #                    mesh, group, sub-mesh or list of elements
3181     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3182     #  @param dimension - defines type of boundary elements to create:
3183     #                     SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3184     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3185     #  @param groupName - a name of group to store created boundary elements in,
3186     #                     "" means not to create the group
3187     #  @param meshName - a name of new mesh to store created boundary elements in,
3188     #                     "" means not to create the new mesh
3189     #  @param toCopyElements - if true, the checked elements will be copied into
3190     #     the new mesh else only boundary elements will be copied into the new mesh
3191     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3192     #     boundary elements will be copied into the new mesh
3193     #  @return tuple (mesh, group) where bondary elements were added to
3194     #  @ingroup l2_modif_edit
3195     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3196                          toCopyElements=False, toCopyExistingBondary=False):
3197         if isinstance( elements, Mesh ):
3198             elements = elements.GetMesh()
3199         if ( isinstance( elements, list )):
3200             elemType = SMESH.ALL
3201             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3202             elements = self.editor.MakeIDSource(elements, elemType)
3203         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3204                                                    toCopyElements,toCopyExistingBondary)
3205         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3206         return mesh, group
3207
3208     ##
3209     # @brief Creates missing boundary elements around either the whole mesh or 
3210     #    groups of 2D elements
3211     #  @param dimension - defines type of boundary elements to create
3212     #  @param groupName - a name of group to store all boundary elements in,
3213     #    "" means not to create the group
3214     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3215     #    mesh + created boundary elements; "" means not to create the new mesh
3216     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3217     #    the new mesh else only boundary elements will be copied into the new mesh
3218     #  @param groups - groups of 2D elements to make boundary around
3219     #  @retval tuple( long, mesh, groups )
3220     #                 long - number of added boundary elements
3221     #                 mesh - the mesh where elements were added to
3222     #                 group - the group of boundary elements or None
3223     #
3224     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3225                              toCopyAll=False, groups=[]):
3226         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3227                                                            toCopyAll,groups)
3228         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3229         return nb, mesh, group
3230
3231     ## Renumber mesh nodes
3232     #  @ingroup l2_modif_renumber
3233     def RenumberNodes(self):
3234         self.editor.RenumberNodes()
3235
3236     ## Renumber mesh elements
3237     #  @ingroup l2_modif_renumber
3238     def RenumberElements(self):
3239         self.editor.RenumberElements()
3240
3241     ## Generates new elements by rotation of the elements around the axis
3242     #  @param IDsOfElements the list of ids of elements to sweep
3243     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3244     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3245     #  @param NbOfSteps the number of steps
3246     #  @param Tolerance tolerance
3247     #  @param MakeGroups forces the generation of new groups from existing ones
3248     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3249     #                    of all steps, else - size of each step
3250     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3251     #  @ingroup l2_modif_extrurev
3252     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3253                       MakeGroups=False, TotalAngle=False):
3254         if IDsOfElements == []:
3255             IDsOfElements = self.GetElementsId()
3256         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3257             Axis = self.smeshpyD.GetAxisStruct(Axis)
3258         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3259         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3260         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3261         self.mesh.SetParameters(Parameters)
3262         if TotalAngle and NbOfSteps:
3263             AngleInRadians /= NbOfSteps
3264         if MakeGroups:
3265             return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3266                                                        AngleInRadians, NbOfSteps, Tolerance)
3267         self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3268         return []
3269
3270     ## Generates new elements by rotation of the elements of object around the axis
3271     #  @param theObject object which elements should be sweeped.
3272     #                   It can be a mesh, a sub mesh or a group.
3273     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3274     #  @param AngleInRadians the angle of Rotation
3275     #  @param NbOfSteps number of steps
3276     #  @param Tolerance tolerance
3277     #  @param MakeGroups forces the generation of new groups from existing ones
3278     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3279     #                    of all steps, else - size of each step
3280     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3281     #  @ingroup l2_modif_extrurev
3282     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3283                             MakeGroups=False, TotalAngle=False):
3284         if ( isinstance( theObject, Mesh )):
3285             theObject = theObject.GetMesh()
3286         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3287             Axis = self.smeshpyD.GetAxisStruct(Axis)
3288         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3289         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3290         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3291         self.mesh.SetParameters(Parameters)
3292         if TotalAngle and NbOfSteps:
3293             AngleInRadians /= NbOfSteps
3294         if MakeGroups:
3295             return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3296                                                              NbOfSteps, Tolerance)
3297         self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3298         return []
3299
3300     ## Generates new elements by rotation of the elements of object around the axis
3301     #  @param theObject object which elements should be sweeped.
3302     #                   It can be a mesh, a sub mesh or a group.
3303     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3304     #  @param AngleInRadians the angle of Rotation
3305     #  @param NbOfSteps number of steps
3306     #  @param Tolerance tolerance
3307     #  @param MakeGroups forces the generation of new groups from existing ones
3308     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3309     #                    of all steps, else - size of each step
3310     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3311     #  @ingroup l2_modif_extrurev
3312     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3313                               MakeGroups=False, TotalAngle=False):
3314         if ( isinstance( theObject, Mesh )):
3315             theObject = theObject.GetMesh()
3316         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3317             Axis = self.smeshpyD.GetAxisStruct(Axis)
3318         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3319         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3320         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3321         self.mesh.SetParameters(Parameters)
3322         if TotalAngle and NbOfSteps:
3323             AngleInRadians /= NbOfSteps
3324         if MakeGroups:
3325             return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3326                                                                NbOfSteps, Tolerance)
3327         self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3328         return []
3329
3330     ## Generates new elements by rotation of the elements of object around the axis
3331     #  @param theObject object which elements should be sweeped.
3332     #                   It can be a mesh, a sub mesh or a group.
3333     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3334     #  @param AngleInRadians the angle of Rotation
3335     #  @param NbOfSteps number of steps
3336     #  @param Tolerance tolerance
3337     #  @param MakeGroups forces the generation of new groups from existing ones
3338     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3339     #                    of all steps, else - size of each step
3340     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3341     #  @ingroup l2_modif_extrurev
3342     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3343                               MakeGroups=False, TotalAngle=False):
3344         if ( isinstance( theObject, Mesh )):
3345             theObject = theObject.GetMesh()
3346         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3347             Axis = self.smeshpyD.GetAxisStruct(Axis)
3348         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3349         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3350         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3351         self.mesh.SetParameters(Parameters)
3352         if TotalAngle and NbOfSteps:
3353             AngleInRadians /= NbOfSteps
3354         if MakeGroups:
3355             return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3356                                                              NbOfSteps, Tolerance)
3357         self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3358         return []
3359
3360     ## Generates new elements by extrusion of the elements with given ids
3361     #  @param IDsOfElements the list of elements ids for extrusion
3362     #  @param StepVector vector or DirStruct or 3 vector components, defining
3363     #         the direction and value of extrusion for one step (the total extrusion
3364     #         length will be NbOfSteps * ||StepVector||)
3365     #  @param NbOfSteps the number of steps
3366     #  @param MakeGroups forces the generation of new groups from existing ones
3367     #  @param IsNodes is True if elements with given ids are nodes
3368     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3369     #  @ingroup l2_modif_extrurev
3370     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3371         if IDsOfElements == []:
3372             IDsOfElements = self.GetElementsId()
3373         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3374             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3375         if isinstance( StepVector, list ):
3376             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3377         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3378         Parameters = StepVector.PS.parameters + var_separator + Parameters
3379         self.mesh.SetParameters(Parameters)
3380         if MakeGroups:
3381             if(IsNodes):
3382                 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3383             else:
3384                 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3385         if(IsNodes):
3386             self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3387         else:
3388             self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3389         return []
3390
3391     ## Generates new elements by extrusion of the elements with given ids
3392     #  @param IDsOfElements is ids of elements
3393     #  @param StepVector vector or DirStruct or 3 vector components, defining
3394     #         the direction and value of extrusion for one step (the total extrusion
3395     #         length will be NbOfSteps * ||StepVector||)
3396     #  @param NbOfSteps the number of steps
3397     #  @param ExtrFlags sets flags for extrusion
3398     #  @param SewTolerance uses for comparing locations of nodes if flag
3399     #         EXTRUSION_FLAG_SEW is set
3400     #  @param MakeGroups forces the generation of new groups from existing ones
3401     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3402     #  @ingroup l2_modif_extrurev
3403     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3404                           ExtrFlags, SewTolerance, MakeGroups=False):
3405         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3406             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3407         if isinstance( StepVector, list ):
3408             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3409         if MakeGroups:
3410             return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3411                                                            ExtrFlags, SewTolerance)
3412         self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3413                                       ExtrFlags, SewTolerance)
3414         return []
3415
3416     ## Generates new elements by extrusion of the elements which belong to the object
3417     #  @param theObject the object which elements should be processed.
3418     #                   It can be a mesh, a sub mesh or a group.
3419     #  @param StepVector vector or DirStruct or 3 vector components, defining
3420     #         the direction and value of extrusion for one step (the total extrusion
3421     #         length will be NbOfSteps * ||StepVector||)
3422     #  @param NbOfSteps the number of steps
3423     #  @param MakeGroups forces the generation of new groups from existing ones
3424     #  @param  IsNodes is True if elements which belong to the object are nodes
3425     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3426     #  @ingroup l2_modif_extrurev
3427     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3428         if ( isinstance( theObject, Mesh )):
3429             theObject = theObject.GetMesh()
3430         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3431             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3432         if isinstance( StepVector, list ):
3433             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3434         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3435         Parameters = StepVector.PS.parameters + var_separator + Parameters
3436         self.mesh.SetParameters(Parameters)
3437         if MakeGroups:
3438             if(IsNodes):
3439                 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3440             else:
3441                 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3442         if(IsNodes):
3443             self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3444         else:
3445             self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3446         return []
3447
3448     ## Generates new elements by extrusion of the elements which belong to the object
3449     #  @param theObject object which elements should be processed.
3450     #                   It can be a mesh, a sub mesh or a group.
3451     #  @param StepVector vector or DirStruct or 3 vector components, defining
3452     #         the direction and value of extrusion for one step (the total extrusion
3453     #         length will be NbOfSteps * ||StepVector||)
3454     #  @param NbOfSteps the number of steps
3455     #  @param MakeGroups to generate new groups from existing ones
3456     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3457     #  @ingroup l2_modif_extrurev
3458     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3459         if ( isinstance( theObject, Mesh )):
3460             theObject = theObject.GetMesh()
3461         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3462             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3463         if isinstance( StepVector, list ):
3464             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3465         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3466         Parameters = StepVector.PS.parameters + var_separator + Parameters
3467         self.mesh.SetParameters(Parameters)
3468         if MakeGroups:
3469             return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3470         self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3471         return []
3472
3473     ## Generates new elements by extrusion of the elements which belong to the object
3474     #  @param theObject object which elements should be processed.
3475     #                   It can be a mesh, a sub mesh or a group.
3476     #  @param StepVector vector or DirStruct or 3 vector components, defining
3477     #         the direction and value of extrusion for one step (the total extrusion
3478     #         length will be NbOfSteps * ||StepVector||)
3479     #  @param NbOfSteps the number of steps
3480     #  @param MakeGroups forces the generation of new groups from existing ones
3481     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3482     #  @ingroup l2_modif_extrurev
3483     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3484         if ( isinstance( theObject, Mesh )):
3485             theObject = theObject.GetMesh()
3486         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3487             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3488         if isinstance( StepVector, list ):
3489             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3490         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3491         Parameters = StepVector.PS.parameters + var_separator + Parameters
3492         self.mesh.SetParameters(Parameters)
3493         if MakeGroups:
3494             return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3495         self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3496         return []
3497
3498
3499
3500     ## Generates new elements by extrusion of the given elements
3501     #  The path of extrusion must be a meshed edge.
3502     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3503     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3504     #  @param NodeStart the start node from Path. Defines the direction of extrusion
3505     #  @param HasAngles allows the shape to be rotated around the path
3506     #                   to get the resulting mesh in a helical fashion
3507     #  @param Angles list of angles in radians
3508     #  @param LinearVariation forces the computation of rotation angles as linear
3509     #                         variation of the given Angles along path steps
3510     #  @param HasRefPoint allows using the reference point
3511     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3512     #         The User can specify any point as the Reference Point.
3513     #  @param MakeGroups forces the generation of new groups from existing ones
3514     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
3515     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3516     #          only SMESH::Extrusion_Error otherwise
3517     #  @ingroup l2_modif_extrurev
3518     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3519                             HasAngles, Angles, LinearVariation,
3520                             HasRefPoint, RefPoint, MakeGroups, ElemType):
3521         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3522             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3523             pass
3524         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3525         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3526         self.mesh.SetParameters(Parameters)
3527
3528         if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3529
3530         if isinstance(Base, list):
3531             IDsOfElements = []
3532             if Base == []: IDsOfElements = self.GetElementsId()
3533             else: IDsOfElements = Base
3534             return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3535                                                    HasAngles, Angles, LinearVariation,
3536                                                    HasRefPoint, RefPoint, MakeGroups, ElemType)
3537         else:
3538             if isinstance(Base, Mesh): Base = Base.GetMesh()
3539             if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3540                 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3541                                                           HasAngles, Angles, LinearVariation,
3542                                                           HasRefPoint, RefPoint, MakeGroups, ElemType)
3543             else:
3544                 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3545
3546
3547     ## Generates new elements by extrusion of the given elements
3548     #  The path of extrusion must be a meshed edge.
3549     #  @param IDsOfElements ids of elements
3550     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3551     #  @param PathShape shape(edge) defines the sub-mesh for the path
3552     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3553     #  @param HasAngles allows the shape to be rotated around the path
3554     #                   to get the resulting mesh in a helical fashion
3555     #  @param Angles list of angles in radians
3556     #  @param HasRefPoint allows using the reference point
3557     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3558     #         The User can specify any point as the Reference Point.
3559     #  @param MakeGroups forces the generation of new groups from existing ones
3560     #  @param LinearVariation forces the computation of rotation angles as linear
3561     #                         variation of the given Angles along path steps
3562     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3563     #          only SMESH::Extrusion_Error otherwise
3564     #  @ingroup l2_modif_extrurev
3565     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3566                            HasAngles, Angles, HasRefPoint, RefPoint,
3567                            MakeGroups=False, LinearVariation=False):
3568         if IDsOfElements == []:
3569             IDsOfElements = self.GetElementsId()
3570         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3571             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3572             pass
3573         if ( isinstance( PathMesh, Mesh )):
3574             PathMesh = PathMesh.GetMesh()
3575         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3576         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3577         self.mesh.SetParameters(Parameters)
3578         if HasAngles and Angles and LinearVariation:
3579             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3580             pass
3581         if MakeGroups:
3582             return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3583                                                             PathShape, NodeStart, HasAngles,
3584                                                             Angles, HasRefPoint, RefPoint)
3585         return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3586                                               NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3587
3588     ## Generates new elements by extrusion of the elements which belong to the object
3589     #  The path of extrusion must be a meshed edge.
3590     #  @param theObject the object which elements should be processed.
3591     #                   It can be a mesh, a sub mesh or a group.
3592     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3593     #  @param PathShape shape(edge) defines the sub-mesh for the path
3594     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3595     #  @param HasAngles allows the shape to be rotated around the path
3596     #                   to get the resulting mesh in a helical fashion
3597     #  @param Angles list of angles
3598     #  @param HasRefPoint allows using the reference point
3599     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3600     #         The User can specify any point as the Reference Point.
3601     #  @param MakeGroups forces the generation of new groups from existing ones
3602     #  @param LinearVariation forces the computation of rotation angles as linear
3603     #                         variation of the given Angles along path steps
3604     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3605     #          only SMESH::Extrusion_Error otherwise
3606     #  @ingroup l2_modif_extrurev
3607     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3608                                  HasAngles, Angles, HasRefPoint, RefPoint,
3609                                  MakeGroups=False, LinearVariation=False):
3610         if ( isinstance( theObject, Mesh )):
3611             theObject = theObject.GetMesh()
3612         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3613             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3614         if ( isinstance( PathMesh, Mesh )):
3615             PathMesh = PathMesh.GetMesh()
3616         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3617         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3618         self.mesh.SetParameters(Parameters)
3619         if HasAngles and Angles and LinearVariation:
3620             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3621             pass
3622         if MakeGroups:
3623             return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3624                                                                   PathShape, NodeStart, HasAngles,
3625                                                                   Angles, HasRefPoint, RefPoint)
3626         return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3627                                                     NodeStart, HasAngles, Angles, HasRefPoint,
3628                                                     RefPoint)
3629
3630     ## Generates new elements by extrusion of the elements which belong to the object
3631     #  The path of extrusion must be a meshed edge.
3632     #  @param theObject the object which elements should be processed.
3633     #                   It can be a mesh, a sub mesh or a group.
3634     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3635     #  @param PathShape shape(edge) defines the sub-mesh for the path
3636     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3637     #  @param HasAngles allows the shape to be rotated around the path
3638     #                   to get the resulting mesh in a helical fashion
3639     #  @param Angles list of angles
3640     #  @param HasRefPoint allows using the reference point
3641     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3642     #         The User can specify any point as the Reference Point.
3643     #  @param MakeGroups forces the generation of new groups from existing ones
3644     #  @param LinearVariation forces the computation of rotation angles as linear
3645     #                         variation of the given Angles along path steps
3646     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3647     #          only SMESH::Extrusion_Error otherwise
3648     #  @ingroup l2_modif_extrurev
3649     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3650                                    HasAngles, Angles, HasRefPoint, RefPoint,
3651                                    MakeGroups=False, LinearVariation=False):
3652         if ( isinstance( theObject, Mesh )):
3653             theObject = theObject.GetMesh()
3654         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3655             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3656         if ( isinstance( PathMesh, Mesh )):
3657             PathMesh = PathMesh.GetMesh()
3658         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3659         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3660         self.mesh.SetParameters(Parameters)
3661         if HasAngles and Angles and LinearVariation:
3662             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3663             pass
3664         if MakeGroups:
3665             return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3666                                                                     PathShape, NodeStart, HasAngles,
3667                                                                     Angles, HasRefPoint, RefPoint)
3668         return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3669                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3670                                                       RefPoint)
3671
3672     ## Generates new elements by extrusion of the elements which belong to the object
3673     #  The path of extrusion must be a meshed edge.
3674     #  @param theObject the object which elements should be processed.
3675     #                   It can be a mesh, a sub mesh or a group.
3676     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3677     #  @param PathShape shape(edge) defines the sub-mesh for the path
3678     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3679     #  @param HasAngles allows the shape to be rotated around the path
3680     #                   to get the resulting mesh in a helical fashion
3681     #  @param Angles list of angles
3682     #  @param HasRefPoint allows using the reference point
3683     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3684     #         The User can specify any point as the Reference Point.
3685     #  @param MakeGroups forces the generation of new groups from existing ones
3686     #  @param LinearVariation forces the computation of rotation angles as linear
3687     #                         variation of the given Angles along path steps
3688     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3689     #          only SMESH::Extrusion_Error otherwise
3690     #  @ingroup l2_modif_extrurev
3691     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3692                                    HasAngles, Angles, HasRefPoint, RefPoint,
3693                                    MakeGroups=False, LinearVariation=False):
3694         if ( isinstance( theObject, Mesh )):
3695             theObject = theObject.GetMesh()
3696         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3697             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3698         if ( isinstance( PathMesh, Mesh )):
3699             PathMesh = PathMesh.GetMesh()
3700         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3701         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3702         self.mesh.SetParameters(Parameters)
3703         if HasAngles and Angles and LinearVariation:
3704             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3705             pass
3706         if MakeGroups:
3707             return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3708                                                                     PathShape, NodeStart, HasAngles,
3709                                                                     Angles, HasRefPoint, RefPoint)
3710         return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3711                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3712                                                       RefPoint)
3713
3714     ## Creates a symmetrical copy of mesh elements
3715     #  @param IDsOfElements list of elements ids
3716     #  @param Mirror is AxisStruct or geom object(point, line, plane)
3717     #  @param theMirrorType is  POINT, AXIS or PLANE
3718     #  If the Mirror is a geom object this parameter is unnecessary
3719     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3720     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3721     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3722     #  @ingroup l2_modif_trsf
3723     def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3724         if IDsOfElements == []:
3725             IDsOfElements = self.GetElementsId()
3726         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3727             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3728         self.mesh.SetParameters(Mirror.parameters)
3729         if Copy and MakeGroups:
3730             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3731         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3732         return []
3733
3734     ## Creates a new mesh by a symmetrical copy of mesh elements
3735     #  @param IDsOfElements the list of elements ids
3736     #  @param Mirror is AxisStruct or geom object (point, line, plane)
3737     #  @param theMirrorType is  POINT, AXIS or PLANE
3738     #  If the Mirror is a geom object this parameter is unnecessary
3739     #  @param MakeGroups to generate new groups from existing ones
3740     #  @param NewMeshName a name of the new mesh to create
3741     #  @return instance of Mesh class
3742     #  @ingroup l2_modif_trsf
3743     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3744         if IDsOfElements == []:
3745             IDsOfElements = self.GetElementsId()
3746         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3747             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3748         self.mesh.SetParameters(Mirror.parameters)
3749         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3750                                           MakeGroups, NewMeshName)
3751         return Mesh(self.smeshpyD,self.geompyD,mesh)
3752
3753     ## Creates a symmetrical copy of the object
3754     #  @param theObject mesh, submesh or group
3755     #  @param Mirror AxisStruct or geom object (point, line, plane)
3756     #  @param theMirrorType is  POINT, AXIS or PLANE
3757     #  If the Mirror is a geom object this parameter is unnecessary
3758     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3759     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3760     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3761     #  @ingroup l2_modif_trsf
3762     def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3763         if ( isinstance( theObject, Mesh )):
3764             theObject = theObject.GetMesh()
3765         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3766             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3767         self.mesh.SetParameters(Mirror.parameters)
3768         if Copy and MakeGroups:
3769             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3770         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3771         return []
3772
3773     ## Creates a new mesh by a symmetrical copy of the object
3774     #  @param theObject mesh, submesh or group
3775     #  @param Mirror AxisStruct or geom object (point, line, plane)
3776     #  @param theMirrorType POINT, AXIS or PLANE
3777     #  If the Mirror is a geom object this parameter is unnecessary
3778     #  @param MakeGroups forces the generation of new groups from existing ones
3779     #  @param NewMeshName the name of the new mesh to create
3780     #  @return instance of Mesh class
3781     #  @ingroup l2_modif_trsf
3782     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3783         if ( isinstance( theObject, Mesh )):
3784             theObject = theObject.GetMesh()
3785         if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3786             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3787         self.mesh.SetParameters(Mirror.parameters)
3788         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3789                                                 MakeGroups, NewMeshName)
3790         return Mesh( self.smeshpyD,self.geompyD,mesh )
3791
3792     ## Translates the elements
3793     #  @param IDsOfElements list of elements ids
3794     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3795     #  @param Copy allows copying the translated elements
3796     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3797     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3798     #  @ingroup l2_modif_trsf
3799     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
3800         if IDsOfElements == []:
3801             IDsOfElements = self.GetElementsId()
3802         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3803             Vector = self.smeshpyD.GetDirStruct(Vector)
3804         if isinstance( Vector, list ):
3805             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3806         self.mesh.SetParameters(Vector.PS.parameters)
3807         if Copy and MakeGroups:
3808             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
3809         self.editor.Translate(IDsOfElements, Vector, Copy)
3810         return []
3811
3812     ## Creates a new mesh of translated elements
3813     #  @param IDsOfElements list of elements ids
3814     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3815     #  @param MakeGroups forces the generation of new groups from existing ones
3816     #  @param NewMeshName the name of the newly created mesh
3817     #  @return instance of Mesh class
3818     #  @ingroup l2_modif_trsf
3819     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
3820         if IDsOfElements == []:
3821             IDsOfElements = self.GetElementsId()
3822         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3823             Vector = self.smeshpyD.GetDirStruct(Vector)
3824         if isinstance( Vector, list ):
3825             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3826         self.mesh.SetParameters(Vector.PS.parameters)
3827         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
3828         return Mesh ( self.smeshpyD, self.geompyD, mesh )
3829
3830     ## Translates the object
3831     #  @param theObject the object to translate (mesh, submesh, or group)
3832     #  @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
3833     #  @param Copy allows copying the translated elements
3834     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3835     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3836     #  @ingroup l2_modif_trsf
3837     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
3838         if ( isinstance( theObject, Mesh )):
3839             theObject = theObject.GetMesh()
3840         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3841             Vector = self.smeshpyD.GetDirStruct(Vector)
3842         if isinstance( Vector, list ):
3843             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3844         self.mesh.SetParameters(Vector.PS.parameters)
3845         if Copy and MakeGroups:
3846             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
3847         self.editor.TranslateObject(theObject, Vector, Copy)
3848         return []
3849
3850     ## Creates a new mesh from the translated object
3851     #  @param theObject the object to translate (mesh, submesh, or group)
3852     #  @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
3853     #  @param MakeGroups forces the generation of new groups from existing ones
3854     #  @param NewMeshName the name of the newly created mesh
3855     #  @return instance of Mesh class
3856     #  @ingroup l2_modif_trsf
3857     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
3858         if isinstance( theObject, Mesh ):
3859             theObject = theObject.GetMesh()
3860         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
3861             Vector = self.smeshpyD.GetDirStruct(Vector)
3862         if isinstance( Vector, list ):
3863             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3864         self.mesh.SetParameters(Vector.PS.parameters)
3865         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
3866         return Mesh( self.smeshpyD, self.geompyD, mesh )
3867
3868
3869
3870     ## Scales the object
3871     #  @param theObject - the object to translate (mesh, submesh, or group)
3872     #  @param thePoint - base point for scale
3873     #  @param theScaleFact - list of 1-3 scale factors for axises
3874     #  @param Copy - allows copying the translated elements
3875     #  @param MakeGroups - forces the generation of new groups from existing
3876     #                      ones (if Copy)
3877     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
3878     #          empty list otherwise
3879     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
3880         if ( isinstance( theObject, Mesh )):
3881             theObject = theObject.GetMesh()
3882         if ( isinstance( theObject, list )):
3883             theObject = self.GetIDSource(theObject, SMESH.ALL)
3884         if ( isinstance( theScaleFact, float )):
3885              theScaleFact = [theScaleFact]
3886         if ( isinstance( theScaleFact, int )):
3887              theScaleFact = [ float(theScaleFact)]
3888
3889         self.mesh.SetParameters(thePoint.parameters)
3890
3891         if Copy and MakeGroups:
3892             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
3893         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
3894         return []
3895
3896     ## Creates a new mesh from the translated object
3897     #  @param theObject - the object to translate (mesh, submesh, or group)
3898     #  @param thePoint - base point for scale
3899     #  @param theScaleFact - list of 1-3 scale factors for axises
3900     #  @param MakeGroups - forces the generation of new groups from existing ones
3901     #  @param NewMeshName - the name of the newly created mesh
3902     #  @return instance of Mesh class
3903     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
3904         if (isinstance(theObject, Mesh)):
3905             theObject = theObject.GetMesh()
3906         if ( isinstance( theObject, list )):
3907             theObject = self.GetIDSource(theObject,SMESH.ALL)
3908         if ( isinstance( theScaleFact, float )):
3909              theScaleFact = [theScaleFact]
3910         if ( isinstance( theScaleFact, int )):
3911              theScaleFact = [ float(theScaleFact)]
3912
3913         self.mesh.SetParameters(thePoint.parameters)
3914         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
3915                                          MakeGroups, NewMeshName)
3916         return Mesh( self.smeshpyD, self.geompyD, mesh )
3917
3918
3919
3920     ## Rotates the elements
3921     #  @param IDsOfElements list of elements ids
3922     #  @param Axis the axis of rotation (AxisStruct or geom line)
3923     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3924     #  @param Copy allows copying the rotated elements
3925     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3926     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3927     #  @ingroup l2_modif_trsf
3928     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
3929         if IDsOfElements == []:
3930             IDsOfElements = self.GetElementsId()
3931         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3932             Axis = self.smeshpyD.GetAxisStruct(Axis)
3933         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3934         Parameters = Axis.parameters + var_separator + Parameters
3935         self.mesh.SetParameters(Parameters)
3936         if Copy and MakeGroups:
3937             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
3938         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
3939         return []
3940
3941     ## Creates a new mesh of rotated elements
3942     #  @param IDsOfElements list of element ids
3943     #  @param Axis the axis of rotation (AxisStruct or geom line)
3944     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3945     #  @param MakeGroups forces the generation of new groups from existing ones
3946     #  @param NewMeshName the name of the newly created mesh
3947     #  @return instance of Mesh class
3948     #  @ingroup l2_modif_trsf
3949     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
3950         if IDsOfElements == []:
3951             IDsOfElements = self.GetElementsId()
3952         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3953             Axis = self.smeshpyD.GetAxisStruct(Axis)
3954         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3955         Parameters = Axis.parameters + var_separator + Parameters
3956         self.mesh.SetParameters(Parameters)
3957         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
3958                                           MakeGroups, NewMeshName)
3959         return Mesh( self.smeshpyD, self.geompyD, mesh )
3960
3961     ## Rotates the object
3962     #  @param theObject the object to rotate( mesh, submesh, or group)
3963     #  @param Axis the axis of rotation (AxisStruct or geom line)
3964     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3965     #  @param Copy allows copying the rotated elements
3966     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3967     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3968     #  @ingroup l2_modif_trsf
3969     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
3970         if (isinstance(theObject, Mesh)):
3971             theObject = theObject.GetMesh()
3972         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3973             Axis = self.smeshpyD.GetAxisStruct(Axis)
3974         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3975         Parameters = Axis.parameters + ":" + Parameters
3976         self.mesh.SetParameters(Parameters)
3977         if Copy and MakeGroups:
3978             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
3979         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
3980         return []
3981
3982     ## Creates a new mesh from the rotated object
3983     #  @param theObject the object to rotate (mesh, submesh, or group)
3984     #  @param Axis the axis of rotation (AxisStruct or geom line)
3985     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
3986     #  @param MakeGroups forces the generation of new groups from existing ones
3987     #  @param NewMeshName the name of the newly created mesh
3988     #  @return instance of Mesh class
3989     #  @ingroup l2_modif_trsf
3990     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
3991         if (isinstance( theObject, Mesh )):
3992             theObject = theObject.GetMesh()
3993         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3994             Axis = self.smeshpyD.GetAxisStruct(Axis)
3995         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3996         Parameters = Axis.parameters + ":" + Parameters
3997         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
3998                                                        MakeGroups, NewMeshName)
3999         self.mesh.SetParameters(Parameters)
4000         return Mesh( self.smeshpyD, self.geompyD, mesh )
4001
4002     ## Finds groups of ajacent nodes within Tolerance.
4003     #  @param Tolerance the value of tolerance
4004     #  @return the list of groups of nodes
4005     #  @ingroup l2_modif_trsf
4006     def FindCoincidentNodes (self, Tolerance):
4007         return self.editor.FindCoincidentNodes(Tolerance)
4008
4009     ## Finds groups of ajacent nodes within Tolerance.
4010     #  @param Tolerance the value of tolerance
4011     #  @param SubMeshOrGroup SubMesh or Group
4012     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4013     #  @return the list of groups of nodes
4014     #  @ingroup l2_modif_trsf
4015     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4016         if (isinstance( SubMeshOrGroup, Mesh )):
4017             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4018         if not isinstance( exceptNodes, list):
4019             exceptNodes = [ exceptNodes ]
4020         if exceptNodes and isinstance( exceptNodes[0], int):
4021             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4022         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4023
4024     ## Merges nodes
4025     #  @param GroupsOfNodes the list of groups of nodes
4026     #  @ingroup l2_modif_trsf
4027     def MergeNodes (self, GroupsOfNodes):
4028         self.editor.MergeNodes(GroupsOfNodes)
4029
4030     ## Finds the elements built on the same nodes.
4031     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4032     #  @return a list of groups of equal elements
4033     #  @ingroup l2_modif_trsf
4034     def FindEqualElements (self, MeshOrSubMeshOrGroup):
4035         if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4036             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4037         return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4038
4039     ## Merges elements in each given group.
4040     #  @param GroupsOfElementsID groups of elements for merging
4041     #  @ingroup l2_modif_trsf
4042     def MergeElements(self, GroupsOfElementsID):
4043         self.editor.MergeElements(GroupsOfElementsID)
4044
4045     ## Leaves one element and removes all other elements built on the same nodes.
4046     #  @ingroup l2_modif_trsf
4047     def MergeEqualElements(self):
4048         self.editor.MergeEqualElements()
4049
4050     ## Sews free borders
4051     #  @return SMESH::Sew_Error
4052     #  @ingroup l2_modif_trsf
4053     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4054                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4055                         CreatePolygons, CreatePolyedrs):
4056         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4057                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4058                                           CreatePolygons, CreatePolyedrs)
4059
4060     ## Sews conform free borders
4061     #  @return SMESH::Sew_Error
4062     #  @ingroup l2_modif_trsf
4063     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4064                                FirstNodeID2, SecondNodeID2):
4065         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4066                                                  FirstNodeID2, SecondNodeID2)
4067
4068     ## Sews border to side
4069     #  @return SMESH::Sew_Error
4070     #  @ingroup l2_modif_trsf
4071     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4072                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4073         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4074                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4075
4076     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4077     #  merged with the nodes of elements of Side2.
4078     #  The number of elements in theSide1 and in theSide2 must be
4079     #  equal and they should have similar nodal connectivity.
4080     #  The nodes to merge should belong to side borders and
4081     #  the first node should be linked to the second.
4082     #  @return SMESH::Sew_Error
4083     #  @ingroup l2_modif_trsf
4084     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4085                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4086                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4087         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4088                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4089                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4090
4091     ## Sets new nodes for the given element.
4092     #  @param ide the element id
4093     #  @param newIDs nodes ids
4094     #  @return If the number of nodes does not correspond to the type of element - returns false
4095     #  @ingroup l2_modif_edit
4096     def ChangeElemNodes(self, ide, newIDs):
4097         return self.editor.ChangeElemNodes(ide, newIDs)
4098
4099     ## If during the last operation of MeshEditor some nodes were
4100     #  created, this method returns the list of their IDs, \n
4101     #  if new nodes were not created - returns empty list
4102     #  @return the list of integer values (can be empty)
4103     #  @ingroup l1_auxiliary
4104     def GetLastCreatedNodes(self):
4105         return self.editor.GetLastCreatedNodes()
4106
4107     ## If during the last operation of MeshEditor some elements were
4108     #  created this method returns the list of their IDs, \n
4109     #  if new elements were not created - returns empty list
4110     #  @return the list of integer values (can be empty)
4111     #  @ingroup l1_auxiliary
4112     def GetLastCreatedElems(self):
4113         return self.editor.GetLastCreatedElems()
4114
4115     ## Clear sequences of nodes and elements created by mesh edition oparations
4116     #  @ingroup l1_auxiliary
4117     def ClearLastCreated(self):
4118         self.editor.ClearLastCreated()
4119
4120      ## Creates a hole in a mesh by doubling the nodes of some particular elements
4121     #  @param theNodes identifiers of nodes to be doubled
4122     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4123     #         nodes. If list of element identifiers is empty then nodes are doubled but
4124     #         they not assigned to elements
4125     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4126     #  @ingroup l2_modif_edit
4127     def DoubleNodes(self, theNodes, theModifiedElems):
4128         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4129
4130     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4131     #  This method provided for convenience works as DoubleNodes() described above.
4132     #  @param theNodeId identifiers of node to be doubled
4133     #  @param theModifiedElems identifiers of elements to be updated
4134     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4135     #  @ingroup l2_modif_edit
4136     def DoubleNode(self, theNodeId, theModifiedElems):
4137         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4138
4139     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4140     #  This method provided for convenience works as DoubleNodes() described above.
4141     #  @param theNodes group of nodes to be doubled
4142     #  @param theModifiedElems group of elements to be updated.
4143     #  @param theMakeGroup forces the generation of a group containing new nodes.
4144     #  @return TRUE or a created group if operation has been completed successfully,
4145     #          FALSE or None otherwise
4146     #  @ingroup l2_modif_edit
4147     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4148         if theMakeGroup:
4149             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4150         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4151
4152     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4153     #  This method provided for convenience works as DoubleNodes() described above.
4154     #  @param theNodes list of groups of nodes to be doubled
4155     #  @param theModifiedElems list of groups of elements to be updated.
4156     #  @param theMakeGroup forces the generation of a group containing new nodes.
4157     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4158     #  @ingroup l2_modif_edit
4159     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4160         if theMakeGroup:
4161             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4162         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4163
4164     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4165     #  @param theElems - the list of elements (edges or faces) to be replicated
4166     #         The nodes for duplication could be found from these elements
4167     #  @param theNodesNot - list of nodes to NOT replicate
4168     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4169     #         replicated nodes should be associated to.
4170     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4171     #  @ingroup l2_modif_edit
4172     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4173         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4174
4175     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4176     #  @param theElems - the list of elements (edges or faces) to be replicated
4177     #         The nodes for duplication could be found from these elements
4178     #  @param theNodesNot - list of nodes to NOT replicate
4179     #  @param theShape - shape to detect affected elements (element which geometric center
4180     #         located on or inside shape).
4181     #         The replicated nodes should be associated to affected elements.
4182     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4183     #  @ingroup l2_modif_edit
4184     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4185         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4186
4187     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4188     #  This method provided for convenience works as DoubleNodes() described above.
4189     #  @param theElems - group of of elements (edges or faces) to be replicated
4190     #  @param theNodesNot - group of nodes not to replicated
4191     #  @param theAffectedElems - group of elements to which the replicated nodes
4192     #         should be associated to.
4193     #  @param theMakeGroup forces the generation of a group containing new elements.
4194     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4195     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4196     #          FALSE or None otherwise
4197     #  @ingroup l2_modif_edit
4198     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4199                              theMakeGroup=False, theMakeNodeGroup=False):
4200         if theMakeGroup or theMakeNodeGroup:
4201             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4202                                                             theAffectedElems,
4203                                                             theMakeGroup, theMakeNodeGroup)
4204             if theMakeGroup and theMakeNodeGroup:
4205                 return twoGroups
4206             else:
4207                 return twoGroups[ int(theMakeNodeGroup) ]
4208         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4209
4210     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4211     #  This method provided for convenience works as DoubleNodes() described above.
4212     #  @param theElems - group of of elements (edges or faces) to be replicated
4213     #  @param theNodesNot - group of nodes not to replicated
4214     #  @param theShape - shape to detect affected elements (element which geometric center
4215     #         located on or inside shape).
4216     #         The replicated nodes should be associated to affected elements.
4217     #  @ingroup l2_modif_edit
4218     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4219         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4220
4221     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4222     #  This method provided for convenience works as DoubleNodes() described above.
4223     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4224     #  @param theNodesNot - list of groups of nodes not to replicated
4225     #  @param theAffectedElems - group of elements to which the replicated nodes
4226     #         should be associated to.
4227     #  @param theMakeGroup forces the generation of a group containing new elements.
4228     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4229     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4230     #          FALSE or None otherwise
4231     #  @ingroup l2_modif_edit
4232     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4233                              theMakeGroup=False, theMakeNodeGroup=False):
4234         if theMakeGroup or theMakeNodeGroup:
4235             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4236                                                              theAffectedElems,
4237                                                              theMakeGroup, theMakeNodeGroup)
4238             if theMakeGroup and theMakeNodeGroup:
4239                 return twoGroups
4240             else:
4241                 return twoGroups[ int(theMakeNodeGroup) ]
4242         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4243
4244     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4245     #  This method provided for convenience works as DoubleNodes() described above.
4246     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4247     #  @param theNodesNot - list of groups of nodes not to replicated
4248     #  @param theShape - shape to detect affected elements (element which geometric center
4249     #         located on or inside shape).
4250     #         The replicated nodes should be associated to affected elements.
4251     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4252     #  @ingroup l2_modif_edit
4253     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4254         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4255
4256     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4257     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4258     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4259     #  @param theNodesNot - list of groups of nodes not to replicated
4260     #  @param theShape - shape to detect affected elements (element which geometric center
4261     #         located on or inside shape).
4262     #         The replicated nodes should be associated to affected elements.
4263     #  @return groups of affected elements
4264     #  @ingroup l2_modif_edit
4265     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4266         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4267
4268     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4269     # The list of groups must describe a partition of the mesh volumes.
4270     # The nodes of the internal faces at the boundaries of the groups are doubled.
4271     # In option, the internal faces are replaced by flat elements.
4272     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4273     # @param theDomains - list of groups of volumes
4274     # @param createJointElems - if TRUE, create the elements
4275     # @return TRUE if operation has been completed successfully, FALSE otherwise
4276     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
4277        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
4278
4279     ## Double nodes on some external faces and create flat elements.
4280     # Flat elements are mainly used by some types of mechanic calculations.
4281     #
4282     # Each group of the list must be constituted of faces.
4283     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4284     # @param theGroupsOfFaces - list of groups of faces
4285     # @return TRUE if operation has been completed successfully, FALSE otherwise
4286     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4287         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4288     
4289     ## identify all the elements around a geom shape, get the faces delimiting the hole
4290     #
4291     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4292         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4293
4294     def _getFunctor(self, funcType ):
4295         fn = self.functors[ funcType._v ]
4296         if not fn:
4297             fn = self.smeshpyD.GetFunctor(funcType)
4298             fn.SetMesh(self.mesh)
4299             self.functors[ funcType._v ] = fn
4300         return fn
4301
4302     def _valueFromFunctor(self, funcType, elemId):
4303         fn = self._getFunctor( funcType )
4304         if fn.GetElementType() == self.GetElementType(elemId, True):
4305             val = fn.GetValue(elemId)
4306         else:
4307             val = 0
4308         return val
4309
4310     ## Get length of 1D element.
4311     #  @param elemId mesh element ID
4312     #  @return element's length value
4313     #  @ingroup l1_measurements
4314     def GetLength(self, elemId):
4315         return self._valueFromFunctor(SMESH.FT_Length, elemId)
4316
4317     ## Get area of 2D element.
4318     #  @param elemId mesh element ID
4319     #  @return element's area value
4320     #  @ingroup l1_measurements
4321     def GetArea(self, elemId):
4322         return self._valueFromFunctor(SMESH.FT_Area, elemId)
4323
4324     ## Get volume of 3D element.
4325     #  @param elemId mesh element ID
4326     #  @return element's volume value
4327     #  @ingroup l1_measurements
4328     def GetVolume(self, elemId):
4329         return self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4330
4331     ## Get maximum element length.
4332     #  @param elemId mesh element ID
4333     #  @return element's maximum length value
4334     #  @ingroup l1_measurements
4335     def GetMaxElementLength(self, elemId):
4336         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4337             ftype = SMESH.FT_MaxElementLength3D
4338         else:
4339             ftype = SMESH.FT_MaxElementLength2D
4340         return self._valueFromFunctor(ftype, elemId)
4341
4342     ## Get aspect ratio of 2D or 3D element.
4343     #  @param elemId mesh element ID
4344     #  @return element's aspect ratio value
4345     #  @ingroup l1_measurements
4346     def GetAspectRatio(self, elemId):
4347         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4348             ftype = SMESH.FT_AspectRatio3D
4349         else:
4350             ftype = SMESH.FT_AspectRatio
4351         return self._valueFromFunctor(ftype, elemId)
4352
4353     ## Get warping angle of 2D element.
4354     #  @param elemId mesh element ID
4355     #  @return element's warping angle value
4356     #  @ingroup l1_measurements
4357     def GetWarping(self, elemId):
4358         return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4359
4360     ## Get minimum angle of 2D element.
4361     #  @param elemId mesh element ID
4362     #  @return element's minimum angle value
4363     #  @ingroup l1_measurements
4364     def GetMinimumAngle(self, elemId):
4365         return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4366
4367     ## Get taper of 2D element.
4368     #  @param elemId mesh element ID
4369     #  @return element's taper value
4370     #  @ingroup l1_measurements
4371     def GetTaper(self, elemId):
4372         return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4373
4374     ## Get skew of 2D element.
4375     #  @param elemId mesh element ID
4376     #  @return element's skew value
4377     #  @ingroup l1_measurements
4378     def GetSkew(self, elemId):
4379         return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4380
4381     pass # end of Mesh class
4382     
4383 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4384 #
4385 class Pattern(SMESH._objref_SMESH_Pattern):
4386
4387     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4388         decrFun = lambda i: i-1
4389         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4390         theMesh.SetParameters(Parameters)
4391         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4392
4393     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4394         decrFun = lambda i: i-1
4395         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4396         theMesh.SetParameters(Parameters)
4397         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4398
4399 # Registering the new proxy for Pattern
4400 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4401
4402 ## Private class used to bind methods creating algorithms to the class Mesh
4403 #
4404 class algoCreator:
4405     def __init__(self):
4406         self.mesh = None
4407         self.defaultAlgoType = ""
4408         self.algoTypeToClass = {}
4409
4410     # Stores a python class of algorithm
4411     def add(self, algoClass):
4412         if type( algoClass ).__name__ == 'classobj' and \
4413            hasattr( algoClass, "algoType"):
4414             self.algoTypeToClass[ algoClass.algoType ] = algoClass
4415             if not self.defaultAlgoType and \
4416                hasattr( algoClass, "isDefault") and algoClass.isDefault:
4417                 self.defaultAlgoType = algoClass.algoType
4418             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4419
4420     # creates a copy of self and assign mesh to the copy
4421     def copy(self, mesh):
4422         other = algoCreator()
4423         other.defaultAlgoType = self.defaultAlgoType
4424         other.algoTypeToClass  = self.algoTypeToClass
4425         other.mesh = mesh
4426         return other
4427
4428     # creates an instance of algorithm
4429     def __call__(self,algo="",geom=0,*args):
4430         algoType = self.defaultAlgoType
4431         for arg in args + (algo,geom):
4432             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4433                 geom = arg
4434             if isinstance( arg, str ) and arg:
4435                 algoType = arg
4436         if not algoType and self.algoTypeToClass:
4437             algoType = self.algoTypeToClass.keys()[0]
4438         if self.algoTypeToClass.has_key( algoType ):
4439             #print "Create algo",algoType
4440             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4441         raise RuntimeError, "No class found for algo type %s" % algoType
4442         return None
4443
4444 # Private class used to substitute and store variable parameters of hypotheses.
4445 #
4446 class hypMethodWrapper:
4447     def __init__(self, hyp, method):
4448         self.hyp    = hyp
4449         self.method = method
4450         #print "REBIND:", method.__name__
4451         return
4452
4453     # call a method of hypothesis with calling SetVarParameter() before
4454     def __call__(self,*args):
4455         if not args:
4456             return self.method( self.hyp, *args ) # hypothesis method with no args
4457
4458         #print "MethWrapper.__call__",self.method.__name__, args
4459         try:
4460             parsed = ParseParameters(*args)     # replace variables with their values
4461             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4462             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4463         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4464             # maybe there is a replaced string arg which is not variable
4465             result = self.method( self.hyp, *args )
4466         except ValueError, detail: # raised by ParseParameters()
4467             try:
4468                 result = self.method( self.hyp, *args )
4469             except omniORB.CORBA.BAD_PARAM:
4470                 raise ValueError, detail # wrong variable name
4471
4472         return result
4473
4474 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4475     #
4476     #print "pluginName: ", pluginName
4477     pluginBuilderName = pluginName + "Builder"
4478     try:
4479         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4480     except Exception, e:
4481         print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4482         continue
4483     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4484     plugin = eval( pluginBuilderName )
4485     #print "  plugin:" , str(plugin)
4486
4487     # add methods creating algorithms to Mesh
4488     for k in dir( plugin ):
4489         if k[0] == '_': continue
4490         algo = getattr( plugin, k )
4491         #print "             algo:", str(algo)
4492         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4493             #print "                     meshMethod:" , str(algo.meshMethod)
4494             if not hasattr( Mesh, algo.meshMethod ):
4495                 setattr( Mesh, algo.meshMethod, algoCreator() )
4496                 pass
4497             getattr( Mesh, algo.meshMethod ).add( algo )
4498             pass
4499         pass
4500     pass
4501 del pluginName