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