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