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