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