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