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