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