Salome HOME
b0f55e498660c71cfcb4443b44cf7255cf1da657
[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 import omniORB
1050 #Registering the new proxy for SMESH_Gen
1051 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1052
1053 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1054 #  interface to create or load meshes.
1055 #
1056 #  Typical use is:
1057 #  \code
1058 #    import salome
1059 #    salome.salome_init()
1060 #    from salome.smesh import smeshBuilder
1061 #    smesh = smeshBuilder.New(theStudy)
1062 #  \endcode
1063 #  @param  study     SALOME study, generally obtained by salome.myStudy.
1064 #  @param  instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1065 #  @return smeshBuilder instance
1066
1067 def New( study, instance=None):
1068     """
1069     Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1070     interface to create or load meshes.
1071
1072     Typical use is:
1073         import salome
1074         salome.salome_init()
1075         from salome.smesh import smeshBuilder
1076         smesh = smeshBuilder.New(theStudy)
1077
1078     Parameters:
1079         study     SALOME study, generally obtained by salome.myStudy.
1080         instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1081     Returns:
1082         smeshBuilder instance
1083     """
1084     global engine
1085     global smeshInst
1086     global doLcc
1087     engine = instance
1088     if engine is None:
1089       doLcc = True
1090     smeshInst = smeshBuilder()
1091     assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1092     smeshInst.init_smesh(study)
1093     return smeshInst
1094
1095
1096 # Public class: Mesh
1097 # ==================
1098
1099 ## This class allows defining and managing a mesh.
1100 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1101 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1102 #  new nodes and elements and by changing the existing entities), to get information
1103 #  about a mesh and to export a mesh into different formats.
1104 class Mesh:
1105
1106     geom = 0
1107     mesh = 0
1108     editor = 0
1109
1110     ## Constructor
1111     #
1112     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1113     #  sets the GUI name of this mesh to \a name.
1114     #  @param smeshpyD an instance of smeshBuilder class
1115     #  @param geompyD an instance of geomBuilder class
1116     #  @param obj Shape to be meshed or SMESH_Mesh object
1117     #  @param name Study name of the mesh
1118     #  @ingroup l2_construct
1119     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1120         self.smeshpyD=smeshpyD
1121         self.geompyD=geompyD
1122         if obj is None:
1123             obj = 0
1124         objHasName = False
1125         if obj != 0:
1126             if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1127                 self.geom = obj
1128                 objHasName = True
1129                 # publish geom of mesh (issue 0021122)
1130                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1131                     objHasName = False
1132                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1133                     if studyID != geompyD.myStudyId:
1134                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
1135                         pass
1136                     if name:
1137                         geo_name = name + " shape"
1138                     else:
1139                         geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1140                     geompyD.addToStudy( self.geom, geo_name )
1141                 self.mesh = self.smeshpyD.CreateMesh(self.geom)
1142
1143             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1144                 self.SetMesh(obj)
1145         else:
1146             self.mesh = self.smeshpyD.CreateEmptyMesh()
1147         if name:
1148             self.smeshpyD.SetName(self.mesh, name)
1149         elif objHasName:
1150             self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1151
1152         if not self.geom:
1153             self.geom = self.mesh.GetShapeToMesh()
1154
1155         self.editor   = self.mesh.GetMeshEditor()
1156         self.functors = [None] * SMESH.FT_Undefined._v
1157
1158         # set self to algoCreator's
1159         for attrName in dir(self):
1160             attr = getattr( self, attrName )
1161             if isinstance( attr, algoCreator ):
1162                 #print "algoCreator ", attrName
1163                 setattr( self, attrName, attr.copy( self ))
1164
1165     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1166     #  @param theMesh a SMESH_Mesh object
1167     #  @ingroup l2_construct
1168     def SetMesh(self, theMesh):
1169         if self.mesh: self.mesh.UnRegister()
1170         self.mesh = theMesh
1171         if self.mesh:
1172             self.mesh.Register()
1173             self.geom = self.mesh.GetShapeToMesh()
1174
1175     ## Returns the mesh, that is an instance of SMESH_Mesh interface
1176     #  @return a SMESH_Mesh object
1177     #  @ingroup l2_construct
1178     def GetMesh(self):
1179         return self.mesh
1180
1181     ## Gets the name of the mesh
1182     #  @return the name of the mesh as a string
1183     #  @ingroup l2_construct
1184     def GetName(self):
1185         name = GetName(self.GetMesh())
1186         return name
1187
1188     ## Sets a name to the mesh
1189     #  @param name a new name of the mesh
1190     #  @ingroup l2_construct
1191     def SetName(self, name):
1192         self.smeshpyD.SetName(self.GetMesh(), name)
1193
1194     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1195     #  The subMesh object gives access to the IDs of nodes and elements.
1196     #  @param geom a geometrical object (shape)
1197     #  @param name a name for the submesh
1198     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1199     #  @ingroup l2_submeshes
1200     def GetSubMesh(self, geom, name):
1201         AssureGeomPublished( self, geom, name )
1202         submesh = self.mesh.GetSubMesh( geom, name )
1203         return submesh
1204
1205     ## Returns the shape associated to the mesh
1206     #  @return a GEOM_Object
1207     #  @ingroup l2_construct
1208     def GetShape(self):
1209         return self.geom
1210
1211     ## Associates the given shape to the mesh (entails the recreation of the mesh)
1212     #  @param geom the shape to be meshed (GEOM_Object)
1213     #  @ingroup l2_construct
1214     def SetShape(self, geom):
1215         self.mesh = self.smeshpyD.CreateMesh(geom)
1216
1217     ## Loads mesh from the study after opening the study
1218     def Load(self):
1219         self.mesh.Load()
1220
1221     ## Returns true if the hypotheses are defined well
1222     #  @param theSubObject a sub-shape of a mesh shape
1223     #  @return True or False
1224     #  @ingroup l2_construct
1225     def IsReadyToCompute(self, theSubObject):
1226         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1227
1228     ## Returns errors of hypotheses definition.
1229     #  The list of errors is empty if everything is OK.
1230     #  @param theSubObject a sub-shape of a mesh shape
1231     #  @return a list of errors
1232     #  @ingroup l2_construct
1233     def GetAlgoState(self, theSubObject):
1234         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1235
1236     ## Returns a geometrical object on which the given element was built.
1237     #  The returned geometrical object, if not nil, is either found in the
1238     #  study or published by this method with the given name
1239     #  @param theElementID the id of the mesh element
1240     #  @param theGeomName the user-defined name of the geometrical object
1241     #  @return GEOM::GEOM_Object instance
1242     #  @ingroup l2_construct
1243     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1244         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1245
1246     ## Returns the mesh dimension depending on the dimension of the underlying shape
1247     #  or, if the mesh is not based on any shape, basing on deimension of elements
1248     #  @return mesh dimension as an integer value [0,3]
1249     #  @ingroup l1_auxiliary
1250     def MeshDimension(self):
1251         if self.mesh.HasShapeToMesh():
1252             shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1253             if len( shells ) > 0 :
1254                 return 3
1255             elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1256                 return 2
1257             elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1258                 return 1
1259             else:
1260                 return 0;
1261         else:
1262             if self.NbVolumes() > 0: return 3
1263             if self.NbFaces()   > 0: return 2
1264             if self.NbEdges()   > 0: return 1
1265         return 0
1266
1267     ## Evaluates size of prospective mesh on a shape
1268     #  @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1269     #  To know predicted number of e.g. edges, inquire it this way
1270     #  Evaluate()[ EnumToLong( Entity_Edge )]
1271     def Evaluate(self, geom=0):
1272         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1273             if self.geom == 0:
1274                 geom = self.mesh.GetShapeToMesh()
1275             else:
1276                 geom = self.geom
1277         return self.smeshpyD.Evaluate(self.mesh, geom)
1278
1279
1280     ## Computes the mesh and returns the status of the computation
1281     #  @param geom geomtrical shape on which mesh data should be computed
1282     #  @param discardModifs if True and the mesh has been edited since
1283     #         a last total re-compute and that may prevent successful partial re-compute,
1284     #         then the mesh is cleaned before Compute()
1285     #  @return True or False
1286     #  @ingroup l2_construct
1287     def Compute(self, geom=0, discardModifs=False):
1288         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1289             if self.geom == 0:
1290                 geom = self.mesh.GetShapeToMesh()
1291             else:
1292                 geom = self.geom
1293         ok = False
1294         try:
1295             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1296                 self.mesh.Clear()
1297             ok = self.smeshpyD.Compute(self.mesh, geom)
1298         except SALOME.SALOME_Exception, ex:
1299             print "Mesh computation failed, exception caught:"
1300             print "    ", ex.details.text
1301         except:
1302             import traceback
1303             print "Mesh computation failed, exception caught:"
1304             traceback.print_exc()
1305         if True:#not ok:
1306             allReasons = ""
1307
1308             # Treat compute errors
1309             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1310             for err in computeErrors:
1311                 shapeText = ""
1312                 if self.mesh.HasShapeToMesh():
1313                     try:
1314                         mainIOR  = salome.orb.object_to_string(geom)
1315                         for sname in salome.myStudyManager.GetOpenStudies():
1316                             s = salome.myStudyManager.GetStudyByName(sname)
1317                             if not s: continue
1318                             mainSO = s.FindObjectIOR(mainIOR)
1319                             if not mainSO: continue
1320                             if err.subShapeID == 1:
1321                                 shapeText = ' on "%s"' % mainSO.GetName()
1322                             subIt = s.NewChildIterator(mainSO)
1323                             while subIt.More():
1324                                 subSO = subIt.Value()
1325                                 subIt.Next()
1326                                 obj = subSO.GetObject()
1327                                 if not obj: continue
1328                                 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1329                                 if not go: continue
1330                                 ids = go.GetSubShapeIndices()
1331                                 if len(ids) == 1 and ids[0] == err.subShapeID:
1332                                     shapeText = ' on "%s"' % subSO.GetName()
1333                                     break
1334                         if not shapeText:
1335                             shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1336                             if shape:
1337                                 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1338                             else:
1339                                 shapeText = " on subshape #%s" % (err.subShapeID)
1340                     except:
1341                         shapeText = " on subshape #%s" % (err.subShapeID)
1342                 errText = ""
1343                 stdErrors = ["OK",                   #COMPERR_OK
1344                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1345                              "std::exception",       #COMPERR_STD_EXCEPTION
1346                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1347                              "..",                   #COMPERR_SLM_EXCEPTION
1348                              "Unknown exception",    #COMPERR_EXCEPTION
1349                              "Memory allocation problem", #COMPERR_MEMORY_PB
1350                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1351                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1352                              "Warning",              #COMPERR_WARNING
1353                              "Computation cancelled",#COMPERR_CANCELED
1354                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1355                 if err.code > 0:
1356                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1357                 else:
1358                     errText = "code %s" % -err.code
1359                 if errText: errText += ". "
1360                 errText += err.comment
1361                 if allReasons != "":allReasons += "\n"
1362                 if ok:
1363                     allReasons += '-  "%s"%s - %s' %(err.algoName, shapeText, errText)
1364                 else:
1365                     allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1366                 pass
1367
1368             # Treat hyp errors
1369             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1370             for err in errors:
1371                 if err.isGlobalAlgo:
1372                     glob = "global"
1373                 else:
1374                     glob = "local"
1375                     pass
1376                 dim = err.algoDim
1377                 name = err.algoName
1378                 if len(name) == 0:
1379                     reason = '%s %sD algorithm is missing' % (glob, dim)
1380                 elif err.state == HYP_MISSING:
1381                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1382                               % (glob, dim, name, dim))
1383                 elif err.state == HYP_NOTCONFORM:
1384                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1385                 elif err.state == HYP_BAD_PARAMETER:
1386                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1387                               % ( glob, dim, name ))
1388                 elif err.state == HYP_BAD_GEOMETRY:
1389                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1390                               'geometry' % ( glob, dim, name ))
1391                 elif err.state == HYP_HIDDEN_ALGO:
1392                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1393                               'algorithm of upper dimension generating %sD mesh'
1394                               % ( glob, dim, name, glob, dim ))
1395                 else:
1396                     reason = ("For unknown reason. "
1397                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1398                     pass
1399                 if allReasons != "":allReasons += "\n"
1400                 allReasons += "-  " + reason
1401                 pass
1402             if not ok or allReasons != "":
1403                 msg = '"' + GetName(self.mesh) + '"'
1404                 if ok: msg += " has been computed with warnings"
1405                 else:  msg += " has not been computed"
1406                 if allReasons != "": msg += ":"
1407                 else:                msg += "."
1408                 print msg
1409                 print allReasons
1410             pass
1411         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1412             smeshgui = salome.ImportComponentGUI("SMESH")
1413             smeshgui.Init(self.mesh.GetStudyId())
1414             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1415             salome.sg.updateObjBrowser(1)
1416             pass
1417         return ok
1418
1419     ## Return submesh objects list in meshing order
1420     #  @return list of list of submesh objects
1421     #  @ingroup l2_construct
1422     def GetMeshOrder(self):
1423         return self.mesh.GetMeshOrder()
1424
1425     ## Return submesh objects list in meshing order
1426     #  @return list of list of submesh objects
1427     #  @ingroup l2_construct
1428     def SetMeshOrder(self, submeshes):
1429         return self.mesh.SetMeshOrder(submeshes)
1430
1431     ## Removes all nodes and elements
1432     #  @ingroup l2_construct
1433     def Clear(self):
1434         self.mesh.Clear()
1435         if ( salome.sg.hasDesktop() and 
1436              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1437             smeshgui = salome.ImportComponentGUI("SMESH")
1438             smeshgui.Init(self.mesh.GetStudyId())
1439             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1440             salome.sg.updateObjBrowser(1)
1441
1442     ## Removes all nodes and elements of indicated shape
1443     #  @ingroup l2_construct
1444     def ClearSubMesh(self, geomId):
1445         self.mesh.ClearSubMesh(geomId)
1446         if salome.sg.hasDesktop():
1447             smeshgui = salome.ImportComponentGUI("SMESH")
1448             smeshgui.Init(self.mesh.GetStudyId())
1449             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1450             salome.sg.updateObjBrowser(1)
1451
1452     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1453     #  @param fineness [0.0,1.0] defines mesh fineness
1454     #  @return True or False
1455     #  @ingroup l3_algos_basic
1456     def AutomaticTetrahedralization(self, fineness=0):
1457         dim = self.MeshDimension()
1458         # assign hypotheses
1459         self.RemoveGlobalHypotheses()
1460         self.Segment().AutomaticLength(fineness)
1461         if dim > 1 :
1462             self.Triangle().LengthFromEdges()
1463             pass
1464         if dim > 2 :
1465             from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1466             self.Tetrahedron(NETGEN)
1467             pass
1468         return self.Compute()
1469
1470     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1471     #  @param fineness [0.0, 1.0] defines mesh fineness
1472     #  @return True or False
1473     #  @ingroup l3_algos_basic
1474     def AutomaticHexahedralization(self, fineness=0):
1475         dim = self.MeshDimension()
1476         # assign the hypotheses
1477         self.RemoveGlobalHypotheses()
1478         self.Segment().AutomaticLength(fineness)
1479         if dim > 1 :
1480             self.Quadrangle()
1481             pass
1482         if dim > 2 :
1483             self.Hexahedron()
1484             pass
1485         return self.Compute()
1486
1487     ## Assigns a hypothesis
1488     #  @param hyp a hypothesis to assign
1489     #  @param geom a subhape of mesh geometry
1490     #  @return SMESH.Hypothesis_Status
1491     #  @ingroup l2_hypotheses
1492     def AddHypothesis(self, hyp, geom=0):
1493         if isinstance( hyp, Mesh_Algorithm ):
1494             hyp = hyp.GetAlgorithm()
1495             pass
1496         if not geom:
1497             geom = self.geom
1498             if not geom:
1499                 geom = self.mesh.GetShapeToMesh()
1500             pass
1501         AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1502         status = self.mesh.AddHypothesis(geom, hyp)
1503         isAlgo = hyp._narrow( SMESH_Algo )
1504         hyp_name = GetName( hyp )
1505         geom_name = ""
1506         if geom:
1507             geom_name = GetName( geom )
1508         TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1509         return status
1510
1511     ## Return True if an algorithm of hypothesis is assigned to a given shape
1512     #  @param hyp a hypothesis to check
1513     #  @param geom a subhape of mesh geometry
1514     #  @return True of False
1515     #  @ingroup l2_hypotheses
1516     def IsUsedHypothesis(self, hyp, geom):
1517         if not hyp: # or not geom
1518             return False
1519         if isinstance( hyp, Mesh_Algorithm ):
1520             hyp = hyp.GetAlgorithm()
1521             pass
1522         hyps = self.GetHypothesisList(geom)
1523         for h in hyps:
1524             if h.GetId() == hyp.GetId():
1525                 return True
1526         return False
1527
1528     ## Unassigns a hypothesis
1529     #  @param hyp a hypothesis to unassign
1530     #  @param geom a sub-shape of mesh geometry
1531     #  @return SMESH.Hypothesis_Status
1532     #  @ingroup l2_hypotheses
1533     def RemoveHypothesis(self, hyp, geom=0):
1534         if not hyp:
1535             return None
1536         if isinstance( hyp, Mesh_Algorithm ):
1537             hyp = hyp.GetAlgorithm()
1538             pass
1539         shape = geom
1540         if not shape:
1541             shape = self.geom
1542             pass
1543         if self.IsUsedHypothesis( hyp, shape ):
1544             return self.mesh.RemoveHypothesis( shape, hyp )
1545         hypName = GetName( hyp )
1546         geoName = GetName( shape )
1547         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1548         return None
1549
1550     ## Gets the list of hypotheses added on a geometry
1551     #  @param geom a sub-shape of mesh geometry
1552     #  @return the sequence of SMESH_Hypothesis
1553     #  @ingroup l2_hypotheses
1554     def GetHypothesisList(self, geom):
1555         return self.mesh.GetHypothesisList( geom )
1556
1557     ## Removes all global hypotheses
1558     #  @ingroup l2_hypotheses
1559     def RemoveGlobalHypotheses(self):
1560         current_hyps = self.mesh.GetHypothesisList( self.geom )
1561         for hyp in current_hyps:
1562             self.mesh.RemoveHypothesis( self.geom, hyp )
1563             pass
1564         pass
1565
1566    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1567     ## allowing to overwrite the file if it exists or add the exported data to its contents
1568     #  @param f is the file name
1569     #  @param auto_groups boolean parameter for creating/not creating
1570     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1571     #  the typical use is auto_groups=false.
1572     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1573     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1574     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1575     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1576     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1577     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1578     #         - 3D in the rest cases.
1579     #
1580     #         If @a autoDimension is @c False, the space dimension is always 3.
1581     #  @ingroup l2_impexp
1582     def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1583                   overwrite=1, meshPart=None, autoDimension=True):
1584         if meshPart:
1585             unRegister = genObjUnRegister()
1586             if isinstance( meshPart, list ):
1587                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1588                 unRegister.set( meshPart )
1589             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension)
1590         else:
1591             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1592
1593     ## Exports the mesh in a file in SAUV format
1594     #  @param f is the file name
1595     #  @param auto_groups boolean parameter for creating/not creating
1596     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1597     #  the typical use is auto_groups=false.
1598     #  @ingroup l2_impexp
1599     def ExportSAUV(self, f, auto_groups=0):
1600         self.mesh.ExportSAUV(f, auto_groups)
1601
1602     ## Exports the mesh in a file in DAT format
1603     #  @param f the file name
1604     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1605     #  @ingroup l2_impexp
1606     def ExportDAT(self, f, meshPart=None):
1607         if meshPart:
1608             unRegister = genObjUnRegister()
1609             if isinstance( meshPart, list ):
1610                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1611                 unRegister.set( meshPart )
1612             self.mesh.ExportPartToDAT( meshPart, f )
1613         else:
1614             self.mesh.ExportDAT(f)
1615
1616     ## Exports the mesh in a file in UNV format
1617     #  @param f the file name
1618     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1619     #  @ingroup l2_impexp
1620     def ExportUNV(self, f, meshPart=None):
1621         if meshPart:
1622             unRegister = genObjUnRegister()
1623             if isinstance( meshPart, list ):
1624                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1625                 unRegister.set( meshPart )
1626             self.mesh.ExportPartToUNV( meshPart, f )
1627         else:
1628             self.mesh.ExportUNV(f)
1629
1630     ## Export the mesh in a file in STL format
1631     #  @param f the file name
1632     #  @param ascii defines the file encoding
1633     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1634     #  @ingroup l2_impexp
1635     def ExportSTL(self, f, ascii=1, meshPart=None):
1636         if meshPart:
1637             unRegister = genObjUnRegister()
1638             if isinstance( meshPart, list ):
1639                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1640                 unRegister.set( meshPart )
1641             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1642         else:
1643             self.mesh.ExportSTL(f, ascii)
1644
1645     ## Exports the mesh in a file in CGNS format
1646     #  @param f is the file name
1647     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1648     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1649     #  @ingroup l2_impexp
1650     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1651         unRegister = genObjUnRegister()
1652         if isinstance( meshPart, list ):
1653             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1654             unRegister.set( meshPart )
1655         if isinstance( meshPart, Mesh ):
1656             meshPart = meshPart.mesh
1657         elif not meshPart:
1658             meshPart = self.mesh
1659         self.mesh.ExportCGNS(meshPart, f, overwrite)
1660
1661     ## Exports the mesh in a file in GMF format.
1662     #  GMF files must have .mesh extension for the ASCII format and .meshb for
1663     #  the bynary format. Other extensions are not allowed.
1664     #  @param f is the file name
1665     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1666     #  @ingroup l2_impexp
1667     def ExportGMF(self, f, meshPart=None):
1668         unRegister = genObjUnRegister()
1669         if isinstance( meshPart, list ):
1670             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1671             unRegister.set( meshPart )
1672         if isinstance( meshPart, Mesh ):
1673             meshPart = meshPart.mesh
1674         elif not meshPart:
1675             meshPart = self.mesh
1676         self.mesh.ExportGMF(meshPart, f, True)
1677
1678     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1679     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1680     ## allowing to overwrite the file if it exists or add the exported data to its contents
1681     #  @param f the file name
1682     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1683     #  @param opt boolean parameter for creating/not creating
1684     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1685     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1686     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1687     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1688     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1689     #         - 3D in the rest cases.
1690     #
1691     #         If @a autoDimension is @c False, the space dimension is always 3.
1692     #  @ingroup l2_impexp
1693     def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1694         self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1695
1696     # Operations with groups:
1697     # ----------------------
1698
1699     ## Creates an empty mesh group
1700     #  @param elementType the type of elements in the group
1701     #  @param name the name of the mesh group
1702     #  @return SMESH_Group
1703     #  @ingroup l2_grps_create
1704     def CreateEmptyGroup(self, elementType, name):
1705         return self.mesh.CreateGroup(elementType, name)
1706
1707     ## Creates a mesh group based on the geometric object \a grp
1708     #  and gives a \a name, \n if this parameter is not defined
1709     #  the name is the same as the geometric group name \n
1710     #  Note: Works like GroupOnGeom().
1711     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1712     #  @param name the name of the mesh group
1713     #  @return SMESH_GroupOnGeom
1714     #  @ingroup l2_grps_create
1715     def Group(self, grp, name=""):
1716         return self.GroupOnGeom(grp, name)
1717
1718     ## Creates a mesh group based on the geometrical object \a grp
1719     #  and gives a \a name, \n if this parameter is not defined
1720     #  the name is the same as the geometrical group name
1721     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1722     #  @param name the name of the mesh group
1723     #  @param typ  the type of elements in the group. If not set, it is
1724     #              automatically detected by the type of the geometry
1725     #  @return SMESH_GroupOnGeom
1726     #  @ingroup l2_grps_create
1727     def GroupOnGeom(self, grp, name="", typ=None):
1728         AssureGeomPublished( self, grp, name )
1729         if name == "":
1730             name = grp.GetName()
1731         if not typ:
1732             typ = self._groupTypeFromShape( grp )
1733         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1734
1735     ## Pivate method to get a type of group on geometry
1736     def _groupTypeFromShape( self, shape ):
1737         tgeo = str(shape.GetShapeType())
1738         if tgeo == "VERTEX":
1739             typ = NODE
1740         elif tgeo == "EDGE":
1741             typ = EDGE
1742         elif tgeo == "FACE" or tgeo == "SHELL":
1743             typ = FACE
1744         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1745             typ = VOLUME
1746         elif tgeo == "COMPOUND":
1747             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1748             if not sub:
1749                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1750             return self._groupTypeFromShape( sub[0] )
1751         else:
1752             raise ValueError, \
1753                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1754         return typ
1755
1756     ## Creates a mesh group with given \a name based on the \a filter which
1757     ## is a special type of group dynamically updating it's contents during
1758     ## mesh modification
1759     #  @param typ  the type of elements in the group
1760     #  @param name the name of the mesh group
1761     #  @param filter the filter defining group contents
1762     #  @return SMESH_GroupOnFilter
1763     #  @ingroup l2_grps_create
1764     def GroupOnFilter(self, typ, name, filter):
1765         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1766
1767     ## Creates a mesh group by the given ids of elements
1768     #  @param groupName the name of the mesh group
1769     #  @param elementType the type of elements in the group
1770     #  @param elemIDs the list of ids
1771     #  @return SMESH_Group
1772     #  @ingroup l2_grps_create
1773     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1774         group = self.mesh.CreateGroup(elementType, groupName)
1775         group.Add(elemIDs)
1776         return group
1777
1778     ## Creates a mesh group by the given conditions
1779     #  @param groupName the name of the mesh group
1780     #  @param elementType the type of elements in the group
1781     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1782     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1783     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
1784     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
1785     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1786     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
1787     #  @return SMESH_Group
1788     #  @ingroup l2_grps_create
1789     def MakeGroup(self,
1790                   groupName,
1791                   elementType,
1792                   CritType=FT_Undefined,
1793                   Compare=FT_EqualTo,
1794                   Threshold="",
1795                   UnaryOp=FT_Undefined,
1796                   Tolerance=1e-07):
1797         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1798         group = self.MakeGroupByCriterion(groupName, aCriterion)
1799         return group
1800
1801     ## Creates a mesh group by the given criterion
1802     #  @param groupName the name of the mesh group
1803     #  @param Criterion the instance of Criterion class
1804     #  @return SMESH_Group
1805     #  @ingroup l2_grps_create
1806     def MakeGroupByCriterion(self, groupName, Criterion):
1807         aFilterMgr = self.smeshpyD.CreateFilterManager()
1808         aFilter = aFilterMgr.CreateFilter()
1809         aCriteria = []
1810         aCriteria.append(Criterion)
1811         aFilter.SetCriteria(aCriteria)
1812         group = self.MakeGroupByFilter(groupName, aFilter)
1813         aFilterMgr.UnRegister()
1814         return group
1815
1816     ## Creates a mesh group by the given criteria (list of criteria)
1817     #  @param groupName the name of the mesh group
1818     #  @param theCriteria the list of criteria
1819     #  @return SMESH_Group
1820     #  @ingroup l2_grps_create
1821     def MakeGroupByCriteria(self, groupName, theCriteria):
1822         aFilterMgr = self.smeshpyD.CreateFilterManager()
1823         aFilter = aFilterMgr.CreateFilter()
1824         aFilter.SetCriteria(theCriteria)
1825         group = self.MakeGroupByFilter(groupName, aFilter)
1826         aFilterMgr.UnRegister()
1827         return group
1828
1829     ## Creates a mesh group by the given filter
1830     #  @param groupName the name of the mesh group
1831     #  @param theFilter the instance of Filter class
1832     #  @return SMESH_Group
1833     #  @ingroup l2_grps_create
1834     def MakeGroupByFilter(self, groupName, theFilter):
1835         group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1836         theFilter.SetMesh( self.mesh )
1837         group.AddFrom( theFilter )
1838         return group
1839
1840     ## Removes a group
1841     #  @ingroup l2_grps_delete
1842     def RemoveGroup(self, group):
1843         self.mesh.RemoveGroup(group)
1844
1845     ## Removes a group with its contents
1846     #  @ingroup l2_grps_delete
1847     def RemoveGroupWithContents(self, group):
1848         self.mesh.RemoveGroupWithContents(group)
1849
1850     ## Gets the list of groups existing in the mesh
1851     #  @return a sequence of SMESH_GroupBase
1852     #  @ingroup l2_grps_create
1853     def GetGroups(self):
1854         return self.mesh.GetGroups()
1855
1856     ## Gets the number of groups existing in the mesh
1857     #  @return the quantity of groups as an integer value
1858     #  @ingroup l2_grps_create
1859     def NbGroups(self):
1860         return self.mesh.NbGroups()
1861
1862     ## Gets the list of names of groups existing in the mesh
1863     #  @return list of strings
1864     #  @ingroup l2_grps_create
1865     def GetGroupNames(self):
1866         groups = self.GetGroups()
1867         names = []
1868         for group in groups:
1869             names.append(group.GetName())
1870         return names
1871
1872     ## Produces a union of two groups
1873     #  A new group is created. All mesh elements that are
1874     #  present in the initial groups are added to the new one
1875     #  @return an instance of SMESH_Group
1876     #  @ingroup l2_grps_operon
1877     def UnionGroups(self, group1, group2, name):
1878         return self.mesh.UnionGroups(group1, group2, name)
1879
1880     ## Produces a union list of groups
1881     #  New group is created. All mesh elements that are present in
1882     #  initial groups are added to the new one
1883     #  @return an instance of SMESH_Group
1884     #  @ingroup l2_grps_operon
1885     def UnionListOfGroups(self, groups, name):
1886       return self.mesh.UnionListOfGroups(groups, name)
1887
1888     ## Prodices an intersection of two groups
1889     #  A new group is created. All mesh elements that are common
1890     #  for the two initial groups are added to the new one.
1891     #  @return an instance of SMESH_Group
1892     #  @ingroup l2_grps_operon
1893     def IntersectGroups(self, group1, group2, name):
1894         return self.mesh.IntersectGroups(group1, group2, name)
1895
1896     ## Produces an intersection of groups
1897     #  New group is created. All mesh elements that are present in all
1898     #  initial groups simultaneously are added to the new one
1899     #  @return an instance of SMESH_Group
1900     #  @ingroup l2_grps_operon
1901     def IntersectListOfGroups(self, groups, name):
1902       return self.mesh.IntersectListOfGroups(groups, name)
1903
1904     ## Produces a cut of two groups
1905     #  A new group is created. All mesh elements that are present in
1906     #  the main group but are not present in the tool group are added to the new one
1907     #  @return an instance of SMESH_Group
1908     #  @ingroup l2_grps_operon
1909     def CutGroups(self, main_group, tool_group, name):
1910         return self.mesh.CutGroups(main_group, tool_group, name)
1911
1912     ## Produces a cut of groups
1913     #  A new group is created. All mesh elements that are present in main groups
1914     #  but do not present in tool groups are added to the new one
1915     #  @return an instance of SMESH_Group
1916     #  @ingroup l2_grps_operon
1917     def CutListOfGroups(self, main_groups, tool_groups, name):
1918       return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1919
1920     ## Produces a group of elements of specified type using list of existing groups
1921     #  A new group is created. System
1922     #  1) extracts all nodes on which groups elements are built
1923     #  2) combines all elements of specified dimension laying on these nodes
1924     #  @return an instance of SMESH_Group
1925     #  @ingroup l2_grps_operon
1926     def CreateDimGroup(self, groups, elem_type, name):
1927       return self.mesh.CreateDimGroup(groups, elem_type, name)
1928
1929
1930     ## Convert group on geom into standalone group
1931     #  @ingroup l2_grps_delete
1932     def ConvertToStandalone(self, group):
1933         return self.mesh.ConvertToStandalone(group)
1934
1935     # Get some info about mesh:
1936     # ------------------------
1937
1938     ## Returns the log of nodes and elements added or removed
1939     #  since the previous clear of the log.
1940     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
1941     #  @return list of log_block structures:
1942     #                                        commandType
1943     #                                        number
1944     #                                        coords
1945     #                                        indexes
1946     #  @ingroup l1_auxiliary
1947     def GetLog(self, clearAfterGet):
1948         return self.mesh.GetLog(clearAfterGet)
1949
1950     ## Clears the log of nodes and elements added or removed since the previous
1951     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
1952     #  @ingroup l1_auxiliary
1953     def ClearLog(self):
1954         self.mesh.ClearLog()
1955
1956     ## Toggles auto color mode on the object.
1957     #  @param theAutoColor the flag which toggles auto color mode.
1958     #  @ingroup l1_auxiliary
1959     def SetAutoColor(self, theAutoColor):
1960         self.mesh.SetAutoColor(theAutoColor)
1961
1962     ## Gets flag of object auto color mode.
1963     #  @return True or False
1964     #  @ingroup l1_auxiliary
1965     def GetAutoColor(self):
1966         return self.mesh.GetAutoColor()
1967
1968     ## Gets the internal ID
1969     #  @return integer value, which is the internal Id of the mesh
1970     #  @ingroup l1_auxiliary
1971     def GetId(self):
1972         return self.mesh.GetId()
1973
1974     ## Get the study Id
1975     #  @return integer value, which is the study Id of the mesh
1976     #  @ingroup l1_auxiliary
1977     def GetStudyId(self):
1978         return self.mesh.GetStudyId()
1979
1980     ## Checks the group names for duplications.
1981     #  Consider the maximum group name length stored in MED file.
1982     #  @return True or False
1983     #  @ingroup l1_auxiliary
1984     def HasDuplicatedGroupNamesMED(self):
1985         return self.mesh.HasDuplicatedGroupNamesMED()
1986
1987     ## Obtains the mesh editor tool
1988     #  @return an instance of SMESH_MeshEditor
1989     #  @ingroup l1_modifying
1990     def GetMeshEditor(self):
1991         return self.editor
1992
1993     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
1994     #  can be passed as argument to a method accepting mesh, group or sub-mesh
1995     #  @return an instance of SMESH_IDSource
1996     #  @ingroup l1_auxiliary
1997     def GetIDSource(self, ids, elemType):
1998         return self.editor.MakeIDSource(ids, elemType)
1999
2000
2001     # Get informations about mesh contents:
2002     # ------------------------------------
2003
2004     ## Gets the mesh stattistic
2005     #  @return dictionary type element - count of elements
2006     #  @ingroup l1_meshinfo
2007     def GetMeshInfo(self, obj = None):
2008         if not obj: obj = self.mesh
2009         return self.smeshpyD.GetMeshInfo(obj)
2010
2011     ## Returns the number of nodes in the mesh
2012     #  @return an integer value
2013     #  @ingroup l1_meshinfo
2014     def NbNodes(self):
2015         return self.mesh.NbNodes()
2016
2017     ## Returns the number of elements in the mesh
2018     #  @return an integer value
2019     #  @ingroup l1_meshinfo
2020     def NbElements(self):
2021         return self.mesh.NbElements()
2022
2023     ## Returns the number of 0d elements in the mesh
2024     #  @return an integer value
2025     #  @ingroup l1_meshinfo
2026     def Nb0DElements(self):
2027         return self.mesh.Nb0DElements()
2028
2029     ## Returns the number of ball discrete elements in the mesh
2030     #  @return an integer value
2031     #  @ingroup l1_meshinfo
2032     def NbBalls(self):
2033         return self.mesh.NbBalls()
2034
2035     ## Returns the number of edges in the mesh
2036     #  @return an integer value
2037     #  @ingroup l1_meshinfo
2038     def NbEdges(self):
2039         return self.mesh.NbEdges()
2040
2041     ## Returns the number of edges with the given order in the mesh
2042     #  @param elementOrder the order of elements:
2043     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2044     #  @return an integer value
2045     #  @ingroup l1_meshinfo
2046     def NbEdgesOfOrder(self, elementOrder):
2047         return self.mesh.NbEdgesOfOrder(elementOrder)
2048
2049     ## Returns the number of faces in the mesh
2050     #  @return an integer value
2051     #  @ingroup l1_meshinfo
2052     def NbFaces(self):
2053         return self.mesh.NbFaces()
2054
2055     ## Returns the number of faces with the given order in the mesh
2056     #  @param elementOrder the order of elements:
2057     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2058     #  @return an integer value
2059     #  @ingroup l1_meshinfo
2060     def NbFacesOfOrder(self, elementOrder):
2061         return self.mesh.NbFacesOfOrder(elementOrder)
2062
2063     ## Returns the number of triangles in the mesh
2064     #  @return an integer value
2065     #  @ingroup l1_meshinfo
2066     def NbTriangles(self):
2067         return self.mesh.NbTriangles()
2068
2069     ## Returns the number of triangles with the given order in the mesh
2070     #  @param elementOrder is the order of elements:
2071     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2072     #  @return an integer value
2073     #  @ingroup l1_meshinfo
2074     def NbTrianglesOfOrder(self, elementOrder):
2075         return self.mesh.NbTrianglesOfOrder(elementOrder)
2076
2077     ## Returns the number of biquadratic triangles in the mesh
2078     #  @return an integer value
2079     #  @ingroup l1_meshinfo
2080     def NbBiQuadTriangles(self):
2081         return self.mesh.NbBiQuadTriangles()
2082
2083     ## Returns the number of quadrangles in the mesh
2084     #  @return an integer value
2085     #  @ingroup l1_meshinfo
2086     def NbQuadrangles(self):
2087         return self.mesh.NbQuadrangles()
2088
2089     ## Returns the number of quadrangles with the given order in the mesh
2090     #  @param elementOrder the order of elements:
2091     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2092     #  @return an integer value
2093     #  @ingroup l1_meshinfo
2094     def NbQuadranglesOfOrder(self, elementOrder):
2095         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2096
2097     ## Returns the number of biquadratic quadrangles in the mesh
2098     #  @return an integer value
2099     #  @ingroup l1_meshinfo
2100     def NbBiQuadQuadrangles(self):
2101         return self.mesh.NbBiQuadQuadrangles()
2102
2103     ## Returns the number of polygons in the mesh
2104     #  @return an integer value
2105     #  @ingroup l1_meshinfo
2106     def NbPolygons(self):
2107         return self.mesh.NbPolygons()
2108
2109     ## Returns the number of volumes in the mesh
2110     #  @return an integer value
2111     #  @ingroup l1_meshinfo
2112     def NbVolumes(self):
2113         return self.mesh.NbVolumes()
2114
2115     ## Returns the number of volumes with the given order in the mesh
2116     #  @param elementOrder  the order of elements:
2117     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2118     #  @return an integer value
2119     #  @ingroup l1_meshinfo
2120     def NbVolumesOfOrder(self, elementOrder):
2121         return self.mesh.NbVolumesOfOrder(elementOrder)
2122
2123     ## Returns the number of tetrahedrons in the mesh
2124     #  @return an integer value
2125     #  @ingroup l1_meshinfo
2126     def NbTetras(self):
2127         return self.mesh.NbTetras()
2128
2129     ## Returns the number of tetrahedrons with the given order in the mesh
2130     #  @param elementOrder  the order of elements:
2131     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2132     #  @return an integer value
2133     #  @ingroup l1_meshinfo
2134     def NbTetrasOfOrder(self, elementOrder):
2135         return self.mesh.NbTetrasOfOrder(elementOrder)
2136
2137     ## Returns the number of hexahedrons in the mesh
2138     #  @return an integer value
2139     #  @ingroup l1_meshinfo
2140     def NbHexas(self):
2141         return self.mesh.NbHexas()
2142
2143     ## Returns the number of hexahedrons with the given order in the mesh
2144     #  @param elementOrder  the order of elements:
2145     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2146     #  @return an integer value
2147     #  @ingroup l1_meshinfo
2148     def NbHexasOfOrder(self, elementOrder):
2149         return self.mesh.NbHexasOfOrder(elementOrder)
2150
2151     ## Returns the number of triquadratic hexahedrons in the mesh
2152     #  @return an integer value
2153     #  @ingroup l1_meshinfo
2154     def NbTriQuadraticHexas(self):
2155         return self.mesh.NbTriQuadraticHexas()
2156
2157     ## Returns the number of pyramids in the mesh
2158     #  @return an integer value
2159     #  @ingroup l1_meshinfo
2160     def NbPyramids(self):
2161         return self.mesh.NbPyramids()
2162
2163     ## Returns the number of pyramids with the given order in the mesh
2164     #  @param elementOrder  the order of elements:
2165     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2166     #  @return an integer value
2167     #  @ingroup l1_meshinfo
2168     def NbPyramidsOfOrder(self, elementOrder):
2169         return self.mesh.NbPyramidsOfOrder(elementOrder)
2170
2171     ## Returns the number of prisms in the mesh
2172     #  @return an integer value
2173     #  @ingroup l1_meshinfo
2174     def NbPrisms(self):
2175         return self.mesh.NbPrisms()
2176
2177     ## Returns the number of prisms with the given order in the mesh
2178     #  @param elementOrder  the order of elements:
2179     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2180     #  @return an integer value
2181     #  @ingroup l1_meshinfo
2182     def NbPrismsOfOrder(self, elementOrder):
2183         return self.mesh.NbPrismsOfOrder(elementOrder)
2184
2185     ## Returns the number of hexagonal prisms in the mesh
2186     #  @return an integer value
2187     #  @ingroup l1_meshinfo
2188     def NbHexagonalPrisms(self):
2189         return self.mesh.NbHexagonalPrisms()
2190
2191     ## Returns the number of polyhedrons in the mesh
2192     #  @return an integer value
2193     #  @ingroup l1_meshinfo
2194     def NbPolyhedrons(self):
2195         return self.mesh.NbPolyhedrons()
2196
2197     ## Returns the number of submeshes in the mesh
2198     #  @return an integer value
2199     #  @ingroup l1_meshinfo
2200     def NbSubMesh(self):
2201         return self.mesh.NbSubMesh()
2202
2203     ## Returns the list of mesh elements IDs
2204     #  @return the list of integer values
2205     #  @ingroup l1_meshinfo
2206     def GetElementsId(self):
2207         return self.mesh.GetElementsId()
2208
2209     ## Returns the list of IDs of mesh elements with the given type
2210     #  @param elementType  the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2211     #  @return list of integer values
2212     #  @ingroup l1_meshinfo
2213     def GetElementsByType(self, elementType):
2214         return self.mesh.GetElementsByType(elementType)
2215
2216     ## Returns the list of mesh nodes IDs
2217     #  @return the list of integer values
2218     #  @ingroup l1_meshinfo
2219     def GetNodesId(self):
2220         return self.mesh.GetNodesId()
2221
2222     # Get the information about mesh elements:
2223     # ------------------------------------
2224
2225     ## Returns the type of mesh element
2226     #  @return the value from SMESH::ElementType enumeration
2227     #  @ingroup l1_meshinfo
2228     def GetElementType(self, id, iselem):
2229         return self.mesh.GetElementType(id, iselem)
2230
2231     ## Returns the geometric type of mesh element
2232     #  @return the value from SMESH::EntityType enumeration
2233     #  @ingroup l1_meshinfo
2234     def GetElementGeomType(self, id):
2235         return self.mesh.GetElementGeomType(id)
2236
2237     ## Returns the list of submesh elements IDs
2238     #  @param Shape a geom object(sub-shape) IOR
2239     #         Shape must be the sub-shape of a ShapeToMesh()
2240     #  @return the list of integer values
2241     #  @ingroup l1_meshinfo
2242     def GetSubMeshElementsId(self, Shape):
2243         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2244             ShapeID = Shape.GetSubShapeIndices()[0]
2245         else:
2246             ShapeID = Shape
2247         return self.mesh.GetSubMeshElementsId(ShapeID)
2248
2249     ## Returns the list of submesh nodes IDs
2250     #  @param Shape a geom object(sub-shape) IOR
2251     #         Shape must be the sub-shape of a ShapeToMesh()
2252     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2253     #  @return the list of integer values
2254     #  @ingroup l1_meshinfo
2255     def GetSubMeshNodesId(self, Shape, all):
2256         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2257             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2258         else:
2259             ShapeID = Shape
2260         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2261
2262     ## Returns type of elements on given shape
2263     #  @param Shape a geom object(sub-shape) IOR
2264     #         Shape must be a sub-shape of a ShapeToMesh()
2265     #  @return element type
2266     #  @ingroup l1_meshinfo
2267     def GetSubMeshElementType(self, Shape):
2268         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2269             ShapeID = Shape.GetSubShapeIndices()[0]
2270         else:
2271             ShapeID = Shape
2272         return self.mesh.GetSubMeshElementType(ShapeID)
2273
2274     ## Gets the mesh description
2275     #  @return string value
2276     #  @ingroup l1_meshinfo
2277     def Dump(self):
2278         return self.mesh.Dump()
2279
2280
2281     # Get the information about nodes and elements of a mesh by its IDs:
2282     # -----------------------------------------------------------
2283
2284     ## Gets XYZ coordinates of a node
2285     #  \n If there is no nodes for the given ID - returns an empty list
2286     #  @return a list of double precision values
2287     #  @ingroup l1_meshinfo
2288     def GetNodeXYZ(self, id):
2289         return self.mesh.GetNodeXYZ(id)
2290
2291     ## Returns list of IDs of inverse elements for the given node
2292     #  \n If there is no node for the given ID - returns an empty list
2293     #  @return a list of integer values
2294     #  @ingroup l1_meshinfo
2295     def GetNodeInverseElements(self, id):
2296         return self.mesh.GetNodeInverseElements(id)
2297
2298     ## @brief Returns the position of a node on the shape
2299     #  @return SMESH::NodePosition
2300     #  @ingroup l1_meshinfo
2301     def GetNodePosition(self,NodeID):
2302         return self.mesh.GetNodePosition(NodeID)
2303
2304     ## @brief Returns the position of an element on the shape
2305     #  @return SMESH::ElementPosition
2306     #  @ingroup l1_meshinfo
2307     def GetElementPosition(self,ElemID):
2308         return self.mesh.GetElementPosition(ElemID)
2309
2310     ## If the given element is a node, returns the ID of shape
2311     #  \n If there is no node for the given ID - returns -1
2312     #  @return an integer value
2313     #  @ingroup l1_meshinfo
2314     def GetShapeID(self, id):
2315         return self.mesh.GetShapeID(id)
2316
2317     ## Returns the ID of the result shape after
2318     #  FindShape() from SMESH_MeshEditor for the given element
2319     #  \n If there is no element for the given ID - returns -1
2320     #  @return an integer value
2321     #  @ingroup l1_meshinfo
2322     def GetShapeIDForElem(self,id):
2323         return self.mesh.GetShapeIDForElem(id)
2324
2325     ## Returns the number of nodes for the given element
2326     #  \n If there is no element for the given ID - returns -1
2327     #  @return an integer value
2328     #  @ingroup l1_meshinfo
2329     def GetElemNbNodes(self, id):
2330         return self.mesh.GetElemNbNodes(id)
2331
2332     ## Returns the node ID the given (zero based) index for the given element
2333     #  \n If there is no element for the given ID - returns -1
2334     #  \n If there is no node for the given index - returns -2
2335     #  @return an integer value
2336     #  @ingroup l1_meshinfo
2337     def GetElemNode(self, id, index):
2338         return self.mesh.GetElemNode(id, index)
2339
2340     ## Returns the IDs of nodes of the given element
2341     #  @return a list of integer values
2342     #  @ingroup l1_meshinfo
2343     def GetElemNodes(self, id):
2344         return self.mesh.GetElemNodes(id)
2345
2346     ## Returns true if the given node is the medium node in the given quadratic element
2347     #  @ingroup l1_meshinfo
2348     def IsMediumNode(self, elementID, nodeID):
2349         return self.mesh.IsMediumNode(elementID, nodeID)
2350
2351     ## Returns true if the given node is the medium node in one of quadratic elements
2352     #  @ingroup l1_meshinfo
2353     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2354         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2355
2356     ## Returns the number of edges for the given element
2357     #  @ingroup l1_meshinfo
2358     def ElemNbEdges(self, id):
2359         return self.mesh.ElemNbEdges(id)
2360
2361     ## Returns the number of faces for the given element
2362     #  @ingroup l1_meshinfo
2363     def ElemNbFaces(self, id):
2364         return self.mesh.ElemNbFaces(id)
2365
2366     ## Returns nodes of given face (counted from zero) for given volumic element.
2367     #  @ingroup l1_meshinfo
2368     def GetElemFaceNodes(self,elemId, faceIndex):
2369         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2370
2371     ## Returns an element based on all given nodes.
2372     #  @ingroup l1_meshinfo
2373     def FindElementByNodes(self,nodes):
2374         return self.mesh.FindElementByNodes(nodes)
2375
2376     ## Returns true if the given element is a polygon
2377     #  @ingroup l1_meshinfo
2378     def IsPoly(self, id):
2379         return self.mesh.IsPoly(id)
2380
2381     ## Returns true if the given element is quadratic
2382     #  @ingroup l1_meshinfo
2383     def IsQuadratic(self, id):
2384         return self.mesh.IsQuadratic(id)
2385
2386     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2387     #  @ingroup l1_meshinfo
2388     def GetBallDiameter(self, id):
2389         return self.mesh.GetBallDiameter(id)
2390
2391     ## Returns XYZ coordinates of the barycenter of the given element
2392     #  \n If there is no element for the given ID - returns an empty list
2393     #  @return a list of three double values
2394     #  @ingroup l1_meshinfo
2395     def BaryCenter(self, id):
2396         return self.mesh.BaryCenter(id)
2397
2398     ## Passes mesh elements through the given filter and return IDs of fitting elements
2399     #  @param theFilter SMESH_Filter
2400     #  @return a list of ids
2401     #  @ingroup l1_controls
2402     def GetIdsFromFilter(self, theFilter):
2403         theFilter.SetMesh( self.mesh )
2404         return theFilter.GetIDs()
2405
2406     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2407     #  Returns a list of special structures (borders).
2408     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2409     #  @ingroup l1_controls
2410     def GetFreeBorders(self):
2411         aFilterMgr = self.smeshpyD.CreateFilterManager()
2412         aPredicate = aFilterMgr.CreateFreeEdges()
2413         aPredicate.SetMesh(self.mesh)
2414         aBorders = aPredicate.GetBorders()
2415         aFilterMgr.UnRegister()
2416         return aBorders
2417
2418
2419     # Get mesh measurements information:
2420     # ------------------------------------
2421
2422     ## Get minimum distance between two nodes, elements or distance to the origin
2423     #  @param id1 first node/element id
2424     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2425     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2426     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2427     #  @return minimum distance value
2428     #  @sa GetMinDistance()
2429     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2430         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2431         return aMeasure.value
2432
2433     ## Get measure structure specifying minimum distance data between two objects
2434     #  @param id1 first node/element id
2435     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2436     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2437     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2438     #  @return Measure structure
2439     #  @sa MinDistance()
2440     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2441         if isElem1:
2442             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2443         else:
2444             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2445         if id2 != 0:
2446             if isElem2:
2447                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2448             else:
2449                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2450             pass
2451         else:
2452             id2 = None
2453
2454         aMeasurements = self.smeshpyD.CreateMeasurements()
2455         aMeasure = aMeasurements.MinDistance(id1, id2)
2456         genObjUnRegister([aMeasurements,id1, id2])
2457         return aMeasure
2458
2459     ## Get bounding box of the specified object(s)
2460     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2461     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2462     #  @c False specifies that @a objects are nodes
2463     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2464     #  @sa GetBoundingBox()
2465     def BoundingBox(self, objects=None, isElem=False):
2466         result = self.GetBoundingBox(objects, isElem)
2467         if result is None:
2468             result = (0.0,)*6
2469         else:
2470             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2471         return result
2472
2473     ## Get measure structure specifying bounding box data of the specified object(s)
2474     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2475     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2476     #  @c False specifies that @a objects are nodes
2477     #  @return Measure structure
2478     #  @sa BoundingBox()
2479     def GetBoundingBox(self, IDs=None, isElem=False):
2480         if IDs is None:
2481             IDs = [self.mesh]
2482         elif isinstance(IDs, tuple):
2483             IDs = list(IDs)
2484         if not isinstance(IDs, list):
2485             IDs = [IDs]
2486         if len(IDs) > 0 and isinstance(IDs[0], int):
2487             IDs = [IDs]
2488         srclist = []
2489         unRegister = genObjUnRegister()
2490         for o in IDs:
2491             if isinstance(o, Mesh):
2492                 srclist.append(o.mesh)
2493             elif hasattr(o, "_narrow"):
2494                 src = o._narrow(SMESH.SMESH_IDSource)
2495                 if src: srclist.append(src)
2496                 pass
2497             elif isinstance(o, list):
2498                 if isElem:
2499                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2500                 else:
2501                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2502                 unRegister.set( srclist[-1] )
2503                 pass
2504             pass
2505         aMeasurements = self.smeshpyD.CreateMeasurements()
2506         unRegister.set( aMeasurements )
2507         aMeasure = aMeasurements.BoundingBox(srclist)
2508         return aMeasure
2509
2510     # Mesh edition (SMESH_MeshEditor functionality):
2511     # ---------------------------------------------
2512
2513     ## Removes the elements from the mesh by ids
2514     #  @param IDsOfElements is a list of ids of elements to remove
2515     #  @return True or False
2516     #  @ingroup l2_modif_del
2517     def RemoveElements(self, IDsOfElements):
2518         return self.editor.RemoveElements(IDsOfElements)
2519
2520     ## Removes nodes from mesh by ids
2521     #  @param IDsOfNodes is a list of ids of nodes to remove
2522     #  @return True or False
2523     #  @ingroup l2_modif_del
2524     def RemoveNodes(self, IDsOfNodes):
2525         return self.editor.RemoveNodes(IDsOfNodes)
2526
2527     ## Removes all orphan (free) nodes from mesh
2528     #  @return number of the removed nodes
2529     #  @ingroup l2_modif_del
2530     def RemoveOrphanNodes(self):
2531         return self.editor.RemoveOrphanNodes()
2532
2533     ## Add a node to the mesh by coordinates
2534     #  @return Id of the new node
2535     #  @ingroup l2_modif_add
2536     def AddNode(self, x, y, z):
2537         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2538         if hasVars: self.mesh.SetParameters(Parameters)
2539         return self.editor.AddNode( x, y, z)
2540
2541     ## Creates a 0D element on a node with given number.
2542     #  @param IDOfNode the ID of node for creation of the element.
2543     #  @return the Id of the new 0D element
2544     #  @ingroup l2_modif_add
2545     def Add0DElement(self, IDOfNode):
2546         return self.editor.Add0DElement(IDOfNode)
2547
2548     ## Create 0D elements on all nodes of the given elements except those 
2549     #  nodes on which a 0D element already exists.
2550     #  @param theObject an object on whose nodes 0D elements will be created.
2551     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2552     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2553     #  @param theGroupName optional name of a group to add 0D elements created
2554     #         and/or found on nodes of \a theObject.
2555     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2556     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2557     #          can be retrieved from the returned object by calling GetIDs()
2558     #  @ingroup l2_modif_add
2559     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2560         unRegister = genObjUnRegister()
2561         if isinstance( theObject, Mesh ):
2562             theObject = theObject.GetMesh()
2563         if isinstance( theObject, list ):
2564             theObject = self.GetIDSource( theObject, SMESH.ALL )
2565             unRegister.set( theObject )
2566         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2567
2568     ## Creates a ball element on a node with given ID.
2569     #  @param IDOfNode the ID of node for creation of the element.
2570     #  @param diameter the bal diameter.
2571     #  @return the Id of the new ball element
2572     #  @ingroup l2_modif_add
2573     def AddBall(self, IDOfNode, diameter):
2574         return self.editor.AddBall( IDOfNode, diameter )
2575
2576     ## Creates a linear or quadratic edge (this is determined
2577     #  by the number of given nodes).
2578     #  @param IDsOfNodes the list of node IDs for creation of the element.
2579     #  The order of nodes in this list should correspond to the description
2580     #  of MED. \n This description is located by the following link:
2581     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2582     #  @return the Id of the new edge
2583     #  @ingroup l2_modif_add
2584     def AddEdge(self, IDsOfNodes):
2585         return self.editor.AddEdge(IDsOfNodes)
2586
2587     ## Creates a linear or quadratic face (this is determined
2588     #  by the number of given nodes).
2589     #  @param IDsOfNodes the list of node IDs for creation of the element.
2590     #  The order of nodes in this list should correspond to the description
2591     #  of MED. \n This description is located by the following link:
2592     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2593     #  @return the Id of the new face
2594     #  @ingroup l2_modif_add
2595     def AddFace(self, IDsOfNodes):
2596         return self.editor.AddFace(IDsOfNodes)
2597
2598     ## Adds a polygonal face to the mesh by the list of node IDs
2599     #  @param IdsOfNodes the list of node IDs for creation of the element.
2600     #  @return the Id of the new face
2601     #  @ingroup l2_modif_add
2602     def AddPolygonalFace(self, IdsOfNodes):
2603         return self.editor.AddPolygonalFace(IdsOfNodes)
2604
2605     ## Creates both simple and quadratic volume (this is determined
2606     #  by the number of given nodes).
2607     #  @param IDsOfNodes the list of node IDs for creation of the element.
2608     #  The order of nodes in this list should correspond to the description
2609     #  of MED. \n This description is located by the following link:
2610     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2611     #  @return the Id of the new volumic element
2612     #  @ingroup l2_modif_add
2613     def AddVolume(self, IDsOfNodes):
2614         return self.editor.AddVolume(IDsOfNodes)
2615
2616     ## Creates a volume of many faces, giving nodes for each face.
2617     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2618     #  @param Quantities the list of integer values, Quantities[i]
2619     #         gives the quantity of nodes in face number i.
2620     #  @return the Id of the new volumic element
2621     #  @ingroup l2_modif_add
2622     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2623         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2624
2625     ## Creates a volume of many faces, giving the IDs of the existing faces.
2626     #  @param IdsOfFaces the list of face IDs for volume creation.
2627     #
2628     #  Note:  The created volume will refer only to the nodes
2629     #         of the given faces, not to the faces themselves.
2630     #  @return the Id of the new volumic element
2631     #  @ingroup l2_modif_add
2632     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2633         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2634
2635
2636     ## @brief Binds a node to a vertex
2637     #  @param NodeID a node ID
2638     #  @param Vertex a vertex or vertex ID
2639     #  @return True if succeed else raises an exception
2640     #  @ingroup l2_modif_add
2641     def SetNodeOnVertex(self, NodeID, Vertex):
2642         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2643             VertexID = Vertex.GetSubShapeIndices()[0]
2644         else:
2645             VertexID = Vertex
2646         try:
2647             self.editor.SetNodeOnVertex(NodeID, VertexID)
2648         except SALOME.SALOME_Exception, inst:
2649             raise ValueError, inst.details.text
2650         return True
2651
2652
2653     ## @brief Stores the node position on an edge
2654     #  @param NodeID a node ID
2655     #  @param Edge an edge or edge ID
2656     #  @param paramOnEdge a parameter on the edge where the node is located
2657     #  @return True if succeed else raises an exception
2658     #  @ingroup l2_modif_add
2659     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2660         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2661             EdgeID = Edge.GetSubShapeIndices()[0]
2662         else:
2663             EdgeID = Edge
2664         try:
2665             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2666         except SALOME.SALOME_Exception, inst:
2667             raise ValueError, inst.details.text
2668         return True
2669
2670     ## @brief Stores node position on a face
2671     #  @param NodeID a node ID
2672     #  @param Face a face or face ID
2673     #  @param u U parameter on the face where the node is located
2674     #  @param v V parameter on the face where the node is located
2675     #  @return True if succeed else raises an exception
2676     #  @ingroup l2_modif_add
2677     def SetNodeOnFace(self, NodeID, Face, u, v):
2678         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2679             FaceID = Face.GetSubShapeIndices()[0]
2680         else:
2681             FaceID = Face
2682         try:
2683             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2684         except SALOME.SALOME_Exception, inst:
2685             raise ValueError, inst.details.text
2686         return True
2687
2688     ## @brief Binds a node to a solid
2689     #  @param NodeID a node ID
2690     #  @param Solid  a solid or solid ID
2691     #  @return True if succeed else raises an exception
2692     #  @ingroup l2_modif_add
2693     def SetNodeInVolume(self, NodeID, Solid):
2694         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2695             SolidID = Solid.GetSubShapeIndices()[0]
2696         else:
2697             SolidID = Solid
2698         try:
2699             self.editor.SetNodeInVolume(NodeID, SolidID)
2700         except SALOME.SALOME_Exception, inst:
2701             raise ValueError, inst.details.text
2702         return True
2703
2704     ## @brief Bind an element to a shape
2705     #  @param ElementID an element ID
2706     #  @param Shape a shape or shape ID
2707     #  @return True if succeed else raises an exception
2708     #  @ingroup l2_modif_add
2709     def SetMeshElementOnShape(self, ElementID, Shape):
2710         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2711             ShapeID = Shape.GetSubShapeIndices()[0]
2712         else:
2713             ShapeID = Shape
2714         try:
2715             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2716         except SALOME.SALOME_Exception, inst:
2717             raise ValueError, inst.details.text
2718         return True
2719
2720
2721     ## Moves the node with the given id
2722     #  @param NodeID the id of the node
2723     #  @param x  a new X coordinate
2724     #  @param y  a new Y coordinate
2725     #  @param z  a new Z coordinate
2726     #  @return True if succeed else False
2727     #  @ingroup l2_modif_movenode
2728     def MoveNode(self, NodeID, x, y, z):
2729         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2730         if hasVars: self.mesh.SetParameters(Parameters)
2731         return self.editor.MoveNode(NodeID, x, y, z)
2732
2733     ## Finds the node closest to a point and moves it to a point location
2734     #  @param x  the X coordinate of a point
2735     #  @param y  the Y coordinate of a point
2736     #  @param z  the Z coordinate of a point
2737     #  @param NodeID if specified (>0), the node with this ID is moved,
2738     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
2739     #  @return the ID of a node
2740     #  @ingroup l2_modif_throughp
2741     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2742         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2743         if hasVars: self.mesh.SetParameters(Parameters)
2744         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2745
2746     ## Finds the node closest to a point
2747     #  @param x  the X coordinate of a point
2748     #  @param y  the Y coordinate of a point
2749     #  @param z  the Z coordinate of a point
2750     #  @return the ID of a node
2751     #  @ingroup l2_modif_throughp
2752     def FindNodeClosestTo(self, x, y, z):
2753         #preview = self.mesh.GetMeshEditPreviewer()
2754         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2755         return self.editor.FindNodeClosestTo(x, y, z)
2756
2757     ## Finds the elements where a point lays IN or ON
2758     #  @param x  the X coordinate of a point
2759     #  @param y  the Y coordinate of a point
2760     #  @param z  the Z coordinate of a point
2761     #  @param elementType type of elements to find (SMESH.ALL type
2762     #         means elements of any type excluding nodes, discrete and 0D elements)
2763     #  @param meshPart a part of mesh (group, sub-mesh) to search within
2764     #  @return list of IDs of found elements
2765     #  @ingroup l2_modif_throughp
2766     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2767         if meshPart:
2768             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2769         else:
2770             return self.editor.FindElementsByPoint(x, y, z, elementType)
2771
2772     # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2773     # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2774     # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2775
2776     def GetPointState(self, x, y, z):
2777         return self.editor.GetPointState(x, y, z)
2778
2779     ## Finds the node closest to a point and moves it to a point location
2780     #  @param x  the X coordinate of a point
2781     #  @param y  the Y coordinate of a point
2782     #  @param z  the Z coordinate of a point
2783     #  @return the ID of a moved node
2784     #  @ingroup l2_modif_throughp
2785     def MeshToPassThroughAPoint(self, x, y, z):
2786         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2787
2788     ## Replaces two neighbour triangles sharing Node1-Node2 link
2789     #  with the triangles built on the same 4 nodes but having other common link.
2790     #  @param NodeID1  the ID of the first node
2791     #  @param NodeID2  the ID of the second node
2792     #  @return false if proper faces were not found
2793     #  @ingroup l2_modif_invdiag
2794     def InverseDiag(self, NodeID1, NodeID2):
2795         return self.editor.InverseDiag(NodeID1, NodeID2)
2796
2797     ## Replaces two neighbour triangles sharing Node1-Node2 link
2798     #  with a quadrangle built on the same 4 nodes.
2799     #  @param NodeID1  the ID of the first node
2800     #  @param NodeID2  the ID of the second node
2801     #  @return false if proper faces were not found
2802     #  @ingroup l2_modif_unitetri
2803     def DeleteDiag(self, NodeID1, NodeID2):
2804         return self.editor.DeleteDiag(NodeID1, NodeID2)
2805
2806     ## Reorients elements by ids
2807     #  @param IDsOfElements if undefined reorients all mesh elements
2808     #  @return True if succeed else False
2809     #  @ingroup l2_modif_changori
2810     def Reorient(self, IDsOfElements=None):
2811         if IDsOfElements == None:
2812             IDsOfElements = self.GetElementsId()
2813         return self.editor.Reorient(IDsOfElements)
2814
2815     ## Reorients all elements of the object
2816     #  @param theObject mesh, submesh or group
2817     #  @return True if succeed else False
2818     #  @ingroup l2_modif_changori
2819     def ReorientObject(self, theObject):
2820         if ( isinstance( theObject, Mesh )):
2821             theObject = theObject.GetMesh()
2822         return self.editor.ReorientObject(theObject)
2823
2824     ## Reorient faces contained in \a the2DObject.
2825     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2826     #  @param theDirection is a desired direction of normal of \a theFace.
2827     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
2828     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2829     #         compared with theDirection. It can be either ID of face or a point
2830     #         by which the face will be found. The point can be given as either
2831     #         a GEOM vertex or a list of point coordinates.
2832     #  @return number of reoriented faces
2833     #  @ingroup l2_modif_changori
2834     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2835         unRegister = genObjUnRegister()
2836         # check the2DObject
2837         if isinstance( the2DObject, Mesh ):
2838             the2DObject = the2DObject.GetMesh()
2839         if isinstance( the2DObject, list ):
2840             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2841             unRegister.set( the2DObject )
2842         # check theDirection
2843         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2844             theDirection = self.smeshpyD.GetDirStruct( theDirection )
2845         if isinstance( theDirection, list ):
2846             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
2847         # prepare theFace and thePoint
2848         theFace = theFaceOrPoint
2849         thePoint = PointStruct(0,0,0)
2850         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2851             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2852             theFace = -1
2853         if isinstance( theFaceOrPoint, list ):
2854             thePoint = PointStruct( *theFaceOrPoint )
2855             theFace = -1
2856         if isinstance( theFaceOrPoint, PointStruct ):
2857             thePoint = theFaceOrPoint
2858             theFace = -1
2859         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2860
2861     ## Fuses the neighbouring triangles into quadrangles.
2862     #  @param IDsOfElements The triangles to be fused,
2863     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
2864     #                       choose a neighbour to fuse with.
2865     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
2866     #                       is still performed; theMaxAngle is mesured in radians.
2867     #                       Also it could be a name of variable which defines angle in degrees.
2868     #  @return TRUE in case of success, FALSE otherwise.
2869     #  @ingroup l2_modif_unitetri
2870     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2871         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2872         self.mesh.SetParameters(Parameters)
2873         if not IDsOfElements:
2874             IDsOfElements = self.GetElementsId()
2875         Functor = self.smeshpyD.GetFunctor(theCriterion)
2876         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2877
2878     ## Fuses the neighbouring triangles of the object into quadrangles
2879     #  @param theObject is mesh, submesh or group
2880     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2881     #         choose a neighbour to fuse with.
2882     #  @param MaxAngle   a max angle between element normals at which the fusion
2883     #                   is still performed; theMaxAngle is mesured in radians.
2884     #  @return TRUE in case of success, FALSE otherwise.
2885     #  @ingroup l2_modif_unitetri
2886     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2887         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2888         self.mesh.SetParameters(Parameters)
2889         if isinstance( theObject, Mesh ):
2890             theObject = theObject.GetMesh()
2891         Functor = self.smeshpyD.GetFunctor(theCriterion)
2892         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2893
2894     ## Splits quadrangles into triangles.
2895     #  @param IDsOfElements the faces to be splitted.
2896     #  @param theCriterion   is a numerical functor, in terms of enum SMESH.FunctorType, used to
2897     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
2898     #         value, then quadrangles will be split by the smallest diagonal.
2899     #  @return TRUE in case of success, FALSE otherwise.
2900     #  @ingroup l2_modif_cutquadr
2901     def QuadToTri (self, IDsOfElements, theCriterion = None):
2902         if IDsOfElements == []:
2903             IDsOfElements = self.GetElementsId()
2904         if theCriterion is None:
2905             theCriterion = FT_MaxElementLength2D
2906         Functor = self.smeshpyD.GetFunctor(theCriterion)
2907         return self.editor.QuadToTri(IDsOfElements, Functor)
2908
2909     ## Splits quadrangles into triangles.
2910     #  @param theObject the object from which the list of elements is taken,
2911     #         this is mesh, submesh or group
2912     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2913     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
2914     #         value, then quadrangles will be split by the smallest diagonal.
2915     #  @return TRUE in case of success, FALSE otherwise.
2916     #  @ingroup l2_modif_cutquadr
2917     def QuadToTriObject (self, theObject, theCriterion = None):
2918         if ( isinstance( theObject, Mesh )):
2919             theObject = theObject.GetMesh()
2920         if theCriterion is None:
2921             theCriterion = FT_MaxElementLength2D
2922         Functor = self.smeshpyD.GetFunctor(theCriterion)
2923         return self.editor.QuadToTriObject(theObject, Functor)
2924
2925     ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
2926     #  a quadrangle.
2927     #  @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
2928     #         group or a list of face IDs. By default all quadrangles are split
2929     #  @ingroup l2_modif_cutquadr
2930     def QuadTo4Tri (self, theElements=[]):
2931         unRegister = genObjUnRegister()
2932         if isinstance( theElements, Mesh ):
2933             theElements = theElements.mesh
2934         elif not theElements:
2935             theElements = self.mesh
2936         elif isinstance( theElements, list ):
2937             theElements = self.GetIDSource( theElements, SMESH.FACE )
2938             unRegister.set( theElements )
2939         return self.editor.QuadTo4Tri( theElements )
2940
2941     ## Splits quadrangles into triangles.
2942     #  @param IDsOfElements the faces to be splitted
2943     #  @param Diag13        is used to choose a diagonal for splitting.
2944     #  @return TRUE in case of success, FALSE otherwise.
2945     #  @ingroup l2_modif_cutquadr
2946     def SplitQuad (self, IDsOfElements, Diag13):
2947         if IDsOfElements == []:
2948             IDsOfElements = self.GetElementsId()
2949         return self.editor.SplitQuad(IDsOfElements, Diag13)
2950
2951     ## Splits quadrangles into triangles.
2952     #  @param theObject the object from which the list of elements is taken,
2953     #         this is mesh, submesh or group
2954     #  @param Diag13    is used to choose a diagonal for splitting.
2955     #  @return TRUE in case of success, FALSE otherwise.
2956     #  @ingroup l2_modif_cutquadr
2957     def SplitQuadObject (self, theObject, Diag13):
2958         if ( isinstance( theObject, Mesh )):
2959             theObject = theObject.GetMesh()
2960         return self.editor.SplitQuadObject(theObject, Diag13)
2961
2962     ## Finds a better splitting of the given quadrangle.
2963     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
2964     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
2965     #         choose a diagonal for splitting.
2966     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
2967     #          diagonal is better, 0 if error occurs.
2968     #  @ingroup l2_modif_cutquadr
2969     def BestSplit (self, IDOfQuad, theCriterion):
2970         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
2971
2972     ## Splits volumic elements into tetrahedrons
2973     #  @param elemIDs either list of elements or mesh or group or submesh
2974     #  @param method  flags passing splitting method: Hex_5Tet, Hex_6Tet, Hex_24Tet
2975     #         Hex_5Tet - split the hexahedron into 5 tetrahedrons, etc
2976     #  @ingroup l2_modif_cutquadr
2977     def SplitVolumesIntoTetra(self, elemIDs, method=smeshBuilder.Hex_5Tet ):
2978         unRegister = genObjUnRegister()
2979         if isinstance( elemIDs, Mesh ):
2980             elemIDs = elemIDs.GetMesh()
2981         if ( isinstance( elemIDs, list )):
2982             elemIDs = self.editor.MakeIDSource(elemIDs, SMESH.VOLUME)
2983             unRegister.set( elemIDs )
2984         self.editor.SplitVolumesIntoTetra(elemIDs, method)
2985
2986     ## Splits quadrangle faces near triangular facets of volumes
2987     #
2988     #  @ingroup l1_auxiliary
2989     def SplitQuadsNearTriangularFacets(self):
2990         faces_array = self.GetElementsByType(SMESH.FACE)
2991         for face_id in faces_array:
2992             if self.GetElemNbNodes(face_id) == 4: # quadrangle
2993                 quad_nodes = self.mesh.GetElemNodes(face_id)
2994                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2995                 isVolumeFound = False
2996                 for node1_elem in node1_elems:
2997                     if not isVolumeFound:
2998                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2999                             nb_nodes = self.GetElemNbNodes(node1_elem)
3000                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3001                                 volume_elem = node1_elem
3002                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3003                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3004                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3005                                         isVolumeFound = True
3006                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3007                                             self.SplitQuad([face_id], False) # diagonal 2-4
3008                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3009                                         isVolumeFound = True
3010                                         self.SplitQuad([face_id], True) # diagonal 1-3
3011                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3012                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3013                                         isVolumeFound = True
3014                                         self.SplitQuad([face_id], True) # diagonal 1-3
3015
3016     ## @brief Splits hexahedrons into tetrahedrons.
3017     #
3018     #  This operation uses pattern mapping functionality for splitting.
3019     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3020     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3021     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3022     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3023     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3024     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3025     #  @return TRUE in case of success, FALSE otherwise.
3026     #  @ingroup l1_auxiliary
3027     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3028         # Pattern:     5.---------.6
3029         #              /|#*      /|
3030         #             / | #*    / |
3031         #            /  |  # * /  |
3032         #           /   |   # /*  |
3033         # (0,0,1) 4.---------.7 * |
3034         #          |#*  |1   | # *|
3035         #          | # *.----|---#.2
3036         #          |  #/ *   |   /
3037         #          |  /#  *  |  /
3038         #          | /   # * | /
3039         #          |/      #*|/
3040         # (0,0,0) 0.---------.3
3041         pattern_tetra = "!!! Nb of points: \n 8 \n\
3042         !!! Points: \n\
3043         0 0 0  !- 0 \n\
3044         0 1 0  !- 1 \n\
3045         1 1 0  !- 2 \n\
3046         1 0 0  !- 3 \n\
3047         0 0 1  !- 4 \n\
3048         0 1 1  !- 5 \n\
3049         1 1 1  !- 6 \n\
3050         1 0 1  !- 7 \n\
3051         !!! Indices of points of 6 tetras: \n\
3052         0 3 4 1 \n\
3053         7 4 3 1 \n\
3054         4 7 5 1 \n\
3055         6 2 5 7 \n\
3056         1 5 2 7 \n\
3057         2 3 1 7 \n"
3058
3059         pattern = self.smeshpyD.GetPattern()
3060         isDone  = pattern.LoadFromFile(pattern_tetra)
3061         if not isDone:
3062             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3063             return isDone
3064
3065         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3066         isDone = pattern.MakeMesh(self.mesh, False, False)
3067         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3068
3069         # split quafrangle faces near triangular facets of volumes
3070         self.SplitQuadsNearTriangularFacets()
3071
3072         return isDone
3073
3074     ## @brief Split hexahedrons into prisms.
3075     #
3076     #  Uses the pattern mapping functionality for splitting.
3077     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3078     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3079     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3080     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3081     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3082     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3083     #  @return TRUE in case of success, FALSE otherwise.
3084     #  @ingroup l1_auxiliary
3085     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3086         # Pattern:     5.---------.6
3087         #              /|#       /|
3088         #             / | #     / |
3089         #            /  |  #   /  |
3090         #           /   |   # /   |
3091         # (0,0,1) 4.---------.7   |
3092         #          |    |    |    |
3093         #          |   1.----|----.2
3094         #          |   / *   |   /
3095         #          |  /   *  |  /
3096         #          | /     * | /
3097         #          |/       *|/
3098         # (0,0,0) 0.---------.3
3099         pattern_prism = "!!! Nb of points: \n 8 \n\
3100         !!! Points: \n\
3101         0 0 0  !- 0 \n\
3102         0 1 0  !- 1 \n\
3103         1 1 0  !- 2 \n\
3104         1 0 0  !- 3 \n\
3105         0 0 1  !- 4 \n\
3106         0 1 1  !- 5 \n\
3107         1 1 1  !- 6 \n\
3108         1 0 1  !- 7 \n\
3109         !!! Indices of points of 2 prisms: \n\
3110         0 1 3 4 5 7 \n\
3111         2 3 1 6 7 5 \n"
3112
3113         pattern = self.smeshpyD.GetPattern()
3114         isDone  = pattern.LoadFromFile(pattern_prism)
3115         if not isDone:
3116             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3117             return isDone
3118
3119         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3120         isDone = pattern.MakeMesh(self.mesh, False, False)
3121         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3122
3123         # Splits quafrangle faces near triangular facets of volumes
3124         self.SplitQuadsNearTriangularFacets()
3125
3126         return isDone
3127
3128     ## Smoothes elements
3129     #  @param IDsOfElements the list if ids of elements to smooth
3130     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3131     #  Note that nodes built on edges and boundary nodes are always fixed.
3132     #  @param MaxNbOfIterations the maximum number of iterations
3133     #  @param MaxAspectRatio varies in range [1.0, inf]
3134     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3135     #  @return TRUE in case of success, FALSE otherwise.
3136     #  @ingroup l2_modif_smooth
3137     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3138                MaxNbOfIterations, MaxAspectRatio, Method):
3139         if IDsOfElements == []:
3140             IDsOfElements = self.GetElementsId()
3141         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3142         self.mesh.SetParameters(Parameters)
3143         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3144                                   MaxNbOfIterations, MaxAspectRatio, Method)
3145
3146     ## Smoothes elements which belong to the given object
3147     #  @param theObject the object to smooth
3148     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3149     #  Note that nodes built on edges and boundary nodes are always fixed.
3150     #  @param MaxNbOfIterations the maximum number of iterations
3151     #  @param MaxAspectRatio varies in range [1.0, inf]
3152     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3153     #  @return TRUE in case of success, FALSE otherwise.
3154     #  @ingroup l2_modif_smooth
3155     def SmoothObject(self, theObject, IDsOfFixedNodes,
3156                      MaxNbOfIterations, MaxAspectRatio, Method):
3157         if ( isinstance( theObject, Mesh )):
3158             theObject = theObject.GetMesh()
3159         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3160                                         MaxNbOfIterations, MaxAspectRatio, Method)
3161
3162     ## Parametrically smoothes the given elements
3163     #  @param IDsOfElements the list if ids of elements to smooth
3164     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3165     #  Note that nodes built on edges and boundary nodes are always fixed.
3166     #  @param MaxNbOfIterations the maximum number of iterations
3167     #  @param MaxAspectRatio varies in range [1.0, inf]
3168     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3169     #  @return TRUE in case of success, FALSE otherwise.
3170     #  @ingroup l2_modif_smooth
3171     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3172                          MaxNbOfIterations, MaxAspectRatio, Method):
3173         if IDsOfElements == []:
3174             IDsOfElements = self.GetElementsId()
3175         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3176         self.mesh.SetParameters(Parameters)
3177         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3178                                             MaxNbOfIterations, MaxAspectRatio, Method)
3179
3180     ## Parametrically smoothes the elements which belong to the given object
3181     #  @param theObject the object to smooth
3182     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3183     #  Note that nodes built on edges and boundary nodes are always fixed.
3184     #  @param MaxNbOfIterations the maximum number of iterations
3185     #  @param MaxAspectRatio varies in range [1.0, inf]
3186     #  @param Method Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3187     #  @return TRUE in case of success, FALSE otherwise.
3188     #  @ingroup l2_modif_smooth
3189     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3190                                MaxNbOfIterations, MaxAspectRatio, Method):
3191         if ( isinstance( theObject, Mesh )):
3192             theObject = theObject.GetMesh()
3193         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3194                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3195
3196     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3197     #  them with quadratic with the same id.
3198     #  @param theForce3d new node creation method:
3199     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3200     #         1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3201     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3202     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3203     #  @ingroup l2_modif_tofromqu
3204     def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3205         if isinstance( theSubMesh, Mesh ):
3206             theSubMesh = theSubMesh.mesh
3207         if theToBiQuad:
3208             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3209         else:
3210             if theSubMesh:
3211                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3212             else:
3213                 self.editor.ConvertToQuadratic(theForce3d)
3214         error = self.editor.GetLastError()
3215         if error and error.comment:
3216             print error.comment
3217             
3218     ## Converts the mesh from quadratic to ordinary,
3219     #  deletes old quadratic elements, \n replacing
3220     #  them with ordinary mesh elements with the same id.
3221     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3222     #  @ingroup l2_modif_tofromqu
3223     def ConvertFromQuadratic(self, theSubMesh=None):
3224         if theSubMesh:
3225             self.editor.ConvertFromQuadraticObject(theSubMesh)
3226         else:
3227             return self.editor.ConvertFromQuadratic()
3228
3229     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3230     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3231     #  @ingroup l2_modif_edit
3232     def  Make2DMeshFrom3D(self):
3233         return self.editor. Make2DMeshFrom3D()
3234
3235     ## Creates missing boundary elements
3236     #  @param elements - elements whose boundary is to be checked:
3237     #                    mesh, group, sub-mesh or list of elements
3238     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3239     #  @param dimension - defines type of boundary elements to create:
3240     #                     SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3241     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3242     #  @param groupName - a name of group to store created boundary elements in,
3243     #                     "" means not to create the group
3244     #  @param meshName - a name of new mesh to store created boundary elements in,
3245     #                     "" means not to create the new mesh
3246     #  @param toCopyElements - if true, the checked elements will be copied into
3247     #     the new mesh else only boundary elements will be copied into the new mesh
3248     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3249     #     boundary elements will be copied into the new mesh
3250     #  @return tuple (mesh, group) where bondary elements were added to
3251     #  @ingroup l2_modif_edit
3252     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3253                          toCopyElements=False, toCopyExistingBondary=False):
3254         unRegister = genObjUnRegister()
3255         if isinstance( elements, Mesh ):
3256             elements = elements.GetMesh()
3257         if ( isinstance( elements, list )):
3258             elemType = SMESH.ALL
3259             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3260             elements = self.editor.MakeIDSource(elements, elemType)
3261             unRegister.set( elements )
3262         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3263                                                    toCopyElements,toCopyExistingBondary)
3264         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3265         return mesh, group
3266
3267     ##
3268     # @brief Creates missing boundary elements around either the whole mesh or 
3269     #    groups of 2D elements
3270     #  @param dimension - defines type of boundary elements to create
3271     #  @param groupName - a name of group to store all boundary elements in,
3272     #    "" means not to create the group
3273     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3274     #    mesh + created boundary elements; "" means not to create the new mesh
3275     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3276     #    the new mesh else only boundary elements will be copied into the new mesh
3277     #  @param groups - groups of 2D elements to make boundary around
3278     #  @retval tuple( long, mesh, groups )
3279     #                 long - number of added boundary elements
3280     #                 mesh - the mesh where elements were added to
3281     #                 group - the group of boundary elements or None
3282     #
3283     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3284                              toCopyAll=False, groups=[]):
3285         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3286                                                            toCopyAll,groups)
3287         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3288         return nb, mesh, group
3289
3290     ## Renumber mesh nodes
3291     #  @ingroup l2_modif_renumber
3292     def RenumberNodes(self):
3293         self.editor.RenumberNodes()
3294
3295     ## Renumber mesh elements
3296     #  @ingroup l2_modif_renumber
3297     def RenumberElements(self):
3298         self.editor.RenumberElements()
3299
3300     ## Generates new elements by rotation of the elements around the axis
3301     #  @param IDsOfElements the list of ids of elements to sweep
3302     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3303     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3304     #  @param NbOfSteps the number of steps
3305     #  @param Tolerance tolerance
3306     #  @param MakeGroups forces the generation of new groups from existing ones
3307     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3308     #                    of all steps, else - size of each step
3309     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3310     #  @ingroup l2_modif_extrurev
3311     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3312                       MakeGroups=False, TotalAngle=False):
3313         if IDsOfElements == []:
3314             IDsOfElements = self.GetElementsId()
3315         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3316             Axis = self.smeshpyD.GetAxisStruct(Axis)
3317         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3318         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3319         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3320         self.mesh.SetParameters(Parameters)
3321         if TotalAngle and NbOfSteps:
3322             AngleInRadians /= NbOfSteps
3323         if MakeGroups:
3324             return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3325                                                        AngleInRadians, NbOfSteps, Tolerance)
3326         self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3327         return []
3328
3329     ## Generates new elements by rotation of the elements of object around the axis
3330     #  @param theObject object which elements should be sweeped.
3331     #                   It can be a mesh, a sub mesh or a group.
3332     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3333     #  @param AngleInRadians the angle of Rotation
3334     #  @param NbOfSteps number of steps
3335     #  @param Tolerance tolerance
3336     #  @param MakeGroups forces the generation of new groups from existing ones
3337     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3338     #                    of all steps, else - size of each step
3339     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3340     #  @ingroup l2_modif_extrurev
3341     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3342                             MakeGroups=False, TotalAngle=False):
3343         if ( isinstance( theObject, Mesh )):
3344             theObject = theObject.GetMesh()
3345         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3346             Axis = self.smeshpyD.GetAxisStruct(Axis)
3347         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3348         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3349         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3350         self.mesh.SetParameters(Parameters)
3351         if TotalAngle and NbOfSteps:
3352             AngleInRadians /= NbOfSteps
3353         if MakeGroups:
3354             return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3355                                                              NbOfSteps, Tolerance)
3356         self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3357         return []
3358
3359     ## Generates new elements by rotation of the elements of object around the axis
3360     #  @param theObject object which elements should be sweeped.
3361     #                   It can be a mesh, a sub mesh or a group.
3362     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3363     #  @param AngleInRadians the angle of Rotation
3364     #  @param NbOfSteps number of steps
3365     #  @param Tolerance tolerance
3366     #  @param MakeGroups forces the generation of new groups from existing ones
3367     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3368     #                    of all steps, else - size of each step
3369     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3370     #  @ingroup l2_modif_extrurev
3371     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3372                               MakeGroups=False, TotalAngle=False):
3373         if ( isinstance( theObject, Mesh )):
3374             theObject = theObject.GetMesh()
3375         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3376             Axis = self.smeshpyD.GetAxisStruct(Axis)
3377         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3378         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3379         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3380         self.mesh.SetParameters(Parameters)
3381         if TotalAngle and NbOfSteps:
3382             AngleInRadians /= NbOfSteps
3383         if MakeGroups:
3384             return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3385                                                                NbOfSteps, Tolerance)
3386         self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3387         return []
3388
3389     ## Generates new elements by rotation of the elements of object around the axis
3390     #  @param theObject object which elements should be sweeped.
3391     #                   It can be a mesh, a sub mesh or a group.
3392     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3393     #  @param AngleInRadians the angle of Rotation
3394     #  @param NbOfSteps number of steps
3395     #  @param Tolerance tolerance
3396     #  @param MakeGroups forces the generation of new groups from existing ones
3397     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3398     #                    of all steps, else - size of each step
3399     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3400     #  @ingroup l2_modif_extrurev
3401     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3402                               MakeGroups=False, TotalAngle=False):
3403         if ( isinstance( theObject, Mesh )):
3404             theObject = theObject.GetMesh()
3405         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3406             Axis = self.smeshpyD.GetAxisStruct(Axis)
3407         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3408         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3409         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3410         self.mesh.SetParameters(Parameters)
3411         if TotalAngle and NbOfSteps:
3412             AngleInRadians /= NbOfSteps
3413         if MakeGroups:
3414             return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3415                                                              NbOfSteps, Tolerance)
3416         self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3417         return []
3418
3419     ## Generates new elements by extrusion of the elements with given ids
3420     #  @param IDsOfElements the list of elements ids for extrusion
3421     #  @param StepVector vector or DirStruct or 3 vector components, defining
3422     #         the direction and value of extrusion for one step (the total extrusion
3423     #         length will be NbOfSteps * ||StepVector||)
3424     #  @param NbOfSteps the number of steps
3425     #  @param MakeGroups forces the generation of new groups from existing ones
3426     #  @param IsNodes is True if elements with given ids are nodes
3427     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3428     #  @ingroup l2_modif_extrurev
3429     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3430         if IDsOfElements == []:
3431             IDsOfElements = self.GetElementsId()
3432         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3433             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3434         if isinstance( StepVector, list ):
3435             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3436         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3437         Parameters = StepVector.PS.parameters + var_separator + Parameters
3438         self.mesh.SetParameters(Parameters)
3439         if MakeGroups:
3440             if(IsNodes):
3441                 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3442             else:
3443                 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3444         if(IsNodes):
3445             self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3446         else:
3447             self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3448         return []
3449
3450     ## Generates new elements by extrusion of the elements with given ids
3451     #  @param IDsOfElements is ids of elements
3452     #  @param StepVector vector or DirStruct or 3 vector components, defining
3453     #         the direction and value of extrusion for one step (the total extrusion
3454     #         length will be NbOfSteps * ||StepVector||)
3455     #  @param NbOfSteps the number of steps
3456     #  @param ExtrFlags sets flags for extrusion
3457     #  @param SewTolerance uses for comparing locations of nodes if flag
3458     #         EXTRUSION_FLAG_SEW is set
3459     #  @param MakeGroups forces the generation of new groups from existing ones
3460     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3461     #  @ingroup l2_modif_extrurev
3462     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3463                           ExtrFlags, SewTolerance, MakeGroups=False):
3464         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3465             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3466         if isinstance( StepVector, list ):
3467             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3468         if MakeGroups:
3469             return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3470                                                            ExtrFlags, SewTolerance)
3471         self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3472                                       ExtrFlags, SewTolerance)
3473         return []
3474
3475     ## Generates new elements by extrusion of the elements which belong to the object
3476     #  @param theObject the object which elements should be processed.
3477     #                   It can be a mesh, a sub mesh or a group.
3478     #  @param StepVector vector or DirStruct or 3 vector components, defining
3479     #         the direction and value of extrusion for one step (the total extrusion
3480     #         length will be NbOfSteps * ||StepVector||)
3481     #  @param NbOfSteps the number of steps
3482     #  @param MakeGroups forces the generation of new groups from existing ones
3483     #  @param  IsNodes is True if elements which belong to the object are nodes
3484     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3485     #  @ingroup l2_modif_extrurev
3486     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3487         if ( isinstance( theObject, Mesh )):
3488             theObject = theObject.GetMesh()
3489         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3490             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3491         if isinstance( StepVector, list ):
3492             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3493         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3494         Parameters = StepVector.PS.parameters + var_separator + Parameters
3495         self.mesh.SetParameters(Parameters)
3496         if MakeGroups:
3497             if(IsNodes):
3498                 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3499             else:
3500                 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3501         if(IsNodes):
3502             self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3503         else:
3504             self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3505         return []
3506
3507     ## Generates new elements by extrusion of the elements which belong to the object
3508     #  @param theObject object which elements should be processed.
3509     #                   It can be a mesh, a sub mesh or a group.
3510     #  @param StepVector vector or DirStruct or 3 vector components, defining
3511     #         the direction and value of extrusion for one step (the total extrusion
3512     #         length will be NbOfSteps * ||StepVector||)
3513     #  @param NbOfSteps the number of steps
3514     #  @param MakeGroups to generate new groups from existing ones
3515     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3516     #  @ingroup l2_modif_extrurev
3517     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3518         if ( isinstance( theObject, Mesh )):
3519             theObject = theObject.GetMesh()
3520         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3521             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3522         if isinstance( StepVector, list ):
3523             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3524         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3525         Parameters = StepVector.PS.parameters + var_separator + Parameters
3526         self.mesh.SetParameters(Parameters)
3527         if MakeGroups:
3528             return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3529         self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3530         return []
3531
3532     ## Generates new elements by extrusion of the elements which belong to the object
3533     #  @param theObject object which elements should be processed.
3534     #                   It can be a mesh, a sub mesh or a group.
3535     #  @param StepVector vector or DirStruct or 3 vector components, defining
3536     #         the direction and value of extrusion for one step (the total extrusion
3537     #         length will be NbOfSteps * ||StepVector||)
3538     #  @param NbOfSteps the number of steps
3539     #  @param MakeGroups forces the generation of new groups from existing ones
3540     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3541     #  @ingroup l2_modif_extrurev
3542     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3543         if ( isinstance( theObject, Mesh )):
3544             theObject = theObject.GetMesh()
3545         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3546             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3547         if isinstance( StepVector, list ):
3548             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3549         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3550         Parameters = StepVector.PS.parameters + var_separator + Parameters
3551         self.mesh.SetParameters(Parameters)
3552         if MakeGroups:
3553             return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3554         self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3555         return []
3556
3557
3558
3559     ## Generates new elements by extrusion of the given elements
3560     #  The path of extrusion must be a meshed edge.
3561     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3562     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3563     #  @param NodeStart the start node from Path. Defines the direction of extrusion
3564     #  @param HasAngles allows the shape to be rotated around the path
3565     #                   to get the resulting mesh in a helical fashion
3566     #  @param Angles list of angles in radians
3567     #  @param LinearVariation forces the computation of rotation angles as linear
3568     #                         variation of the given Angles along path steps
3569     #  @param HasRefPoint allows using the reference point
3570     #  @param RefPoint the point around which the elements are rotated (the mass
3571     #         center of the elements by default).
3572     #         The User can specify any point as the Reference Point.
3573     #         RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3574     #  @param MakeGroups forces the generation of new groups from existing ones
3575     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
3576     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3577     #          only SMESH::Extrusion_Error otherwise
3578     #  @ingroup l2_modif_extrurev
3579     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3580                             HasAngles, Angles, LinearVariation,
3581                             HasRefPoint, RefPoint, MakeGroups, ElemType):
3582         if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3583             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3584             pass
3585         elif isinstance( RefPoint, list ):
3586             RefPoint = PointStruct(*RefPoint)
3587             pass
3588         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3589         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3590         self.mesh.SetParameters(Parameters)
3591
3592         if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3593
3594         if isinstance(Base, list):
3595             IDsOfElements = []
3596             if Base == []: IDsOfElements = self.GetElementsId()
3597             else: IDsOfElements = Base
3598             return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3599                                                    HasAngles, Angles, LinearVariation,
3600                                                    HasRefPoint, RefPoint, MakeGroups, ElemType)
3601         else:
3602             if isinstance(Base, Mesh): Base = Base.GetMesh()
3603             if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3604                 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3605                                                           HasAngles, Angles, LinearVariation,
3606                                                           HasRefPoint, RefPoint, MakeGroups, ElemType)
3607             else:
3608                 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3609
3610
3611     ## Generates new elements by extrusion of the given elements
3612     #  The path of extrusion must be a meshed edge.
3613     #  @param IDsOfElements ids of elements
3614     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3615     #  @param PathShape shape(edge) defines the sub-mesh for the path
3616     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3617     #  @param HasAngles allows the shape to be rotated around the path
3618     #                   to get the resulting mesh in a helical fashion
3619     #  @param Angles list of angles in radians
3620     #  @param HasRefPoint allows using the reference point
3621     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3622     #         The User can specify any point as the Reference Point.
3623     #  @param MakeGroups forces the generation of new groups from existing ones
3624     #  @param LinearVariation forces the computation of rotation angles as linear
3625     #                         variation of the given Angles along path steps
3626     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3627     #          only SMESH::Extrusion_Error otherwise
3628     #  @ingroup l2_modif_extrurev
3629     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3630                            HasAngles, Angles, HasRefPoint, RefPoint,
3631                            MakeGroups=False, LinearVariation=False):
3632         if IDsOfElements == []:
3633             IDsOfElements = self.GetElementsId()
3634         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3635             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3636             pass
3637         if ( isinstance( PathMesh, Mesh )):
3638             PathMesh = PathMesh.GetMesh()
3639         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3640         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3641         self.mesh.SetParameters(Parameters)
3642         if HasAngles and Angles and LinearVariation:
3643             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3644             pass
3645         if MakeGroups:
3646             return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3647                                                             PathShape, NodeStart, HasAngles,
3648                                                             Angles, HasRefPoint, RefPoint)
3649         return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3650                                               NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3651
3652     ## Generates new elements by extrusion of the elements which belong to the object
3653     #  The path of extrusion must be a meshed edge.
3654     #  @param theObject the object which elements should be processed.
3655     #                   It can be a mesh, a sub mesh or a group.
3656     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3657     #  @param PathShape shape(edge) defines the sub-mesh for the path
3658     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3659     #  @param HasAngles allows the shape to be rotated around the path
3660     #                   to get the resulting mesh in a helical fashion
3661     #  @param Angles list of angles
3662     #  @param HasRefPoint allows using the reference point
3663     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3664     #         The User can specify any point as the Reference Point.
3665     #  @param MakeGroups forces the generation of new groups from existing ones
3666     #  @param LinearVariation forces the computation of rotation angles as linear
3667     #                         variation of the given Angles along path steps
3668     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3669     #          only SMESH::Extrusion_Error otherwise
3670     #  @ingroup l2_modif_extrurev
3671     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3672                                  HasAngles, Angles, HasRefPoint, RefPoint,
3673                                  MakeGroups=False, LinearVariation=False):
3674         if ( isinstance( theObject, Mesh )):
3675             theObject = theObject.GetMesh()
3676         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3677             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3678         if ( isinstance( PathMesh, Mesh )):
3679             PathMesh = PathMesh.GetMesh()
3680         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3681         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3682         self.mesh.SetParameters(Parameters)
3683         if HasAngles and Angles and LinearVariation:
3684             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3685             pass
3686         if MakeGroups:
3687             return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3688                                                                   PathShape, NodeStart, HasAngles,
3689                                                                   Angles, HasRefPoint, RefPoint)
3690         return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3691                                                     NodeStart, HasAngles, Angles, HasRefPoint,
3692                                                     RefPoint)
3693
3694     ## Generates new elements by extrusion of the elements which belong to the object
3695     #  The path of extrusion must be a meshed edge.
3696     #  @param theObject the object which elements should be processed.
3697     #                   It can be a mesh, a sub mesh or a group.
3698     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3699     #  @param PathShape shape(edge) defines the sub-mesh for the path
3700     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3701     #  @param HasAngles allows the shape to be rotated around the path
3702     #                   to get the resulting mesh in a helical fashion
3703     #  @param Angles list of angles
3704     #  @param HasRefPoint allows using the reference point
3705     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3706     #         The User can specify any point as the Reference Point.
3707     #  @param MakeGroups forces the generation of new groups from existing ones
3708     #  @param LinearVariation forces the computation of rotation angles as linear
3709     #                         variation of the given Angles along path steps
3710     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3711     #          only SMESH::Extrusion_Error otherwise
3712     #  @ingroup l2_modif_extrurev
3713     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3714                                    HasAngles, Angles, HasRefPoint, RefPoint,
3715                                    MakeGroups=False, LinearVariation=False):
3716         if ( isinstance( theObject, Mesh )):
3717             theObject = theObject.GetMesh()
3718         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3719             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3720         if ( isinstance( PathMesh, Mesh )):
3721             PathMesh = PathMesh.GetMesh()
3722         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3723         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3724         self.mesh.SetParameters(Parameters)
3725         if HasAngles and Angles and LinearVariation:
3726             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3727             pass
3728         if MakeGroups:
3729             return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3730                                                                     PathShape, NodeStart, HasAngles,
3731                                                                     Angles, HasRefPoint, RefPoint)
3732         return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3733                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3734                                                       RefPoint)
3735
3736     ## Generates new elements by extrusion of the elements which belong to the object
3737     #  The path of extrusion must be a meshed edge.
3738     #  @param theObject the object which elements should be processed.
3739     #                   It can be a mesh, a sub mesh or a group.
3740     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3741     #  @param PathShape shape(edge) defines the sub-mesh for the path
3742     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3743     #  @param HasAngles allows the shape to be rotated around the path
3744     #                   to get the resulting mesh in a helical fashion
3745     #  @param Angles list of angles
3746     #  @param HasRefPoint allows using the reference point
3747     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3748     #         The User can specify any point as the Reference Point.
3749     #  @param MakeGroups forces the generation of new groups from existing ones
3750     #  @param LinearVariation forces the computation of rotation angles as linear
3751     #                         variation of the given Angles along path steps
3752     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3753     #          only SMESH::Extrusion_Error otherwise
3754     #  @ingroup l2_modif_extrurev
3755     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3756                                    HasAngles, Angles, HasRefPoint, RefPoint,
3757                                    MakeGroups=False, LinearVariation=False):
3758         if ( isinstance( theObject, Mesh )):
3759             theObject = theObject.GetMesh()
3760         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3761             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3762         if ( isinstance( PathMesh, Mesh )):
3763             PathMesh = PathMesh.GetMesh()
3764         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3765         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3766         self.mesh.SetParameters(Parameters)
3767         if HasAngles and Angles and LinearVariation:
3768             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3769             pass
3770         if MakeGroups:
3771             return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3772                                                                     PathShape, NodeStart, HasAngles,
3773                                                                     Angles, HasRefPoint, RefPoint)
3774         return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3775                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3776                                                       RefPoint)
3777
3778     ## Creates a symmetrical copy of mesh elements
3779     #  @param IDsOfElements list of elements ids
3780     #  @param Mirror is AxisStruct or geom object(point, line, plane)
3781     #  @param theMirrorType is  POINT, AXIS or PLANE
3782     #  If the Mirror is a geom object this parameter is unnecessary
3783     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3784     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3785     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3786     #  @ingroup l2_modif_trsf
3787     def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3788         if IDsOfElements == []:
3789             IDsOfElements = self.GetElementsId()
3790         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3791             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3792         self.mesh.SetParameters(Mirror.parameters)
3793         if Copy and MakeGroups:
3794             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3795         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3796         return []
3797
3798     ## Creates a new mesh by a symmetrical copy of mesh elements
3799     #  @param IDsOfElements the list of elements ids
3800     #  @param Mirror is AxisStruct or geom object (point, line, plane)
3801     #  @param theMirrorType is  POINT, AXIS or PLANE
3802     #  If the Mirror is a geom object this parameter is unnecessary
3803     #  @param MakeGroups to generate new groups from existing ones
3804     #  @param NewMeshName a name of the new mesh to create
3805     #  @return instance of Mesh class
3806     #  @ingroup l2_modif_trsf
3807     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3808         if IDsOfElements == []:
3809             IDsOfElements = self.GetElementsId()
3810         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3811             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3812         self.mesh.SetParameters(Mirror.parameters)
3813         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3814                                           MakeGroups, NewMeshName)
3815         return Mesh(self.smeshpyD,self.geompyD,mesh)
3816
3817     ## Creates a symmetrical copy of the object
3818     #  @param theObject mesh, submesh or group
3819     #  @param Mirror AxisStruct or geom object (point, line, plane)
3820     #  @param theMirrorType is  POINT, AXIS or PLANE
3821     #  If the Mirror is a geom object this parameter is unnecessary
3822     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3823     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3824     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3825     #  @ingroup l2_modif_trsf
3826     def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3827         if ( isinstance( theObject, Mesh )):
3828             theObject = theObject.GetMesh()
3829         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3830             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3831         self.mesh.SetParameters(Mirror.parameters)
3832         if Copy and MakeGroups:
3833             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3834         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3835         return []
3836
3837     ## Creates a new mesh by a symmetrical copy of the object
3838     #  @param theObject mesh, submesh or group
3839     #  @param Mirror AxisStruct or geom object (point, line, plane)
3840     #  @param theMirrorType POINT, AXIS or PLANE
3841     #  If the Mirror is a geom object this parameter is unnecessary
3842     #  @param MakeGroups forces the generation of new groups from existing ones
3843     #  @param NewMeshName the name of the new mesh to create
3844     #  @return instance of Mesh class
3845     #  @ingroup l2_modif_trsf
3846     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3847         if ( isinstance( theObject, Mesh )):
3848             theObject = theObject.GetMesh()
3849         if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3850             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3851         self.mesh.SetParameters(Mirror.parameters)
3852         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3853                                                 MakeGroups, NewMeshName)
3854         return Mesh( self.smeshpyD,self.geompyD,mesh )
3855
3856     ## Translates the elements
3857     #  @param IDsOfElements list of elements ids
3858     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3859     #  @param Copy allows copying the translated elements
3860     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3861     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3862     #  @ingroup l2_modif_trsf
3863     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
3864         if IDsOfElements == []:
3865             IDsOfElements = self.GetElementsId()
3866         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3867             Vector = self.smeshpyD.GetDirStruct(Vector)
3868         if isinstance( Vector, list ):
3869             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3870         self.mesh.SetParameters(Vector.PS.parameters)
3871         if Copy and MakeGroups:
3872             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
3873         self.editor.Translate(IDsOfElements, Vector, Copy)
3874         return []
3875
3876     ## Creates a new mesh of translated elements
3877     #  @param IDsOfElements list of elements ids
3878     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3879     #  @param MakeGroups forces the generation of new groups from existing ones
3880     #  @param NewMeshName the name of the newly created mesh
3881     #  @return instance of Mesh class
3882     #  @ingroup l2_modif_trsf
3883     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
3884         if IDsOfElements == []:
3885             IDsOfElements = self.GetElementsId()
3886         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3887             Vector = self.smeshpyD.GetDirStruct(Vector)
3888         if isinstance( Vector, list ):
3889             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3890         self.mesh.SetParameters(Vector.PS.parameters)
3891         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
3892         return Mesh ( self.smeshpyD, self.geompyD, mesh )
3893
3894     ## Translates the object
3895     #  @param theObject the object to translate (mesh, submesh, or group)
3896     #  @param Vector direction of translation (DirStruct or geom 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 TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
3902         if ( isinstance( theObject, Mesh )):
3903             theObject = theObject.GetMesh()
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.TranslateObjectMakeGroups(theObject, Vector)
3911         self.editor.TranslateObject(theObject, Vector, Copy)
3912         return []
3913
3914     ## Creates a new mesh from the translated object
3915     #  @param theObject the object to translate (mesh, submesh, or group)
3916     #  @param Vector the direction of translation (DirStruct or geom 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 TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
3922         if isinstance( theObject, Mesh ):
3923             theObject = theObject.GetMesh()
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.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
3930         return Mesh( self.smeshpyD, self.geompyD, mesh )
3931
3932
3933
3934     ## Scales the object
3935     #  @param theObject - the object to translate (mesh, submesh, or group)
3936     #  @param thePoint - base point for scale
3937     #  @param theScaleFact - list of 1-3 scale factors for axises
3938     #  @param Copy - allows copying the translated elements
3939     #  @param MakeGroups - forces the generation of new groups from existing
3940     #                      ones (if Copy)
3941     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
3942     #          empty list otherwise
3943     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
3944         unRegister = genObjUnRegister()
3945         if ( isinstance( theObject, Mesh )):
3946             theObject = theObject.GetMesh()
3947         if ( isinstance( theObject, list )):
3948             theObject = self.GetIDSource(theObject, SMESH.ALL)
3949             unRegister.set( theObject )
3950         if ( isinstance( theScaleFact, float )):
3951              theScaleFact = [theScaleFact]
3952         if ( isinstance( theScaleFact, int )):
3953              theScaleFact = [ float(theScaleFact)]
3954
3955         self.mesh.SetParameters(thePoint.parameters)
3956
3957         if Copy and MakeGroups:
3958             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
3959         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
3960         return []
3961
3962     ## Creates a new mesh from the translated object
3963     #  @param theObject - the object to translate (mesh, submesh, or group)
3964     #  @param thePoint - base point for scale
3965     #  @param theScaleFact - list of 1-3 scale factors for axises
3966     #  @param MakeGroups - forces the generation of new groups from existing ones
3967     #  @param NewMeshName - the name of the newly created mesh
3968     #  @return instance of Mesh class
3969     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
3970         unRegister = genObjUnRegister()
3971         if (isinstance(theObject, Mesh)):
3972             theObject = theObject.GetMesh()
3973         if ( isinstance( theObject, list )):
3974             theObject = self.GetIDSource(theObject,SMESH.ALL)
3975             unRegister.set( theObject )
3976         if ( isinstance( theScaleFact, float )):
3977              theScaleFact = [theScaleFact]
3978         if ( isinstance( theScaleFact, int )):
3979              theScaleFact = [ float(theScaleFact)]
3980
3981         self.mesh.SetParameters(thePoint.parameters)
3982         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
3983                                          MakeGroups, NewMeshName)
3984         return Mesh( self.smeshpyD, self.geompyD, mesh )
3985
3986
3987
3988     ## Rotates the elements
3989     #  @param IDsOfElements list of elements ids
3990     #  @param Axis the axis of rotation (AxisStruct or geom line)
3991     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3992     #  @param Copy allows copying the rotated elements
3993     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3994     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3995     #  @ingroup l2_modif_trsf
3996     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
3997         if IDsOfElements == []:
3998             IDsOfElements = self.GetElementsId()
3999         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4000             Axis = self.smeshpyD.GetAxisStruct(Axis)
4001         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4002         Parameters = Axis.parameters + var_separator + Parameters
4003         self.mesh.SetParameters(Parameters)
4004         if Copy and MakeGroups:
4005             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4006         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4007         return []
4008
4009     ## Creates a new mesh of rotated elements
4010     #  @param IDsOfElements list of element ids
4011     #  @param Axis the axis of rotation (AxisStruct or geom line)
4012     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4013     #  @param MakeGroups forces the generation of new groups from existing ones
4014     #  @param NewMeshName the name of the newly created mesh
4015     #  @return instance of Mesh class
4016     #  @ingroup l2_modif_trsf
4017     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4018         if IDsOfElements == []:
4019             IDsOfElements = self.GetElementsId()
4020         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4021             Axis = self.smeshpyD.GetAxisStruct(Axis)
4022         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4023         Parameters = Axis.parameters + var_separator + Parameters
4024         self.mesh.SetParameters(Parameters)
4025         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4026                                           MakeGroups, NewMeshName)
4027         return Mesh( self.smeshpyD, self.geompyD, mesh )
4028
4029     ## Rotates the object
4030     #  @param theObject the object to rotate( mesh, submesh, or group)
4031     #  @param Axis the axis of rotation (AxisStruct or geom line)
4032     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4033     #  @param Copy allows copying the rotated elements
4034     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4035     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4036     #  @ingroup l2_modif_trsf
4037     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4038         if (isinstance(theObject, Mesh)):
4039             theObject = theObject.GetMesh()
4040         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4041             Axis = self.smeshpyD.GetAxisStruct(Axis)
4042         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4043         Parameters = Axis.parameters + ":" + Parameters
4044         self.mesh.SetParameters(Parameters)
4045         if Copy and MakeGroups:
4046             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4047         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4048         return []
4049
4050     ## Creates a new mesh from the rotated object
4051     #  @param theObject the object to rotate (mesh, submesh, or group)
4052     #  @param Axis the axis of rotation (AxisStruct or geom line)
4053     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
4054     #  @param MakeGroups forces the generation of new groups from existing ones
4055     #  @param NewMeshName the name of the newly created mesh
4056     #  @return instance of Mesh class
4057     #  @ingroup l2_modif_trsf
4058     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4059         if (isinstance( theObject, Mesh )):
4060             theObject = theObject.GetMesh()
4061         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4062             Axis = self.smeshpyD.GetAxisStruct(Axis)
4063         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4064         Parameters = Axis.parameters + ":" + Parameters
4065         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4066                                                        MakeGroups, NewMeshName)
4067         self.mesh.SetParameters(Parameters)
4068         return Mesh( self.smeshpyD, self.geompyD, mesh )
4069
4070     ## Finds groups of ajacent nodes within Tolerance.
4071     #  @param Tolerance the value of tolerance
4072     #  @return the list of groups of nodes
4073     #  @ingroup l2_modif_trsf
4074     def FindCoincidentNodes (self, Tolerance):
4075         return self.editor.FindCoincidentNodes(Tolerance)
4076
4077     ## Finds groups of ajacent nodes within Tolerance.
4078     #  @param Tolerance the value of tolerance
4079     #  @param SubMeshOrGroup SubMesh or Group
4080     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4081     #  @return the list of groups of nodes
4082     #  @ingroup l2_modif_trsf
4083     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4084         unRegister = genObjUnRegister()
4085         if (isinstance( SubMeshOrGroup, Mesh )):
4086             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4087         if not isinstance( exceptNodes, list):
4088             exceptNodes = [ exceptNodes ]
4089         if exceptNodes and isinstance( exceptNodes[0], int):
4090             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4091             unRegister.set( exceptNodes )
4092         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4093
4094     ## Merges nodes
4095     #  @param GroupsOfNodes the list of groups of nodes
4096     #  @ingroup l2_modif_trsf
4097     def MergeNodes (self, GroupsOfNodes):
4098         self.editor.MergeNodes(GroupsOfNodes)
4099
4100     ## Finds the elements built on the same nodes.
4101     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4102     #  @return a list of groups of equal elements
4103     #  @ingroup l2_modif_trsf
4104     def FindEqualElements (self, MeshOrSubMeshOrGroup):
4105         if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4106             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4107         return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4108
4109     ## Merges elements in each given group.
4110     #  @param GroupsOfElementsID groups of elements for merging
4111     #  @ingroup l2_modif_trsf
4112     def MergeElements(self, GroupsOfElementsID):
4113         self.editor.MergeElements(GroupsOfElementsID)
4114
4115     ## Leaves one element and removes all other elements built on the same nodes.
4116     #  @ingroup l2_modif_trsf
4117     def MergeEqualElements(self):
4118         self.editor.MergeEqualElements()
4119
4120     ## Sews free borders
4121     #  @return SMESH::Sew_Error
4122     #  @ingroup l2_modif_trsf
4123     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4124                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4125                         CreatePolygons, CreatePolyedrs):
4126         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4127                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4128                                           CreatePolygons, CreatePolyedrs)
4129
4130     ## Sews conform free borders
4131     #  @return SMESH::Sew_Error
4132     #  @ingroup l2_modif_trsf
4133     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4134                                FirstNodeID2, SecondNodeID2):
4135         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4136                                                  FirstNodeID2, SecondNodeID2)
4137
4138     ## Sews border to side
4139     #  @return SMESH::Sew_Error
4140     #  @ingroup l2_modif_trsf
4141     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4142                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4143         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4144                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4145
4146     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4147     #  merged with the nodes of elements of Side2.
4148     #  The number of elements in theSide1 and in theSide2 must be
4149     #  equal and they should have similar nodal connectivity.
4150     #  The nodes to merge should belong to side borders and
4151     #  the first node should be linked to the second.
4152     #  @return SMESH::Sew_Error
4153     #  @ingroup l2_modif_trsf
4154     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4155                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4156                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4157         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4158                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4159                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4160
4161     ## Sets new nodes for the given element.
4162     #  @param ide the element id
4163     #  @param newIDs nodes ids
4164     #  @return If the number of nodes does not correspond to the type of element - returns false
4165     #  @ingroup l2_modif_edit
4166     def ChangeElemNodes(self, ide, newIDs):
4167         return self.editor.ChangeElemNodes(ide, newIDs)
4168
4169     ## If during the last operation of MeshEditor some nodes were
4170     #  created, this method returns the list of their IDs, \n
4171     #  if new nodes were not created - returns empty list
4172     #  @return the list of integer values (can be empty)
4173     #  @ingroup l1_auxiliary
4174     def GetLastCreatedNodes(self):
4175         return self.editor.GetLastCreatedNodes()
4176
4177     ## If during the last operation of MeshEditor some elements were
4178     #  created this method returns the list of their IDs, \n
4179     #  if new elements were not created - returns empty list
4180     #  @return the list of integer values (can be empty)
4181     #  @ingroup l1_auxiliary
4182     def GetLastCreatedElems(self):
4183         return self.editor.GetLastCreatedElems()
4184
4185     ## Clears sequences of nodes and elements created by mesh edition oparations
4186     #  @ingroup l1_auxiliary
4187     def ClearLastCreated(self):
4188         self.editor.ClearLastCreated()
4189
4190     ## Creates Duplicates given elements, i.e. creates new elements based on the 
4191     #  same nodes as the given ones.
4192     #  @param theElements - container of elements to duplicate. It can be a Mesh,
4193     #         sub-mesh, group, filter or a list of element IDs.
4194     # @param theGroupName - a name of group to contain the generated elements.
4195     #                    If a group with such a name already exists, the new elements
4196     #                    are added to the existng group, else a new group is created.
4197     #                    If \a theGroupName is empty, new elements are not added 
4198     #                    in any group.
4199     # @return a group where the new elements are added. None if theGroupName == "".
4200     #  @ingroup l2_modif_edit
4201     def DoubleElements(self, theElements, theGroupName=""):
4202         unRegister = genObjUnRegister()
4203         if isinstance( theElements, Mesh ):
4204             theElements = theElements.mesh
4205         elif isinstance( theElements, list ):
4206             theElements = self.GetIDSource( theElements, SMESH.ALL )
4207             unRegister.set( theElements )
4208         return self.editor.DoubleElements(theElements, theGroupName)
4209
4210     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4211     #  @param theNodes identifiers of nodes to be doubled
4212     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4213     #         nodes. If list of element identifiers is empty then nodes are doubled but
4214     #         they not assigned to elements
4215     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4216     #  @ingroup l2_modif_edit
4217     def DoubleNodes(self, theNodes, theModifiedElems):
4218         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4219
4220     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4221     #  This method provided for convenience works as DoubleNodes() described above.
4222     #  @param theNodeId identifiers of node to be doubled
4223     #  @param theModifiedElems identifiers of elements to be updated
4224     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4225     #  @ingroup l2_modif_edit
4226     def DoubleNode(self, theNodeId, theModifiedElems):
4227         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4228
4229     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4230     #  This method provided for convenience works as DoubleNodes() described above.
4231     #  @param theNodes group of nodes to be doubled
4232     #  @param theModifiedElems group of elements to be updated.
4233     #  @param theMakeGroup forces the generation of a group containing new nodes.
4234     #  @return TRUE or a created group if operation has been completed successfully,
4235     #          FALSE or None otherwise
4236     #  @ingroup l2_modif_edit
4237     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4238         if theMakeGroup:
4239             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4240         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4241
4242     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4243     #  This method provided for convenience works as DoubleNodes() described above.
4244     #  @param theNodes list of groups of nodes to be doubled
4245     #  @param theModifiedElems list of groups of elements to be updated.
4246     #  @param theMakeGroup forces the generation of a group containing new nodes.
4247     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4248     #  @ingroup l2_modif_edit
4249     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4250         if theMakeGroup:
4251             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4252         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4253
4254     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4255     #  @param theElems - the list of elements (edges or faces) to be replicated
4256     #         The nodes for duplication could be found from these elements
4257     #  @param theNodesNot - list of nodes to NOT replicate
4258     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4259     #         replicated nodes should be associated to.
4260     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4261     #  @ingroup l2_modif_edit
4262     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4263         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4264
4265     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4266     #  @param theElems - the list of elements (edges or faces) to be replicated
4267     #         The nodes for duplication could be found from these elements
4268     #  @param theNodesNot - list of nodes to NOT replicate
4269     #  @param theShape - shape to detect affected elements (element which geometric center
4270     #         located on or inside shape).
4271     #         The replicated nodes should be associated to affected elements.
4272     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4273     #  @ingroup l2_modif_edit
4274     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4275         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4276
4277     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4278     #  This method provided for convenience works as DoubleNodes() described above.
4279     #  @param theElems - group of of elements (edges or faces) to be replicated
4280     #  @param theNodesNot - group of nodes not to replicated
4281     #  @param theAffectedElems - group of elements to which the replicated nodes
4282     #         should be associated to.
4283     #  @param theMakeGroup forces the generation of a group containing new elements.
4284     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4285     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4286     #          FALSE or None otherwise
4287     #  @ingroup l2_modif_edit
4288     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4289                              theMakeGroup=False, theMakeNodeGroup=False):
4290         if theMakeGroup or theMakeNodeGroup:
4291             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4292                                                             theAffectedElems,
4293                                                             theMakeGroup, theMakeNodeGroup)
4294             if theMakeGroup and theMakeNodeGroup:
4295                 return twoGroups
4296             else:
4297                 return twoGroups[ int(theMakeNodeGroup) ]
4298         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4299
4300     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4301     #  This method provided for convenience works as DoubleNodes() described above.
4302     #  @param theElems - group of of elements (edges or faces) to be replicated
4303     #  @param theNodesNot - group of nodes not to replicated
4304     #  @param theShape - shape to detect affected elements (element which geometric center
4305     #         located on or inside shape).
4306     #         The replicated nodes should be associated to affected elements.
4307     #  @ingroup l2_modif_edit
4308     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4309         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4310
4311     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4312     #  This method provided for convenience works as DoubleNodes() described above.
4313     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4314     #  @param theNodesNot - list of groups of nodes not to replicated
4315     #  @param theAffectedElems - group of elements to which the replicated nodes
4316     #         should be associated to.
4317     #  @param theMakeGroup forces the generation of a group containing new elements.
4318     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4319     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4320     #          FALSE or None otherwise
4321     #  @ingroup l2_modif_edit
4322     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4323                              theMakeGroup=False, theMakeNodeGroup=False):
4324         if theMakeGroup or theMakeNodeGroup:
4325             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4326                                                              theAffectedElems,
4327                                                              theMakeGroup, theMakeNodeGroup)
4328             if theMakeGroup and theMakeNodeGroup:
4329                 return twoGroups
4330             else:
4331                 return twoGroups[ int(theMakeNodeGroup) ]
4332         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4333
4334     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4335     #  This method provided for convenience works as DoubleNodes() described above.
4336     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4337     #  @param theNodesNot - list of groups of nodes not to replicated
4338     #  @param theShape - shape to detect affected elements (element which geometric center
4339     #         located on or inside shape).
4340     #         The replicated nodes should be associated to affected elements.
4341     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4342     #  @ingroup l2_modif_edit
4343     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4344         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4345
4346     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4347     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4348     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4349     #  @param theNodesNot - list of groups of nodes not to replicated
4350     #  @param theShape - shape to detect affected elements (element which geometric center
4351     #         located on or inside shape).
4352     #         The replicated nodes should be associated to affected elements.
4353     #  @return groups of affected elements
4354     #  @ingroup l2_modif_edit
4355     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4356         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4357
4358     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4359     # The list of groups must describe a partition of the mesh volumes.
4360     # The nodes of the internal faces at the boundaries of the groups are doubled.
4361     # In option, the internal faces are replaced by flat elements.
4362     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4363     # @param theDomains - list of groups of volumes
4364     # @param createJointElems - if TRUE, create the elements
4365     # @return TRUE if operation has been completed successfully, FALSE otherwise
4366     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
4367        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
4368
4369     ## Double nodes on some external faces and create flat elements.
4370     # Flat elements are mainly used by some types of mechanic calculations.
4371     #
4372     # Each group of the list must be constituted of faces.
4373     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4374     # @param theGroupsOfFaces - list of groups of faces
4375     # @return TRUE if operation has been completed successfully, FALSE otherwise
4376     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4377         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4378     
4379     ## identify all the elements around a geom shape, get the faces delimiting the hole
4380     #
4381     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4382         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4383
4384     def _getFunctor(self, funcType ):
4385         fn = self.functors[ funcType._v ]
4386         if not fn:
4387             fn = self.smeshpyD.GetFunctor(funcType)
4388             fn.SetMesh(self.mesh)
4389             self.functors[ funcType._v ] = fn
4390         return fn
4391
4392     def _valueFromFunctor(self, funcType, elemId):
4393         fn = self._getFunctor( funcType )
4394         if fn.GetElementType() == self.GetElementType(elemId, True):
4395             val = fn.GetValue(elemId)
4396         else:
4397             val = 0
4398         return val
4399
4400     ## Get length of 1D element.
4401     #  @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4402     #  @return element's length value
4403     #  @ingroup l1_measurements
4404     def GetLength(self, elemId=None):
4405         length = 0
4406         if elemId == None:
4407             aMeasurements = self.smeshpyD.CreateMeasurements()
4408             length = aMeasurements.Length(self.GetMesh())
4409             aMeasurements.UnRegister()
4410         else:
4411             length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4412         return length
4413
4414     ## Get area of 2D element.
4415     #  @param elemId mesh element ID (if not defined - sum of area of all 2D elements will be calculated)
4416     #  @return element's area value
4417     #  @ingroup l1_measurements
4418     def GetArea(self, elemId=None):
4419         area = 0
4420         if elemId == None:
4421             aMeasurements = self.smeshpyD.CreateMeasurements()
4422             area = aMeasurements.Area(self.GetMesh())
4423             aMeasurements.UnRegister()
4424         else:
4425             area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4426         return area
4427
4428     ## Get volume of 3D element.
4429     #  @param elemId mesh element ID (if not defined - sum of volume of all 3D elements will be calculated)
4430     #  @return element's volume value
4431     #  @ingroup l1_measurements
4432     def GetVolume(self, elemId=None):
4433         volume = 0
4434         if elemId == None:
4435             aMeasurements = self.smeshpyD.CreateMeasurements()
4436             volume = aMeasurements.Volume(self.GetMesh())
4437             aMeasurements.UnRegister()
4438         else:
4439             volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4440         return volume
4441
4442     ## Get maximum element length.
4443     #  @param elemId mesh element ID
4444     #  @return element's maximum length value
4445     #  @ingroup l1_measurements
4446     def GetMaxElementLength(self, elemId):
4447         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4448             ftype = SMESH.FT_MaxElementLength3D
4449         else:
4450             ftype = SMESH.FT_MaxElementLength2D
4451         return self._valueFromFunctor(ftype, elemId)
4452
4453     ## Get aspect ratio of 2D or 3D element.
4454     #  @param elemId mesh element ID
4455     #  @return element's aspect ratio value
4456     #  @ingroup l1_measurements
4457     def GetAspectRatio(self, elemId):
4458         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4459             ftype = SMESH.FT_AspectRatio3D
4460         else:
4461             ftype = SMESH.FT_AspectRatio
4462         return self._valueFromFunctor(ftype, elemId)
4463
4464     ## Get warping angle of 2D element.
4465     #  @param elemId mesh element ID
4466     #  @return element's warping angle value
4467     #  @ingroup l1_measurements
4468     def GetWarping(self, elemId):
4469         return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4470
4471     ## Get minimum angle of 2D element.
4472     #  @param elemId mesh element ID
4473     #  @return element's minimum angle value
4474     #  @ingroup l1_measurements
4475     def GetMinimumAngle(self, elemId):
4476         return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4477
4478     ## Get taper of 2D element.
4479     #  @param elemId mesh element ID
4480     #  @return element's taper value
4481     #  @ingroup l1_measurements
4482     def GetTaper(self, elemId):
4483         return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4484
4485     ## Get skew of 2D element.
4486     #  @param elemId mesh element ID
4487     #  @return element's skew value
4488     #  @ingroup l1_measurements
4489     def GetSkew(self, elemId):
4490         return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4491
4492     pass # end of Mesh class
4493     
4494 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4495 #
4496 class Pattern(SMESH._objref_SMESH_Pattern):
4497
4498     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4499         decrFun = lambda i: i-1
4500         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4501         theMesh.SetParameters(Parameters)
4502         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4503
4504     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4505         decrFun = lambda i: i-1
4506         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4507         theMesh.SetParameters(Parameters)
4508         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4509
4510 # Registering the new proxy for Pattern
4511 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4512
4513 ## Private class used to bind methods creating algorithms to the class Mesh
4514 #
4515 class algoCreator:
4516     def __init__(self):
4517         self.mesh = None
4518         self.defaultAlgoType = ""
4519         self.algoTypeToClass = {}
4520
4521     # Stores a python class of algorithm
4522     def add(self, algoClass):
4523         if type( algoClass ).__name__ == 'classobj' and \
4524            hasattr( algoClass, "algoType"):
4525             self.algoTypeToClass[ algoClass.algoType ] = algoClass
4526             if not self.defaultAlgoType and \
4527                hasattr( algoClass, "isDefault") and algoClass.isDefault:
4528                 self.defaultAlgoType = algoClass.algoType
4529             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4530
4531     # creates a copy of self and assign mesh to the copy
4532     def copy(self, mesh):
4533         other = algoCreator()
4534         other.defaultAlgoType = self.defaultAlgoType
4535         other.algoTypeToClass  = self.algoTypeToClass
4536         other.mesh = mesh
4537         return other
4538
4539     # creates an instance of algorithm
4540     def __call__(self,algo="",geom=0,*args):
4541         algoType = self.defaultAlgoType
4542         for arg in args + (algo,geom):
4543             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4544                 geom = arg
4545             if isinstance( arg, str ) and arg:
4546                 algoType = arg
4547         if not algoType and self.algoTypeToClass:
4548             algoType = self.algoTypeToClass.keys()[0]
4549         if self.algoTypeToClass.has_key( algoType ):
4550             #print "Create algo",algoType
4551             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4552         raise RuntimeError, "No class found for algo type %s" % algoType
4553         return None
4554
4555 # Private class used to substitute and store variable parameters of hypotheses.
4556 #
4557 class hypMethodWrapper:
4558     def __init__(self, hyp, method):
4559         self.hyp    = hyp
4560         self.method = method
4561         #print "REBIND:", method.__name__
4562         return
4563
4564     # call a method of hypothesis with calling SetVarParameter() before
4565     def __call__(self,*args):
4566         if not args:
4567             return self.method( self.hyp, *args ) # hypothesis method with no args
4568
4569         #print "MethWrapper.__call__",self.method.__name__, args
4570         try:
4571             parsed = ParseParameters(*args)     # replace variables with their values
4572             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4573             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4574         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4575             # maybe there is a replaced string arg which is not variable
4576             result = self.method( self.hyp, *args )
4577         except ValueError, detail: # raised by ParseParameters()
4578             try:
4579                 result = self.method( self.hyp, *args )
4580             except omniORB.CORBA.BAD_PARAM:
4581                 raise ValueError, detail # wrong variable name
4582
4583         return result
4584     pass
4585
4586 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4587 class genObjUnRegister:
4588
4589     def __init__(self, genObj=None):
4590         self.genObjList = []
4591         self.set( genObj )
4592         return
4593
4594     def set(self, genObj):
4595         "Store one or a list of of SALOME.GenericObj'es"
4596         if isinstance( genObj, list ):
4597             self.genObjList.extend( genObj )
4598         else:
4599             self.genObjList.append( genObj )
4600         return
4601
4602     def __del__(self):
4603         for genObj in self.genObjList:
4604             if genObj and hasattr( genObj, "UnRegister" ):
4605                 genObj.UnRegister()
4606
4607 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4608     #
4609     #print "pluginName: ", pluginName
4610     pluginBuilderName = pluginName + "Builder"
4611     try:
4612         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4613     except Exception, e:
4614         print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4615         continue
4616     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4617     plugin = eval( pluginBuilderName )
4618     #print "  plugin:" , str(plugin)
4619
4620     # add methods creating algorithms to Mesh
4621     for k in dir( plugin ):
4622         if k[0] == '_': continue
4623         algo = getattr( plugin, k )
4624         #print "             algo:", str(algo)
4625         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4626             #print "                     meshMethod:" , str(algo.meshMethod)
4627             if not hasattr( Mesh, algo.meshMethod ):
4628                 setattr( Mesh, algo.meshMethod, algoCreator() )
4629                 pass
4630             getattr( Mesh, algo.meshMethod ).add( algo )
4631             pass
4632         pass
4633     pass
4634 del pluginName