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