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