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