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