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