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