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