Salome HOME
in Mesh.Compute(), report hypothesis errors even if compute() returns OK
[modules/smesh.git] / src / SMESH_SWIG / smeshDC.py
1 #  Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
3 #
4 #  This library is free software; you can redistribute it and/or
5 #  modify it under the terms of the GNU Lesser General Public
6 #  License as published by the Free Software Foundation; either
7 #  version 2.1 of the License.
8 #
9 #  This library is distributed in the hope that it will be useful,
10 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 #  Lesser General Public License for more details.
13 #
14 #  You should have received a copy of the GNU Lesser General Public
15 #  License along with this library; if not, write to the Free Software
16 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 #  File   : smesh.py
21 #  Author : Francis KLOSS, OCC
22 #  Module : SMESH
23
24 """
25  \namespace smesh
26  \brief Module smesh
27 """
28
29 ## \package smeshDC
30 #  To get started, please, have a look at smeshDC::smeshDC documentation
31 #  for general services of smesh package
32 #  You can also find the smeshDC::smeshDC documentation by the first
33 #  item in the Data Structures list on this page.
34 #  See also the list of Data Structures and the list of Functions
35 #  for other classes and methods of smesh python interface.
36
37
38 import salome
39 import geompyDC
40
41 import SMESH # This is necessary for back compatibility
42 from   SMESH import *
43
44 import StdMeshers
45
46 import SALOME
47
48 # import NETGENPlugin module if possible
49 noNETGENPlugin = 0
50 try:
51     import NETGENPlugin
52 except ImportError:
53     noNETGENPlugin = 1
54     pass
55
56 # Types of algorithms
57 REGULAR    = 1
58 PYTHON     = 2
59 COMPOSITE  = 3
60
61 MEFISTO       = 3
62 NETGEN        = 4
63 GHS3D         = 5
64 FULL_NETGEN   = 6
65 NETGEN_2D     = 7
66 NETGEN_1D2D   = NETGEN
67 NETGEN_1D2D3D = FULL_NETGEN
68 NETGEN_FULL   = FULL_NETGEN
69 Hexa    = 8
70 Hexotic = 9
71 BLSURF  = 10
72
73 # MirrorType enumeration
74 POINT = SMESH_MeshEditor.POINT
75 AXIS =  SMESH_MeshEditor.AXIS
76 PLANE = SMESH_MeshEditor.PLANE
77
78 # Smooth_Method enumeration
79 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
80 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
81
82 # Fineness enumeration (for NETGEN)
83 VeryCoarse = 0
84 Coarse     = 1
85 Moderate   = 2
86 Fine       = 3
87 VeryFine   = 4
88 Custom     = 5
89
90 # Optimization level of GHS3D
91 None_Optimization, Light_Optimization, Medium_Optimization, Strong_Optimization = 0,1,2,3
92
93 # Topology treatment way of BLSURF
94 FromCAD, PreProcess, PreProcessPlus = 0,1,2
95
96 # Element size flag of BLSURF
97 DefaultSize, DefaultGeom, Custom = 0,0,1
98
99 PrecisionConfusion = 1e-07
100
101 def IsEqual(val1, val2, tol=PrecisionConfusion):
102     if abs(val1 - val2) < tol:
103         return True
104     return False
105
106 NO_NAME = "NoName"
107
108 ## Gets object name
109 def GetName(obj):
110     ior  = salome.orb.object_to_string(obj)
111     sobj = salome.myStudy.FindObjectIOR(ior)
112     if sobj is None:
113         return NO_NAME
114     else:
115         attr = sobj.FindAttribute("AttributeName")[1]
116         return attr.Value()
117
118 ## Sets a name to the object
119 def SetName(obj, name):
120     ior  = salome.orb.object_to_string(obj)
121     sobj = salome.myStudy.FindObjectIOR(ior)
122     if not sobj is None:
123         attr = sobj.FindAttribute("AttributeName")[1]
124         attr.SetValue(name)
125
126 ## Prints error message if a hypothesis was not assigned.
127 def TreatHypoStatus(status, hypName, geomName, isAlgo):
128     if isAlgo:
129         hypType = "algorithm"
130     else:
131         hypType = "hypothesis"
132         pass
133     if status == HYP_UNKNOWN_FATAL :
134         reason = "for unknown reason"
135     elif status == HYP_INCOMPATIBLE :
136         reason = "this hypothesis mismatches the algorithm"
137     elif status == HYP_NOTCONFORM :
138         reason = "a non-conform mesh would be built"
139     elif status == HYP_ALREADY_EXIST :
140         reason = hypType + " of the same dimension is already assigned to this shape"
141     elif status == HYP_BAD_DIM :
142         reason = hypType + " mismatches the shape"
143     elif status == HYP_CONCURENT :
144         reason = "there are concurrent hypotheses on sub-shapes"
145     elif status == HYP_BAD_SUBSHAPE :
146         reason = "the shape is neither the main one, nor its subshape, nor a valid group"
147     elif status == HYP_BAD_GEOMETRY:
148         reason = "geometry mismatches the expectation of the algorithm"
149     elif status == HYP_HIDDEN_ALGO:
150         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
151     elif status == HYP_HIDING_ALGO:
152         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
153     else:
154         return
155     hypName = '"' + hypName + '"'
156     geomName= '"' + geomName+ '"'
157     if status < HYP_UNKNOWN_FATAL:
158         print hypName, "was assigned to",    geomName,"but", reason
159     else:
160         print hypName, "was not assigned to",geomName,":", reason
161         pass
162
163 ## Converts an angle from degrees to radians
164 def DegreesToRadians(AngleInDegrees):
165     from math import pi
166     return AngleInDegrees * pi / 180.0
167
168 ## Methods of the package smesh.py provide general services of MESH component.
169 #
170 #  All methods of this class are accessible directly from the smesh.py package.
171 #  Use these methods to create an empty mesh, to import the mesh from file,
172 #  and to create patterns and filtering criteria.
173 class smeshDC(SMESH._objref_SMESH_Gen):
174
175     ## Sets the current study and Geometry component
176     def init_smesh(self,theStudy,geompyD):
177         self.geompyD=geompyD
178         self.SetGeomEngine(geompyD)
179         self.SetCurrentStudy(theStudy)
180
181     ## Creates an empty Mesh. This mesh can have an underlying geometry.
182     #  @param obj the Geometrical object on which the mesh is built. If not defined,
183     #             the mesh will have no underlying geometry.
184     #  @param name the name for the new mesh.
185     #  @return an instance of Mesh class.
186     def Mesh(self, obj=0, name=0):
187       return Mesh(self,self.geompyD,obj,name)
188
189     ## Returns a long value from enumeration
190     #  Should be used for SMESH.FunctorType enumeration
191     def EnumToLong(self,theItem):
192         return theItem._v
193
194     ## Gets PointStruct from vertex
195     #  @param theVertex a GEOM object(vertex)
196     #  @return SMESH.PointStruct
197     def GetPointStruct(self,theVertex):
198         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
199         return PointStruct(x,y,z)
200
201     ## Gets DirStruct from vector
202     #  @param theVector a GEOM object(vector)
203     #  @return SMESH.DirStruct
204     def GetDirStruct(self,theVector):
205         vertices = self.geompyD.SubShapeAll( theVector, geompyDC.ShapeType["VERTEX"] )
206         if(len(vertices) != 2):
207             print "Error: vector object is incorrect."
208             return None
209         p1 = self.geompyD.PointCoordinates(vertices[0])
210         p2 = self.geompyD.PointCoordinates(vertices[1])
211         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
212         dirst = DirStruct(pnt)
213         return dirst
214
215     ## Makes DirStruct from a triplet
216     #  @param x,y,z vector components
217     #  @return SMESH.DirStruct
218     def MakeDirStruct(self,x,y,z):
219         pnt = PointStruct(x,y,z)
220         return DirStruct(pnt)
221
222     ## Get AxisStruct from object
223     #  @param theObj a GEOM object (line or plane)
224     #  @return SMESH.AxisStruct
225     def GetAxisStruct(self,theObj):
226         edges = self.geompyD.SubShapeAll( theObj, geompyDC.ShapeType["EDGE"] )
227         if len(edges) > 1:
228             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geompyDC.ShapeType["VERTEX"] )
229             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geompyDC.ShapeType["VERTEX"] )
230             vertex1 = self.geompyD.PointCoordinates(vertex1)
231             vertex2 = self.geompyD.PointCoordinates(vertex2)
232             vertex3 = self.geompyD.PointCoordinates(vertex3)
233             vertex4 = self.geompyD.PointCoordinates(vertex4)
234             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
235             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
236             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] ]
237             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
238             return axis
239         elif len(edges) == 1:
240             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geompyDC.ShapeType["VERTEX"] )
241             p1 = self.geompyD.PointCoordinates( vertex1 )
242             p2 = self.geompyD.PointCoordinates( vertex2 )
243             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
244             return axis
245         return None
246
247     # From SMESH_Gen interface:
248     # ------------------------
249
250     ## Sets the current mode
251     def SetEmbeddedMode( self,theMode ):
252         #self.SetEmbeddedMode(theMode)
253         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
254
255     ## Gets the current mode
256     def IsEmbeddedMode(self):
257         #return self.IsEmbeddedMode()
258         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
259
260     ## Sets the current study
261     def SetCurrentStudy( self, theStudy ):
262         #self.SetCurrentStudy(theStudy)
263         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
264
265     ## Gets the current study
266     def GetCurrentStudy(self):
267         #return self.GetCurrentStudy()
268         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
269
270     ## Creates a Mesh object importing data from the given UNV file
271     #  @return an instance of Mesh class
272     def CreateMeshesFromUNV( self,theFileName ):
273         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
274         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
275         return aMesh
276
277     ## Creates a Mesh object(s) importing data from the given MED file
278     #  @return a list of Mesh class instances
279     def CreateMeshesFromMED( self,theFileName ):
280         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
281         aMeshes = []
282         for iMesh in range(len(aSmeshMeshes)) :
283             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
284             aMeshes.append(aMesh)
285         return aMeshes, aStatus
286
287     ## Creates a Mesh object importing data from the given STL file
288     #  @return an instance of Mesh class
289     def CreateMeshesFromSTL( self, theFileName ):
290         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
291         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
292         return aMesh
293
294     ## From SMESH_Gen interface
295     #  @return the list of integer values
296     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
297         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
298
299     ## From SMESH_Gen interface. Creates a pattern
300     # @return an instance of SMESH_Pattern
301     def GetPattern(self):
302         return SMESH._objref_SMESH_Gen.GetPattern(self)
303
304
305     # Filtering. Auxiliary functions:
306     # ------------------------------
307
308     ## Creates an empty criterion
309     #  @return SMESH.Filter.Criterion
310     def GetEmptyCriterion(self):
311         Type = self.EnumToLong(FT_Undefined)
312         Compare = self.EnumToLong(FT_Undefined)
313         Threshold = 0
314         ThresholdStr = ""
315         ThresholdID = ""
316         UnaryOp = self.EnumToLong(FT_Undefined)
317         BinaryOp = self.EnumToLong(FT_Undefined)
318         Tolerance = 1e-07
319         TypeOfElement = ALL
320         Precision = -1 ##@1e-07
321         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
322                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
323
324     ## Creates a criterion by the given parameters
325     #  @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
326     #  @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
327     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
328     #  @param Treshold the threshold value (range of ids as string, shape, numeric)
329     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
330     #  @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
331     #                  FT_Undefined (must be for the last criterion of all criteria)
332     #  @return SMESH.Filter.Criterion
333     def GetCriterion(self,elementType,
334                      CritType,
335                      Compare = FT_EqualTo,
336                      Treshold="",
337                      UnaryOp=FT_Undefined,
338                      BinaryOp=FT_Undefined):
339         aCriterion = self.GetEmptyCriterion()
340         aCriterion.TypeOfElement = elementType
341         aCriterion.Type = self.EnumToLong(CritType)
342
343         aTreshold = Treshold
344
345         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
346             aCriterion.Compare = self.EnumToLong(Compare)
347         elif Compare == "=" or Compare == "==":
348             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
349         elif Compare == "<":
350             aCriterion.Compare = self.EnumToLong(FT_LessThan)
351         elif Compare == ">":
352             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
353         else:
354             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
355             aTreshold = Compare
356
357         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
358                         FT_BelongToCylinder, FT_LyingOnGeom]:
359             # Checks the treshold
360             if isinstance(aTreshold, geompyDC.GEOM._objref_GEOM_Object):
361                 aCriterion.ThresholdStr = GetName(aTreshold)
362                 aCriterion.ThresholdID = salome.ObjectToID(aTreshold)
363             else:
364                 print "Error: The treshold should be a shape."
365                 return None
366         elif CritType == FT_RangeOfIds:
367             # Checks the treshold
368             if isinstance(aTreshold, str):
369                 aCriterion.ThresholdStr = aTreshold
370             else:
371                 print "Error: The treshold should be a string."
372                 return None
373         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_BadOrientedVolume]:
374             # At this point the treshold is unnecessary
375             if aTreshold ==  FT_LogicalNOT:
376                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
377             elif aTreshold in [FT_LogicalAND, FT_LogicalOR]:
378                 aCriterion.BinaryOp = aTreshold
379         else:
380             # Check treshold
381             try:
382                 aTreshold = float(aTreshold)
383                 aCriterion.Threshold = aTreshold
384             except:
385                 print "Error: The treshold should be a number."
386                 return None
387
388         if Treshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
389             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
390
391         if Treshold in [FT_LogicalAND, FT_LogicalOR]:
392             aCriterion.BinaryOp = self.EnumToLong(Treshold)
393
394         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
395             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
396
397         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
398             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
399
400         return aCriterion
401
402     ## Creates a filter with the given parameters
403     #  @param elementType the type of elements in the group
404     #  @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
405     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
406     #  @param Treshold the threshold value (range of id ids as string, shape, numeric)
407     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
408     #  @return SMESH_Filter
409     def GetFilter(self,elementType,
410                   CritType=FT_Undefined,
411                   Compare=FT_EqualTo,
412                   Treshold="",
413                   UnaryOp=FT_Undefined):
414         aCriterion = self.GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
415         aFilterMgr = self.CreateFilterManager()
416         aFilter = aFilterMgr.CreateFilter()
417         aCriteria = []
418         aCriteria.append(aCriterion)
419         aFilter.SetCriteria(aCriteria)
420         return aFilter
421
422     ## Creates a numerical functor by its type
423     #  @param theCriterion FT_...; functor type
424     #  @return SMESH_NumericalFunctor
425     def GetFunctor(self,theCriterion):
426         aFilterMgr = self.CreateFilterManager()
427         if theCriterion == FT_AspectRatio:
428             return aFilterMgr.CreateAspectRatio()
429         elif theCriterion == FT_AspectRatio3D:
430             return aFilterMgr.CreateAspectRatio3D()
431         elif theCriterion == FT_Warping:
432             return aFilterMgr.CreateWarping()
433         elif theCriterion == FT_MinimumAngle:
434             return aFilterMgr.CreateMinimumAngle()
435         elif theCriterion == FT_Taper:
436             return aFilterMgr.CreateTaper()
437         elif theCriterion == FT_Skew:
438             return aFilterMgr.CreateSkew()
439         elif theCriterion == FT_Area:
440             return aFilterMgr.CreateArea()
441         elif theCriterion == FT_Volume3D:
442             return aFilterMgr.CreateVolume3D()
443         elif theCriterion == FT_MultiConnection:
444             return aFilterMgr.CreateMultiConnection()
445         elif theCriterion == FT_MultiConnection2D:
446             return aFilterMgr.CreateMultiConnection2D()
447         elif theCriterion == FT_Length:
448             return aFilterMgr.CreateLength()
449         elif theCriterion == FT_Length2D:
450             return aFilterMgr.CreateLength2D()
451         else:
452             print "Error: given parameter is not numerucal functor type."
453
454 import omniORB
455 #Registering the new proxy for SMESH_Gen
456 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshDC)
457
458
459 # Public class: Mesh
460 # ==================
461
462 ## This class allows defining and managing a mesh.
463 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
464 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
465 #  new nodes and elements and by changing the existing entities), to get information
466 #  about a mesh and to export a mesh into different formats.
467 class Mesh:
468
469     geom = 0
470     mesh = 0
471     editor = 0
472
473     ## Constructor
474     #
475     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
476     #  sets the GUI name of this mesh to \a name.
477     #  @param obj Shape to be meshed or SMESH_Mesh object
478     #  @param name Study name of the mesh
479     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
480         self.smeshpyD=smeshpyD
481         self.geompyD=geompyD
482         if obj is None:
483             obj = 0
484         if obj != 0:
485             if isinstance(obj, geompyDC.GEOM._objref_GEOM_Object):
486                 self.geom = obj
487                 self.mesh = self.smeshpyD.CreateMesh(self.geom)
488             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
489                 self.SetMesh(obj)
490         else:
491             self.mesh = self.smeshpyD.CreateEmptyMesh()
492         if name != 0:
493             SetName(self.mesh, name)
494         elif obj != 0:
495             SetName(self.mesh, GetName(obj))
496
497         self.editor = self.mesh.GetMeshEditor()
498
499     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
500     #  @param theMesh a SMESH_Mesh object
501     def SetMesh(self, theMesh):
502         self.mesh = theMesh
503         self.geom = self.mesh.GetShapeToMesh()
504
505     ## Returns the mesh, that is an instance of SMESH_Mesh interface
506     #  @return a SMESH_Mesh object
507     def GetMesh(self):
508         return self.mesh
509
510     ## Gets the name of the mesh
511     #  @return the name of the mesh as a string
512     def GetName(self):
513         name = GetName(self.GetMesh())
514         return name
515
516     ## Sets a name to the mesh
517     #  @param name a new name of the mesh
518     def SetName(self, name):
519         SetName(self.GetMesh(), name)
520
521     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
522     #  The subMesh object gives access to the IDs of nodes and elements.
523     #  @param theSubObject a geometrical object (shape)
524     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
525     def GetSubMesh(self, theSubObject, name):
526         submesh = self.mesh.GetSubMesh(theSubObject, name)
527         return submesh
528
529     ## Returns the shape associated to the mesh
530     #  @return a GEOM_Object
531     def GetShape(self):
532         return self.geom
533
534     ## Associates the given shape to the mesh (entails the recreation of the mesh)
535     #  @param geom the shape to be meshed (GEOM_Object)
536     def SetShape(self, geom):
537         self.mesh = self.smeshpyD.CreateMesh(geom)
538
539     ## Returns true if the hypotheses are defined well
540     #  @param theSubObject a subshape of a mesh shape
541     #  @return True or False
542     def IsReadyToCompute(self, theSubObject):
543         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
544
545     ## Returns errors of hypotheses definition.
546     #  The list of errors is empty if everything is OK.
547     #  @param theSubObject a subshape of a mesh shape
548     #  @return a list of errors
549     def GetAlgoState(self, theSubObject):
550         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
551
552     ## Returns a geometrical object on which the given element was built.
553     #  The returned geometrical object, if not nil, is either found in the
554     #  study or published by this method with the given name
555     #  @param theElementID the id of the mesh element
556     #  @param theGeomName the user-defined name of the geometrical object
557     #  @return GEOM::GEOM_Object instance
558     def GetGeometryByMeshElement(self, theElementID, theGeomName):
559         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
560
561     ## Returns the mesh dimension depending on the dimension of the underlying shape
562     #  @return mesh dimension as an integer value [0,3]
563     def MeshDimension(self):
564         shells = self.geompyD.SubShapeAllIDs( self.geom, geompyDC.ShapeType["SHELL"] )
565         if len( shells ) > 0 :
566             return 3
567         elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
568             return 2
569         elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
570             return 1
571         else:
572             return 0;
573         pass
574
575     ## Creates a segment discretization 1D algorithm.
576     #  If the optional \a algo parameter is not set, this algorithm is REGULAR.
577     #  \n If the optional \a geom parameter is not set, this algorithm is global.
578     #  Otherwise, this algorithm defines a submesh based on \a geom subshape.
579     #  @param algo the type of the required algorithm. Possible values are:
580     #     - smesh.REGULAR,
581     #     - smesh.PYTHON for discretization via a python function,
582     #     - smesh.COMPOSITE for meshing a set of edges on one face side as a whole.
583     #  @param geom If defined is the subshape to be meshed
584     #  @return an instance of Mesh_Segment or Mesh_Segment_Python, or Mesh_CompositeSegment class
585     def Segment(self, algo=REGULAR, geom=0):
586         ## if Segment(geom) is called by mistake
587         if isinstance( algo, geompyDC.GEOM._objref_GEOM_Object):
588             algo, geom = geom, algo
589             if not algo: algo = REGULAR
590             pass
591         if algo == REGULAR:
592             return Mesh_Segment(self,  geom)
593         elif algo == PYTHON:
594             return Mesh_Segment_Python(self, geom)
595         elif algo == COMPOSITE:
596             return Mesh_CompositeSegment(self, geom)
597         else:
598             return Mesh_Segment(self, geom)
599
600     ## Enables creation of nodes and segments usable by 2D algoritms.
601     #  The added nodes and segments must be bound to edges and vertices by
602     #  SetNodeOnVertex(), SetNodeOnEdge() and SetMeshElementOnShape()
603     #  If the optional \a geom parameter is not set, this algorithm is global.
604     #  \n Otherwise, this algorithm defines a submesh based on \a geom subshape.
605     #  @param geom the subshape to be manually meshed
606     #  @return StdMeshers_UseExisting_1D algorithm that generates nothing
607     def UseExistingSegments(self, geom=0):
608         algo = Mesh_UseExisting(1,self,geom)
609         return algo.GetAlgorithm()
610
611     ## Enables creation of nodes and faces usable by 3D algoritms.
612     #  The added nodes and faces must be bound to geom faces by SetNodeOnFace()
613     #  and SetMeshElementOnShape()
614     #  If the optional \a geom parameter is not set, this algorithm is global.
615     #  \n Otherwise, this algorithm defines a submesh based on \a geom subshape.
616     #  @param geom the subshape to be manually meshed
617     #  @return StdMeshers_UseExisting_2D algorithm that generates nothing
618     def UseExistingFaces(self, geom=0):
619         algo = Mesh_UseExisting(2,self,geom)
620         return algo.GetAlgorithm()
621
622     ## Creates a triangle 2D algorithm for faces.
623     #  If the optional \a geom parameter is not set, this algorithm is global.
624     #  \n Otherwise, this algorithm defines a submesh based on \a geom subshape.
625     #  @param algo values are: smesh.MEFISTO || smesh.NETGEN_1D2D || smesh.NETGEN_2D || smesh.BLSURF
626     #  @param geom If defined, the subshape to be meshed (GEOM_Object)
627     #  @return an instance of Mesh_Triangle algorithm
628     def Triangle(self, algo=MEFISTO, geom=0):
629         ## if Triangle(geom) is called by mistake
630         if (isinstance(algo, geompyDC.GEOM._objref_GEOM_Object)):
631             geom = algo
632             algo = MEFISTO
633
634         return Mesh_Triangle(self, algo, geom)
635
636     ## Creates a quadrangle 2D algorithm for faces.
637     #  If the optional \a geom parameter is not set, this algorithm is global.
638     #  \n Otherwise, this algorithm defines a submesh based on \a geom subshape.
639     #  @param geom If defined, the subshape to be meshed (GEOM_Object)
640     #  @return an instance of Mesh_Quadrangle algorithm
641     def Quadrangle(self, geom=0):
642         return Mesh_Quadrangle(self,  geom)
643
644     ## Creates a tetrahedron 3D algorithm for solids.
645     #  The parameter \a algo permits to choose the algorithm: NETGEN or GHS3D
646     #  If the optional \a geom parameter is not set, this algorithm is global.
647     #  \n Otherwise, this algorithm defines a submesh based on \a geom subshape.
648     #  @param algo values are: smesh.NETGEN, smesh.GHS3D, smesh.FULL_NETGEN
649     #  @param geom If defined, the subshape to be meshed (GEOM_Object)
650     #  @return an instance of Mesh_Tetrahedron algorithm
651     def Tetrahedron(self, algo=NETGEN, geom=0):
652         ## if Tetrahedron(geom) is called by mistake
653         if ( isinstance( algo, geompyDC.GEOM._objref_GEOM_Object)):
654             algo, geom = geom, algo
655             if not algo: algo = NETGEN
656             pass
657         return Mesh_Tetrahedron(self,  algo, geom)
658
659     ## Creates a hexahedron 3D algorithm for solids.
660     #  If the optional \a geom parameter is not set, this algorithm is global.
661     #  \n Otherwise, this algorithm defines a submesh based on \a geom subshape.
662     #  @param algo possible values are: smesh.Hexa, smesh.Hexotic
663     #  @param geom If defined, the subshape to be meshed (GEOM_Object)
664     #  @return an instance of Mesh_Hexahedron algorithm
665     def Hexahedron(self, algo=Hexa, geom=0):
666         ## if Hexahedron(geom, algo) or Hexahedron(geom) is called by mistake
667         if ( isinstance(algo, geompyDC.GEOM._objref_GEOM_Object) ):
668             if   geom in [Hexa, Hexotic]: algo, geom = geom, algo
669             elif geom == 0:               algo, geom = Hexa, algo
670         return Mesh_Hexahedron(self, algo, geom)
671
672     ## Deprecated, used only for compatibility!
673     #  @return an instance of Mesh_Netgen algorithm
674     def Netgen(self, is3D, geom=0):
675         return Mesh_Netgen(self,  is3D, geom)
676
677     ## Creates a projection 1D algorithm for edges.
678     #  If the optional \a geom parameter is not set, this algorithm is global.
679     #  Otherwise, this algorithm defines a submesh based on \a geom subshape.
680     #  @param geom If defined, the subshape to be meshed
681     #  @return an instance of Mesh_Projection1D algorithm
682     def Projection1D(self, geom=0):
683         return Mesh_Projection1D(self,  geom)
684
685     ## Creates a projection 2D algorithm for faces.
686     #  If the optional \a geom parameter is not set, this algorithm is global.
687     #  Otherwise, this algorithm defines a submesh based on \a geom subshape.
688     #  @param geom If defined, the subshape to be meshed
689     #  @return an instance of Mesh_Projection2D algorithm
690     def Projection2D(self, geom=0):
691         return Mesh_Projection2D(self,  geom)
692
693     ## Creates a projection 3D algorithm for solids.
694     #  If the optional \a geom parameter is not set, this algorithm is global.
695     #  Otherwise, this algorithm defines a submesh based on \a geom subshape.
696     #  @param geom If defined, the subshape to be meshed
697     #  @return an instance of Mesh_Projection3D algorithm
698     def Projection3D(self, geom=0):
699         return Mesh_Projection3D(self,  geom)
700
701     ## Creates a 3D extrusion (Prism 3D) or RadialPrism 3D algorithm for solids.
702     #  If the optional \a geom parameter is not set, this algorithm is global.
703     #  Otherwise, this algorithm defines a submesh based on \a geom subshape.
704     #  @param geom If defined, the subshape to be meshed
705     #  @return an instance of Mesh_Prism3D or Mesh_RadialPrism3D algorithm
706     def Prism(self, geom=0):
707         shape = geom
708         if shape==0:
709             shape = self.geom
710         nbSolids = len( self.geompyD.SubShapeAll( shape, geompyDC.ShapeType["SOLID"] ))
711         nbShells = len( self.geompyD.SubShapeAll( shape, geompyDC.ShapeType["SHELL"] ))
712         if nbSolids == 0 or nbSolids == nbShells:
713             return Mesh_Prism3D(self,  geom)
714         return Mesh_RadialPrism3D(self,  geom)
715
716     ## Computes the mesh and returns the status of the computation
717     #  @return True or False
718     def Compute(self, geom=0):
719         if geom == 0 or not isinstance(geom, geompyDC.GEOM._objref_GEOM_Object):
720             if self.geom == 0:
721                 print "Compute impossible: mesh is not constructed on geom shape."
722                 return 0
723             else:
724                 geom = self.geom
725         ok = False
726         try:
727             ok = self.smeshpyD.Compute(self.mesh, geom)
728         except SALOME.SALOME_Exception, ex:
729             print "Mesh computation failed, exception caught:"
730             print "    ", ex.details.text
731         except:
732             import traceback
733             print "Mesh computation failed, exception caught:"
734             traceback.print_exc()
735         if True:#not ok:
736             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
737             allReasons = ""
738             for err in errors:
739                 if err.isGlobalAlgo:
740                     glob = "global"
741                 else:
742                     glob = "local"
743                     pass
744                 dim = err.algoDim
745                 name = err.algoName
746                 if len(name) == 0:
747                     reason = '%s %sD algorithm is missing' % (glob, dim)
748                 elif err.state == HYP_MISSING:
749                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
750                               % (glob, dim, name, dim))
751                 elif err.state == HYP_NOTCONFORM:
752                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
753                 elif err.state == HYP_BAD_PARAMETER:
754                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
755                               % ( glob, dim, name ))
756                 elif err.state == HYP_BAD_GEOMETRY:
757                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
758                               'geometry' % ( glob, dim, name ))
759                 else:
760                     reason = "For unknown reason."+\
761                              " Revise Mesh.Compute() implementation in smeshDC.py!"
762                     pass
763                 if allReasons != "":
764                     allReasons += "\n"
765                     pass
766                 allReasons += reason
767                 pass
768             if allReasons != "":
769                 print '"' + GetName(self.mesh) + '"',"has not been computed:"
770                 print allReasons
771                 ok = False
772             elif not ok:
773                 print '"' + GetName(self.mesh) + '"',"has not been computed."
774                 pass
775             pass
776         if salome.sg.hasDesktop():
777             smeshgui = salome.ImportComponentGUI("SMESH")
778             smeshgui.Init(salome.myStudyId)
779             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
780             salome.sg.updateObjBrowser(1)
781             pass
782         return ok
783
784     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
785     #  The parameter \a fineness [0,-1] defines mesh fineness
786     #  @return True or False
787     def AutomaticTetrahedralization(self, fineness=0):
788         dim = self.MeshDimension()
789         # assign hypotheses
790         self.RemoveGlobalHypotheses()
791         self.Segment().AutomaticLength(fineness)
792         if dim > 1 :
793             self.Triangle().LengthFromEdges()
794             pass
795         if dim > 2 :
796             self.Tetrahedron(NETGEN)
797             pass
798         return self.Compute()
799
800     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
801     #  The parameter \a fineness [0,-1] defines mesh fineness
802     #  @return True or False
803     def AutomaticHexahedralization(self, fineness=0):
804         dim = self.MeshDimension()
805         # assign the hypotheses
806         self.RemoveGlobalHypotheses()
807         self.Segment().AutomaticLength(fineness)
808         if dim > 1 :
809             self.Quadrangle()
810             pass
811         if dim > 2 :
812             self.Hexahedron()
813             pass
814         return self.Compute()
815
816     ## Assigns a hypothesis
817     #  @param hyp a hypothesis to assign
818     #  @param geom a subhape of mesh geometry
819     #  @return SMESH.Hypothesis_Status
820     def AddHypothesis(self, hyp, geom=0):
821         if isinstance( hyp, Mesh_Algorithm ):
822             hyp = hyp.GetAlgorithm()
823             pass
824         if not geom:
825             geom = self.geom
826             pass
827         status = self.mesh.AddHypothesis(geom, hyp)
828         isAlgo = hyp._narrow( SMESH_Algo )
829         TreatHypoStatus( status, GetName( hyp ), GetName( geom ), isAlgo )
830         return status
831
832     ## Unassigns a hypothesis
833     #  @param hyp a hypothesis to unassign
834     #  @param geom a subshape of mesh geometry
835     #  @return SMESH.Hypothesis_Status
836     def RemoveHypothesis(self, hyp, geom=0):
837         if isinstance( hyp, Mesh_Algorithm ):
838             hyp = hyp.GetAlgorithm()
839             pass
840         if not geom:
841             geom = self.geom
842             pass
843         status = self.mesh.RemoveHypothesis(geom, hyp)
844         return status
845
846     ## Gets the list of hypotheses added on a geometry
847     #  @param geom a subshape of mesh geometry
848     #  @return the sequence of SMESH_Hypothesis
849     def GetHypothesisList(self, geom):
850         return self.mesh.GetHypothesisList( geom )
851
852     ## Removes all global hypotheses
853     def RemoveGlobalHypotheses(self):
854         current_hyps = self.mesh.GetHypothesisList( self.geom )
855         for hyp in current_hyps:
856             self.mesh.RemoveHypothesis( self.geom, hyp )
857             pass
858         pass
859
860     ## Creates a mesh group based on the geometric object \a grp
861     #  and gives a \a name, \n if this parameter is not defined
862     #  the name is the same as the geometric group name \n
863     #  Note: Works like GroupOnGeom().
864     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
865     #  @param name the name of the mesh group
866     #  @return SMESH_GroupOnGeom
867     def Group(self, grp, name=""):
868         return self.GroupOnGeom(grp, name)
869
870     ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
871     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
872     #  @param f the file name
873     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
874     def ExportToMED(self, f, version, opt=0):
875         self.mesh.ExportToMED(f, opt, version)
876
877     ## Exports the mesh in a file in MED format
878     #  @param f is the file name
879     #  @param auto_groups boolean parameter for creating/not creating
880     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
881     #  the typical use is auto_groups=false.
882     #  @param version MED format version(MED_V2_1 or MED_V2_2)
883     def ExportMED(self, f, auto_groups=0, version=MED_V2_2):
884         self.mesh.ExportToMED(f, auto_groups, version)
885
886     ## Exports the mesh in a file in DAT format
887     #  @param f the file name
888     def ExportDAT(self, f):
889         self.mesh.ExportDAT(f)
890
891     ## Exports the mesh in a file in UNV format
892     #  @param f the file name
893     def ExportUNV(self, f):
894         self.mesh.ExportUNV(f)
895
896     ## Export the mesh in a file in STL format
897     #  @param f the file name
898     #  @param ascii defines the file encoding
899     def ExportSTL(self, f, ascii=1):
900         self.mesh.ExportSTL(f, ascii)
901
902
903     # Operations with groups:
904     # ----------------------
905
906     ## Creates an empty mesh group
907     #  @param elementType the type of elements in the group
908     #  @param name the name of the mesh group
909     #  @return SMESH_Group
910     def CreateEmptyGroup(self, elementType, name):
911         return self.mesh.CreateGroup(elementType, name)
912
913     ## Creates a mesh group based on the geometrical object \a grp
914     #  and gives a \a name, \n if this parameter is not defined
915     #  the name is the same as the geometrical group name
916     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
917     #  @param name the name of the mesh group
918     #  @return SMESH_GroupOnGeom
919     def GroupOnGeom(self, grp, name="", typ=None):
920         if name == "":
921             name = grp.GetName()
922
923         if typ == None:
924             tgeo = str(grp.GetShapeType())
925             if tgeo == "VERTEX":
926                 typ = NODE
927             elif tgeo == "EDGE":
928                 typ = EDGE
929             elif tgeo == "FACE":
930                 typ = FACE
931             elif tgeo == "SOLID":
932                 typ = VOLUME
933             elif tgeo == "SHELL":
934                 typ = VOLUME
935             elif tgeo == "COMPOUND":
936                 if len( self.geompyD.GetObjectIDs( grp )) == 0:
937                     print "Mesh.Group: empty geometric group", GetName( grp )
938                     return 0
939                 tgeo = self.geompyD.GetType(grp)
940                 if tgeo == geompyDC.ShapeType["VERTEX"]:
941                     typ = NODE
942                 elif tgeo == geompyDC.ShapeType["EDGE"]:
943                     typ = EDGE
944                 elif tgeo == geompyDC.ShapeType["FACE"]:
945                     typ = FACE
946                 elif tgeo == geompyDC.ShapeType["SOLID"]:
947                     typ = VOLUME
948
949         if typ == None:
950             print "Mesh.Group: bad first argument: expected a group, a vertex, an edge, a face or a solid"
951             return 0
952         else:
953             return self.mesh.CreateGroupFromGEOM(typ, name, grp)
954
955     ## Creates a mesh group by the given ids of elements
956     #  @param groupName the name of the mesh group
957     #  @param elementType the type of elements in the group
958     #  @param elemIDs the list of ids
959     #  @return SMESH_Group
960     def MakeGroupByIds(self, groupName, elementType, elemIDs):
961         group = self.mesh.CreateGroup(elementType, groupName)
962         group.Add(elemIDs)
963         return group
964
965     ## Creates a mesh group by the given conditions
966     #  @param groupName the name of the mesh group
967     #  @param elementType the type of elements in the group
968     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
969     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
970     #  @param Treshold the threshold value (range of id ids as string, shape, numeric)
971     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
972     #  @return SMESH_Group
973     def MakeGroup(self,
974                   groupName,
975                   elementType,
976                   CritType=FT_Undefined,
977                   Compare=FT_EqualTo,
978                   Treshold="",
979                   UnaryOp=FT_Undefined):
980         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
981         group = self.MakeGroupByCriterion(groupName, aCriterion)
982         return group
983
984     ## Creates a mesh group by the given criterion
985     #  @param groupName the name of the mesh group
986     #  @param Criterion the instance of Criterion class
987     #  @return SMESH_Group
988     def MakeGroupByCriterion(self, groupName, Criterion):
989         aFilterMgr = self.smeshpyD.CreateFilterManager()
990         aFilter = aFilterMgr.CreateFilter()
991         aCriteria = []
992         aCriteria.append(Criterion)
993         aFilter.SetCriteria(aCriteria)
994         group = self.MakeGroupByFilter(groupName, aFilter)
995         return group
996
997     ## Creates a mesh group by the given criteria (list of criteria)
998     #  @param groupName the name of the mesh group
999     #  @param Criteria the list of criteria
1000     #  @return SMESH_Group
1001     def MakeGroupByCriteria(self, groupName, theCriteria):
1002         aFilterMgr = self.smeshpyD.CreateFilterManager()
1003         aFilter = aFilterMgr.CreateFilter()
1004         aFilter.SetCriteria(theCriteria)
1005         group = self.MakeGroupByFilter(groupName, aFilter)
1006         return group
1007
1008     ## Creates a mesh group by the given filter
1009     #  @param groupName  the name of the mesh group
1010     #  @param Criterion  the instance of Filter class
1011     #  @return SMESH_Group
1012     def MakeGroupByFilter(self, groupName, theFilter):
1013         anIds = theFilter.GetElementsId(self.mesh)
1014         anElemType = theFilter.GetElementType()
1015         group = self.MakeGroupByIds(groupName, anElemType, anIds)
1016         return group
1017
1018     ## Passes mesh elements through the given filter and return IDs of fitting elements
1019     #  @param theFilter SMESH_Filter
1020     #  @return a list of ids
1021     def GetIdsFromFilter(self, theFilter):
1022         return theFilter.GetElementsId(self.mesh)
1023
1024     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
1025     #  Returns a list of special structures (borders).
1026     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
1027     def GetFreeBorders(self):
1028         aFilterMgr = self.smeshpyD.CreateFilterManager()
1029         aPredicate = aFilterMgr.CreateFreeEdges()
1030         aPredicate.SetMesh(self.mesh)
1031         aBorders = aPredicate.GetBorders()
1032         return aBorders
1033
1034     ## Removes a group
1035     def RemoveGroup(self, group):
1036         self.mesh.RemoveGroup(group)
1037
1038     ## Removes a group with its contents
1039     def RemoveGroupWithContents(self, group):
1040         self.mesh.RemoveGroupWithContents(group)
1041
1042     ## Gets the list of groups existing in the mesh
1043     #  @return a sequence of SMESH_GroupBase
1044     def GetGroups(self):
1045         return self.mesh.GetGroups()
1046
1047     ## Gets the number of groups existing in the mesh
1048     #  @return the quantity of groups as an integer value
1049     def NbGroups(self):
1050         return self.mesh.NbGroups()
1051
1052     ## Gets the list of names of groups existing in the mesh
1053     #  @return list of strings
1054     def GetGroupNames(self):
1055         groups = self.GetGroups()
1056         names = []
1057         for group in groups:
1058             names.append(group.GetName())
1059         return names
1060
1061     ## Produces a union of two groups
1062     #  A new group is created. All mesh elements that are
1063     #  present in the initial groups are added to the new one
1064     #  @return an instance of SMESH_Group
1065     def UnionGroups(self, group1, group2, name):
1066         return self.mesh.UnionGroups(group1, group2, name)
1067
1068     ## Prodices an intersection of two groups
1069     #  A new group is created. All mesh elements that are common
1070     #  for the two initial groups are added to the new one.
1071     #  @return an instance of SMESH_Group
1072     def IntersectGroups(self, group1, group2, name):
1073         return self.mesh.IntersectGroups(group1, group2, name)
1074
1075     ## Produces a cut of two groups
1076     #  A new group is created. All mesh elements that are present in
1077     #  the main group but are not present in the tool group are added to the new one
1078     #  @return an instance of SMESH_Group
1079     def CutGroups(self, mainGroup, toolGroup, name):
1080         return self.mesh.CutGroups(mainGroup, toolGroup, name)
1081
1082
1083     # Get some info about mesh:
1084     # ------------------------
1085
1086     ## Returns the log of nodes and elements added or removed
1087     #  since the previous clear of the log.
1088     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
1089     #  @return list of log_block structures:
1090     #                                        commandType
1091     #                                        number
1092     #                                        coords
1093     #                                        indexes
1094     def GetLog(self, clearAfterGet):
1095         return self.mesh.GetLog(clearAfterGet)
1096
1097     ## Clears the log of nodes and elements added or removed since the previous
1098     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
1099     def ClearLog(self):
1100         self.mesh.ClearLog()
1101
1102     ## Toggles auto color mode on the object.
1103     #  @param theAutoColor the flag which toggles auto color mode.
1104     def SetAutoColor(self, theAutoColor):
1105         self.mesh.SetAutoColor(theAutoColor)
1106
1107     ## Gets flag of object auto color mode.
1108     #  @return True or False
1109     def GetAutoColor(self):
1110         return self.mesh.GetAutoColor()
1111
1112     ## Gets the internal ID
1113     #  @return integer value, which is the internal Id of the mesh
1114     def GetId(self):
1115         return self.mesh.GetId()
1116
1117     ## Get the study Id
1118     #  @return integer value, which is the study Id of the mesh
1119     def GetStudyId(self):
1120         return self.mesh.GetStudyId()
1121
1122     ## Checks the group names for duplications.
1123     #  Consider the maximum group name length stored in MED file.
1124     #  @return True or False
1125     def HasDuplicatedGroupNamesMED(self):
1126         return self.mesh.HasDuplicatedGroupNamesMED()
1127
1128     ## Obtains the mesh editor tool
1129     #  @return an instance of SMESH_MeshEditor
1130     def GetMeshEditor(self):
1131         return self.mesh.GetMeshEditor()
1132
1133     ## Gets MED Mesh
1134     #  @return an instance of SALOME_MED::MESH
1135     def GetMEDMesh(self):
1136         return self.mesh.GetMEDMesh()
1137
1138
1139     # Get informations about mesh contents:
1140     # ------------------------------------
1141
1142     ## Returns the number of nodes in the mesh
1143     #  @return an integer value
1144     def NbNodes(self):
1145         return self.mesh.NbNodes()
1146
1147     ## Returns the number of elements in the mesh
1148     #  @return an integer value
1149     def NbElements(self):
1150         return self.mesh.NbElements()
1151
1152     ## Returns the number of edges in the mesh
1153     #  @return an integer value
1154     def NbEdges(self):
1155         return self.mesh.NbEdges()
1156
1157     ## Returns the number of edges with the given order in the mesh
1158     #  @param elementOrder the order of elements:
1159     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1160     #  @return an integer value
1161     def NbEdgesOfOrder(self, elementOrder):
1162         return self.mesh.NbEdgesOfOrder(elementOrder)
1163
1164     ## Returns the number of faces in the mesh
1165     #  @return an integer value
1166     def NbFaces(self):
1167         return self.mesh.NbFaces()
1168
1169     ## Returns the number of faces with the given order in the mesh
1170     #  @param elementOrder the order of elements:
1171     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1172     #  @return an integer value
1173     def NbFacesOfOrder(self, elementOrder):
1174         return self.mesh.NbFacesOfOrder(elementOrder)
1175
1176     ## Returns the number of triangles in the mesh
1177     #  @return an integer value
1178     def NbTriangles(self):
1179         return self.mesh.NbTriangles()
1180
1181     ## Returns the number of triangles with the given order in the mesh
1182     #  @param elementOrder is the order of elements:
1183     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1184     #  @return an integer value
1185     def NbTrianglesOfOrder(self, elementOrder):
1186         return self.mesh.NbTrianglesOfOrder(elementOrder)
1187
1188     ## Returns the number of quadrangles in the mesh
1189     #  @return an integer value
1190     def NbQuadrangles(self):
1191         return self.mesh.NbQuadrangles()
1192
1193     ## Returns the number of quadrangles with the given order in the mesh
1194     #  @param elementOrder the order of elements:
1195     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1196     #  @return an integer value
1197     def NbQuadranglesOfOrder(self, elementOrder):
1198         return self.mesh.NbQuadranglesOfOrder(elementOrder)
1199
1200     ## Returns the number of polygons in the mesh
1201     #  @return an integer value
1202     def NbPolygons(self):
1203         return self.mesh.NbPolygons()
1204
1205     ## Returns the number of volumes in the mesh
1206     #  @return an integer value
1207     def NbVolumes(self):
1208         return self.mesh.NbVolumes()
1209
1210     ## Returns the number of volumes with the given order in the mesh
1211     #  @param elementOrder  the order of elements:
1212     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1213     #  @return an integer value
1214     def NbVolumesOfOrder(self, elementOrder):
1215         return self.mesh.NbVolumesOfOrder(elementOrder)
1216
1217     ## Returns the number of tetrahedrons in the mesh
1218     #  @return an integer value
1219     def NbTetras(self):
1220         return self.mesh.NbTetras()
1221
1222     ## Returns the number of tetrahedrons with the given order in the mesh
1223     #  @param elementOrder  the order of elements:
1224     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1225     #  @return an integer value
1226     def NbTetrasOfOrder(self, elementOrder):
1227         return self.mesh.NbTetrasOfOrder(elementOrder)
1228
1229     ## Returns the number of hexahedrons in the mesh
1230     #  @return an integer value
1231     def NbHexas(self):
1232         return self.mesh.NbHexas()
1233
1234     ## Returns the number of hexahedrons with the given order in the mesh
1235     #  @param elementOrder  the order of elements:
1236     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1237     #  @return an integer value
1238     def NbHexasOfOrder(self, elementOrder):
1239         return self.mesh.NbHexasOfOrder(elementOrder)
1240
1241     ## Returns the number of pyramids in the mesh
1242     #  @return an integer value
1243     def NbPyramids(self):
1244         return self.mesh.NbPyramids()
1245
1246     ## Returns the number of pyramids with the given order in the mesh
1247     #  @param elementOrder  the order of elements:
1248     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1249     #  @return an integer value
1250     def NbPyramidsOfOrder(self, elementOrder):
1251         return self.mesh.NbPyramidsOfOrder(elementOrder)
1252
1253     ## Returns the number of prisms in the mesh
1254     #  @return an integer value
1255     def NbPrisms(self):
1256         return self.mesh.NbPrisms()
1257
1258     ## Returns the number of prisms with the given order in the mesh
1259     #  @param elementOrder  the order of elements:
1260     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1261     #  @return an integer value
1262     def NbPrismsOfOrder(self, elementOrder):
1263         return self.mesh.NbPrismsOfOrder(elementOrder)
1264
1265     ## Returns the number of polyhedrons in the mesh
1266     #  @return an integer value
1267     def NbPolyhedrons(self):
1268         return self.mesh.NbPolyhedrons()
1269
1270     ## Returns the number of submeshes in the mesh
1271     #  @return an integer value
1272     def NbSubMesh(self):
1273         return self.mesh.NbSubMesh()
1274
1275     ## Returns the list of mesh elements IDs
1276     #  @return the list of integer values
1277     def GetElementsId(self):
1278         return self.mesh.GetElementsId()
1279
1280     ## Returns the list of IDs of mesh elements with the given type
1281     #  @param elementType  the required type of elements
1282     #  @return list of integer values
1283     def GetElementsByType(self, elementType):
1284         return self.mesh.GetElementsByType(elementType)
1285
1286     ## Returns the list of mesh nodes IDs
1287     #  @return the list of integer values
1288     def GetNodesId(self):
1289         return self.mesh.GetNodesId()
1290
1291     # Get the information about mesh elements:
1292     # ------------------------------------
1293
1294     ## Returns the type of mesh element
1295     #  @return the value from SMESH::ElementType enumeration
1296     def GetElementType(self, id, iselem):
1297         return self.mesh.GetElementType(id, iselem)
1298
1299     ## Returns the list of submesh elements IDs
1300     #  @param Shape a geom object(subshape) IOR
1301     #         Shape must be the subshape of a ShapeToMesh()
1302     #  @return the list of integer values
1303     def GetSubMeshElementsId(self, Shape):
1304         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
1305             ShapeID = Shape.GetSubShapeIndices()[0]
1306         else:
1307             ShapeID = Shape
1308         return self.mesh.GetSubMeshElementsId(ShapeID)
1309
1310     ## Returns the list of submesh nodes IDs
1311     #  @param Shape a geom object(subshape) IOR
1312     #         Shape must be the subshape of a ShapeToMesh()
1313     #  @return the list of integer values
1314     def GetSubMeshNodesId(self, Shape, all):
1315         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
1316             ShapeID = Shape.GetSubShapeIndices()[0]
1317         else:
1318             ShapeID = Shape
1319         return self.mesh.GetSubMeshNodesId(ShapeID, all)
1320
1321     ## Returns the list of IDs of submesh elements with the given type
1322     #  @param Shape a geom object(subshape) IOR
1323     #         Shape must be a subshape of a ShapeToMesh()
1324     #  @return the list of integer values
1325     def GetSubMeshElementType(self, Shape):
1326         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
1327             ShapeID = Shape.GetSubShapeIndices()[0]
1328         else:
1329             ShapeID = Shape
1330         return self.mesh.GetSubMeshElementType(ShapeID)
1331
1332     ## Gets the mesh description
1333     #  @return string value
1334     def Dump(self):
1335         return self.mesh.Dump()
1336
1337
1338     # Get the information about nodes and elements of a mesh by its IDs:
1339     # -----------------------------------------------------------
1340
1341     ## Gets XYZ coordinates of a node
1342     #  \n If there is no nodes for the given ID - returns an empty list
1343     #  @return a list of double precision values
1344     def GetNodeXYZ(self, id):
1345         return self.mesh.GetNodeXYZ(id)
1346
1347     ## Returns list of IDs of inverse elements for the given node
1348     #  \n If there is no node for the given ID - returns an empty list
1349     #  @return a list of integer values
1350     def GetNodeInverseElements(self, id):
1351         return self.mesh.GetNodeInverseElements(id)
1352
1353     ## @brief Returns the position of a node on the shape
1354     #  @return SMESH::NodePosition
1355     def GetNodePosition(self,NodeID):
1356         return self.mesh.GetNodePosition(NodeID)
1357
1358     ## If the given element is a node, returns the ID of shape
1359     #  \n If there is no node for the given ID - returns -1
1360     #  @return an integer value
1361     def GetShapeID(self, id):
1362         return self.mesh.GetShapeID(id)
1363
1364     ## Returns the ID of the result shape after
1365     #  FindShape() from SMESH_MeshEditor for the given element
1366     #  \n If there is no element for the given ID - returns -1
1367     #  @return an integer value
1368     def GetShapeIDForElem(self,id):
1369         return self.mesh.GetShapeIDForElem(id)
1370
1371     ## Returns the number of nodes for the given element
1372     #  \n If there is no element for the given ID - returns -1
1373     #  @return an integer value
1374     def GetElemNbNodes(self, id):
1375         return self.mesh.GetElemNbNodes(id)
1376
1377     ## Returns the node ID the given index for the given element
1378     #  \n If there is no element for the given ID - returns -1
1379     #  \n If there is no node for the given index - returns -2
1380     #  @return an integer value
1381     def GetElemNode(self, id, index):
1382         return self.mesh.GetElemNode(id, index)
1383
1384     ## Returns the IDs of nodes of the given element
1385     #  @return a list of integer values
1386     def GetElemNodes(self, id):
1387         return self.mesh.GetElemNodes(id)
1388
1389     ## Returns true if the given node is the medium node in the given quadratic element
1390     def IsMediumNode(self, elementID, nodeID):
1391         return self.mesh.IsMediumNode(elementID, nodeID)
1392
1393     ## Returns true if the given node is the medium node in one of quadratic elements
1394     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
1395         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
1396
1397     ## Returns the number of edges for the given element
1398     def ElemNbEdges(self, id):
1399         return self.mesh.ElemNbEdges(id)
1400
1401     ## Returns the number of faces for the given element
1402     def ElemNbFaces(self, id):
1403         return self.mesh.ElemNbFaces(id)
1404
1405     ## Returns true if the given element is a polygon
1406     def IsPoly(self, id):
1407         return self.mesh.IsPoly(id)
1408
1409     ## Returns true if the given element is quadratic
1410     def IsQuadratic(self, id):
1411         return self.mesh.IsQuadratic(id)
1412
1413     ## Returns XYZ coordinates of the barycenter of the given element
1414     #  \n If there is no element for the given ID - returns an empty list
1415     #  @return a list of three double values
1416     def BaryCenter(self, id):
1417         return self.mesh.BaryCenter(id)
1418
1419
1420     # Mesh edition (SMESH_MeshEditor functionality):
1421     # ---------------------------------------------
1422
1423     ## Removes the elements from the mesh by ids
1424     #  @param IDsOfElements is a list of ids of elements to remove
1425     #  @return True or False
1426     def RemoveElements(self, IDsOfElements):
1427         return self.editor.RemoveElements(IDsOfElements)
1428
1429     ## Removes nodes from mesh by ids
1430     #  @param IDsOfNodes is a list of ids of nodes to remove
1431     #  @return True or False
1432     def RemoveNodes(self, IDsOfNodes):
1433         return self.editor.RemoveNodes(IDsOfNodes)
1434
1435     ## Add a node to the mesh by coordinates
1436     #  @return Id of the new node
1437     def AddNode(self, x, y, z):
1438         return self.editor.AddNode( x, y, z)
1439
1440
1441     ## Creates a linear or quadratic edge (this is determined
1442     #  by the number of given nodes).
1443     #  @param IdsOfNodes the list of node IDs for creation of the element.
1444     #  The order of nodes in this list should correspond to the description
1445     #  of MED. \n This description is located by the following link:
1446     #  http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1447     #  @return the Id of the new edge
1448     def AddEdge(self, IDsOfNodes):
1449         return self.editor.AddEdge(IDsOfNodes)
1450
1451     ## Creates a linear or quadratic face (this is determined
1452     #  by the number of given nodes).
1453     #  @param IdsOfNodes the list of node IDs for creation of the element.
1454     #  The order of nodes in this list should correspond to the description
1455     #  of MED. \n This description is located by the following link:
1456     #  http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1457     #  @return the Id of the new face
1458     def AddFace(self, IDsOfNodes):
1459         return self.editor.AddFace(IDsOfNodes)
1460
1461     ## Adds a polygonal face to the mesh by the list of node IDs
1462     #  @return the Id of the new face
1463     def AddPolygonalFace(self, IdsOfNodes):
1464         return self.editor.AddPolygonalFace(IdsOfNodes)
1465
1466     ## Creates both simple and quadratic volume (this is determined
1467     #  by the number of given nodes).
1468     #  @param IdsOfNodes the list of node IDs for creation of the element.
1469     #  The order of nodes in this list should correspond to the description
1470     #  of MED. \n This description is located by the following link:
1471     #  http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1472     #  @return the Id of the new volumic element
1473     def AddVolume(self, IDsOfNodes):
1474         return self.editor.AddVolume(IDsOfNodes)
1475
1476     ## Creates a volume of many faces, giving nodes for each face.
1477     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
1478     #  @param Quantities the list of integer values, Quantities[i]
1479     #         gives the quantity of nodes in face number i.
1480     #  @return the Id of the new volumic element
1481     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
1482         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
1483
1484     ## Creates a volume of many faces, giving the IDs of the existing faces.
1485     #  @param IdsOfFaces the list of face IDs for volume creation.
1486     #
1487     #  Note:  The created volume will refer only to the nodes
1488     #         of the given faces, not to the faces themselves.
1489     #  @return the Id of the new volumic element
1490     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
1491         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
1492
1493
1494     ## @brief Binds a node to a vertex
1495     # @param NodeID a node ID
1496     # @param Vertex a vertex or vertex ID
1497     # @return True if succeed else raises an exception
1498     def SetNodeOnVertex(self, NodeID, Vertex):
1499         if ( isinstance( Vertex, geompyDC.GEOM._objref_GEOM_Object)):
1500             VertexID = Vertex.GetSubShapeIndices()[0]
1501         else:
1502             VertexID = Vertex
1503         try:
1504             self.editor.SetNodeOnVertex(NodeID, VertexID)
1505         except SALOME.SALOME_Exception, inst:
1506             raise ValueError, inst.details.text
1507         return True
1508
1509
1510     ## @brief Stores the node position on an edge
1511     # @param NodeID a node ID
1512     # @param Edge an edge or edge ID
1513     # @param paramOnEdge a parameter on the edge where the node is located
1514     # @return True if succeed else raises an exception
1515     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
1516         if ( isinstance( Edge, geompyDC.GEOM._objref_GEOM_Object)):
1517             EdgeID = Edge.GetSubShapeIndices()[0]
1518         else:
1519             EdgeID = Edge
1520         try:
1521             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
1522         except SALOME.SALOME_Exception, inst:
1523             raise ValueError, inst.details.text
1524         return True
1525
1526     ## @brief Stores node position on a face
1527     # @param NodeID a node ID
1528     # @param Face a face or face ID
1529     # @param u U parameter on the face where the node is located
1530     # @param v V parameter on the face where the node is located
1531     # @return True if succeed else raises an exception
1532     def SetNodeOnFace(self, NodeID, Face, u, v):
1533         if ( isinstance( Face, geompyDC.GEOM._objref_GEOM_Object)):
1534             FaceID = Face.GetSubShapeIndices()[0]
1535         else:
1536             FaceID = Face
1537         try:
1538             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
1539         except SALOME.SALOME_Exception, inst:
1540             raise ValueError, inst.details.text
1541         return True
1542
1543     ## @brief Binds a node to a solid
1544     # @param NodeID a node ID
1545     # @param Solid  a solid or solid ID
1546     # @return True if succeed else raises an exception
1547     def SetNodeInVolume(self, NodeID, Solid):
1548         if ( isinstance( Solid, geompyDC.GEOM._objref_GEOM_Object)):
1549             SolidID = Solid.GetSubShapeIndices()[0]
1550         else:
1551             SolidID = Solid
1552         try:
1553             self.editor.SetNodeInVolume(NodeID, SolidID)
1554         except SALOME.SALOME_Exception, inst:
1555             raise ValueError, inst.details.text
1556         return True
1557
1558     ## @brief Bind an element to a shape
1559     # @param ElementID an element ID
1560     # @param Shape a shape or shape ID
1561     # @return True if succeed else raises an exception
1562     def SetMeshElementOnShape(self, ElementID, Shape):
1563         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
1564             ShapeID = Shape.GetSubShapeIndices()[0]
1565         else:
1566             ShapeID = Shape
1567         try:
1568             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
1569         except SALOME.SALOME_Exception, inst:
1570             raise ValueError, inst.details.text
1571         return True
1572
1573
1574     ## Moves the node with the given id
1575     #  @param NodeID the id of the node
1576     #  @param x  a new X coordinate
1577     #  @param y  a new Y coordinate
1578     #  @param z  a new Z coordinate
1579     #  @return True if succeed else False
1580     def MoveNode(self, NodeID, x, y, z):
1581         return self.editor.MoveNode(NodeID, x, y, z)
1582
1583     ## Finds the node closest to a point
1584     #  @param x  the X coordinate of a point
1585     #  @param y  the Y coordinate of a point
1586     #  @param z  the Z coordinate of a point
1587     #  @return the ID of a node
1588     def FindNodeClosestTo(self, x, y, z):
1589         preview = self.mesh.GetMeshEditPreviewer()
1590         return preview.MoveClosestNodeToPoint(x, y, z, -1)
1591
1592     ## Finds the node closest to a point and moves it to a point location
1593     #  @param x  the X coordinate of a point
1594     #  @param y  the Y coordinate of a point
1595     #  @param z  the Z coordinate of a point
1596     #  @return the ID of a moved node
1597     def MeshToPassThroughAPoint(self, x, y, z):
1598         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
1599
1600     ## Replaces two neighbour triangles sharing Node1-Node2 link
1601     #  with the triangles built on the same 4 nodes but having other common link.
1602     #  @param NodeID1  the ID of the first node
1603     #  @param NodeID2  the ID of the second node
1604     #  @return false if proper faces were not found
1605     def InverseDiag(self, NodeID1, NodeID2):
1606         return self.editor.InverseDiag(NodeID1, NodeID2)
1607
1608     ## Replaces two neighbour triangles sharing Node1-Node2 link
1609     #  with a quadrangle built on the same 4 nodes.
1610     #  @param NodeID1  the ID of the first node
1611     #  @param NodeID2  the ID of the second node
1612     #  @return false if proper faces were not found
1613     def DeleteDiag(self, NodeID1, NodeID2):
1614         return self.editor.DeleteDiag(NodeID1, NodeID2)
1615
1616     ## Reorients elements by ids
1617     #  @param IDsOfElements if undefined reorients all mesh elements
1618     #  @return True if succeed else False
1619     def Reorient(self, IDsOfElements=None):
1620         if IDsOfElements == None:
1621             IDsOfElements = self.GetElementsId()
1622         return self.editor.Reorient(IDsOfElements)
1623
1624     ## Reorients all elements of the object
1625     #  @param theObject mesh, submesh or group
1626     #  @return True if succeed else False
1627     def ReorientObject(self, theObject):
1628         if ( isinstance( theObject, Mesh )):
1629             theObject = theObject.GetMesh()
1630         return self.editor.ReorientObject(theObject)
1631
1632     ## Fuses the neighbouring triangles into quadrangles.
1633     #  @param IDsOfElements The triangles to be fused,
1634     #  @param theCriterion  is FT_...; used to choose a neighbour to fuse with.
1635     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
1636     #                       is still performed; theMaxAngle is mesured in radians.
1637     #  @return TRUE in case of success, FALSE otherwise.
1638     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
1639         if IDsOfElements == []:
1640             IDsOfElements = self.GetElementsId()
1641         return self.editor.TriToQuad(IDsOfElements, self.smeshpyD.GetFunctor(theCriterion), MaxAngle)
1642
1643     ## Fuses the neighbouring triangles of the object into quadrangles
1644     #  @param theObject is mesh, submesh or group
1645     #  @param theCriterion is FT_...; used to choose a neighbour to fuse with.
1646     #  @param MaxAngle   a max angle between element normals at which the fusion
1647     #                   is still performed; theMaxAngle is mesured in radians.
1648     #  @return TRUE in case of success, FALSE otherwise.
1649     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
1650         if ( isinstance( theObject, Mesh )):
1651             theObject = theObject.GetMesh()
1652         return self.editor.TriToQuadObject(theObject, self.smeshpyD.GetFunctor(theCriterion), MaxAngle)
1653
1654     ## Splits quadrangles into triangles.
1655     #  @param IDsOfElements the faces to be splitted.
1656     #  @param theCriterion   FT_...; used to choose a diagonal for splitting.
1657     #  @return TRUE in case of success, FALSE otherwise.
1658     def QuadToTri (self, IDsOfElements, theCriterion):
1659         if IDsOfElements == []:
1660             IDsOfElements = self.GetElementsId()
1661         return self.editor.QuadToTri(IDsOfElements, self.smeshpyD.GetFunctor(theCriterion))
1662
1663     ## Splits quadrangles into triangles.
1664     #  @param theObject  the object from which the list of elements is taken, this is mesh, submesh or group
1665     #  @param theCriterion   FT_...; used to choose a diagonal for splitting.
1666     #  @return TRUE in case of success, FALSE otherwise.
1667     def QuadToTriObject (self, theObject, theCriterion):
1668         if ( isinstance( theObject, Mesh )):
1669             theObject = theObject.GetMesh()
1670         return self.editor.QuadToTriObject(theObject, self.smeshpyD.GetFunctor(theCriterion))
1671
1672     ## Splits quadrangles into triangles.
1673     #  @param theElems  the faces to be splitted
1674     #  @param the13Diag is used to choose a diagonal for splitting.
1675     #  @return TRUE in case of success, FALSE otherwise.
1676     def SplitQuad (self, IDsOfElements, Diag13):
1677         if IDsOfElements == []:
1678             IDsOfElements = self.GetElementsId()
1679         return self.editor.SplitQuad(IDsOfElements, Diag13)
1680
1681     ## Splits quadrangles into triangles.
1682     #  @param theObject  the object from which the list of elements is taken, this is mesh, submesh or group
1683     #  @return TRUE in case of success, FALSE otherwise.
1684     def SplitQuadObject (self, theObject, Diag13):
1685         if ( isinstance( theObject, Mesh )):
1686             theObject = theObject.GetMesh()
1687         return self.editor.SplitQuadObject(theObject, Diag13)
1688
1689     ## Finds a better splitting of the given quadrangle.
1690     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
1691     #  @param theCriterion  FT_...; a criterion to choose a diagonal for splitting.
1692     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
1693     #          diagonal is better, 0 if error occurs.
1694     def BestSplit (self, IDOfQuad, theCriterion):
1695         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
1696
1697     ## Splits quadrangle faces near triangular facets of volumes
1698     #
1699     def SplitQuadsNearTriangularFacets(self):
1700         faces_array = self.GetElementsByType(SMESH.FACE)
1701         for face_id in faces_array:
1702             if self.GetElemNbNodes(face_id) == 4: # quadrangle
1703                 quad_nodes = self.mesh.GetElemNodes(face_id)
1704                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
1705                 isVolumeFound = False
1706                 for node1_elem in node1_elems:
1707                     if not isVolumeFound:
1708                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
1709                             nb_nodes = self.GetElemNbNodes(node1_elem)
1710                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
1711                                 volume_elem = node1_elem
1712                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
1713                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
1714                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
1715                                         isVolumeFound = True
1716                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
1717                                             self.SplitQuad([face_id], False) # diagonal 2-4
1718                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
1719                                         isVolumeFound = True
1720                                         self.SplitQuad([face_id], True) # diagonal 1-3
1721                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
1722                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
1723                                         isVolumeFound = True
1724                                         self.SplitQuad([face_id], True) # diagonal 1-3
1725
1726     ## @brief Splits hexahedrons into tetrahedrons.
1727     #
1728     #  This operation uses pattern mapping functionality for splitting.
1729     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
1730     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
1731     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
1732     #         will be mapped into <theNode000>-th node of each volume, the (0,0,1)
1733     #         key-point will be mapped into <theNode001>-th node of each volume.
1734     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
1735     #  @return TRUE in case of success, FALSE otherwise.
1736     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
1737         # Pattern:     5.---------.6
1738         #              /|#*      /|
1739         #             / | #*    / |
1740         #            /  |  # * /  |
1741         #           /   |   # /*  |
1742         # (0,0,1) 4.---------.7 * |
1743         #          |#*  |1   | # *|
1744         #          | # *.----|---#.2
1745         #          |  #/ *   |   /
1746         #          |  /#  *  |  /
1747         #          | /   # * | /
1748         #          |/      #*|/
1749         # (0,0,0) 0.---------.3
1750         pattern_tetra = "!!! Nb of points: \n 8 \n\
1751         !!! Points: \n\
1752         0 0 0  !- 0 \n\
1753         0 1 0  !- 1 \n\
1754         1 1 0  !- 2 \n\
1755         1 0 0  !- 3 \n\
1756         0 0 1  !- 4 \n\
1757         0 1 1  !- 5 \n\
1758         1 1 1  !- 6 \n\
1759         1 0 1  !- 7 \n\
1760         !!! Indices of points of 6 tetras: \n\
1761         0 3 4 1 \n\
1762         7 4 3 1 \n\
1763         4 7 5 1 \n\
1764         6 2 5 7 \n\
1765         1 5 2 7 \n\
1766         2 3 1 7 \n"
1767
1768         pattern = self.smeshpyD.GetPattern()
1769         isDone  = pattern.LoadFromFile(pattern_tetra)
1770         if not isDone:
1771             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
1772             return isDone
1773
1774         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
1775         isDone = pattern.MakeMesh(self.mesh, False, False)
1776         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
1777
1778         # split quafrangle faces near triangular facets of volumes
1779         self.SplitQuadsNearTriangularFacets()
1780
1781         return isDone
1782
1783     ## @brief Split hexahedrons into prisms.
1784     #
1785     #  Uses the pattern mapping functionality for splitting.
1786     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
1787     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
1788     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
1789     #         will be mapped into the <theNode000>-th node of each volume, keypoint (0,0,1)
1790     #         will be mapped into the <theNode001>-th node of each volume.
1791     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
1792     #  @return TRUE in case of success, FALSE otherwise.
1793     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
1794         # Pattern:     5.---------.6
1795         #              /|#       /|
1796         #             / | #     / |
1797         #            /  |  #   /  |
1798         #           /   |   # /   |
1799         # (0,0,1) 4.---------.7   |
1800         #          |    |    |    |
1801         #          |   1.----|----.2
1802         #          |   / *   |   /
1803         #          |  /   *  |  /
1804         #          | /     * | /
1805         #          |/       *|/
1806         # (0,0,0) 0.---------.3
1807         pattern_prism = "!!! Nb of points: \n 8 \n\
1808         !!! Points: \n\
1809         0 0 0  !- 0 \n\
1810         0 1 0  !- 1 \n\
1811         1 1 0  !- 2 \n\
1812         1 0 0  !- 3 \n\
1813         0 0 1  !- 4 \n\
1814         0 1 1  !- 5 \n\
1815         1 1 1  !- 6 \n\
1816         1 0 1  !- 7 \n\
1817         !!! Indices of points of 2 prisms: \n\
1818         0 1 3 4 5 7 \n\
1819         2 3 1 6 7 5 \n"
1820
1821         pattern = self.smeshpyD.GetPattern()
1822         isDone  = pattern.LoadFromFile(pattern_prism)
1823         if not isDone:
1824             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
1825             return isDone
1826
1827         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
1828         isDone = pattern.MakeMesh(self.mesh, False, False)
1829         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
1830
1831         # Splits quafrangle faces near triangular facets of volumes
1832         self.SplitQuadsNearTriangularFacets()
1833
1834         return isDone
1835
1836     ## Smoothes elements
1837     #  @param IDsOfElements the list if ids of elements to smooth
1838     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
1839     #  Note that nodes built on edges and boundary nodes are always fixed.
1840     #  @param MaxNbOfIterations the maximum number of iterations
1841     #  @param MaxAspectRatio varies in range [1.0, inf]
1842     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
1843     #  @return TRUE in case of success, FALSE otherwise.
1844     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
1845                MaxNbOfIterations, MaxAspectRatio, Method):
1846         if IDsOfElements == []:
1847             IDsOfElements = self.GetElementsId()
1848         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
1849                                   MaxNbOfIterations, MaxAspectRatio, Method)
1850
1851     ## Smoothes elements which belong to the given object
1852     #  @param theObject the object to smooth
1853     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
1854     #  Note that nodes built on edges and boundary nodes are always fixed.
1855     #  @param MaxNbOfIterations the maximum number of iterations
1856     #  @param MaxAspectRatio varies in range [1.0, inf]
1857     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
1858     #  @return TRUE in case of success, FALSE otherwise.
1859     def SmoothObject(self, theObject, IDsOfFixedNodes,
1860                      MaxNbOfIterations, MaxxAspectRatio, Method):
1861         if ( isinstance( theObject, Mesh )):
1862             theObject = theObject.GetMesh()
1863         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
1864                                         MaxNbOfIterations, MaxxAspectRatio, Method)
1865
1866     ## Parametrically smoothes the given elements
1867     #  @param IDsOfElements the list if ids of elements to smooth
1868     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
1869     #  Note that nodes built on edges and boundary nodes are always fixed.
1870     #  @param MaxNbOfIterations the maximum number of iterations
1871     #  @param MaxAspectRatio varies in range [1.0, inf]
1872     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
1873     #  @return TRUE in case of success, FALSE otherwise.
1874     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
1875                          MaxNbOfIterations, MaxAspectRatio, Method):
1876         if IDsOfElements == []:
1877             IDsOfElements = self.GetElementsId()
1878         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
1879                                             MaxNbOfIterations, MaxAspectRatio, Method)
1880
1881     ## Parametrically smoothes the elements which belong to the given object
1882     #  @param theObject the object to smooth
1883     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
1884     #  Note that nodes built on edges and boundary nodes are always fixed.
1885     #  @param MaxNbOfIterations the maximum number of iterations
1886     #  @param MaxAspectRatio varies in range [1.0, inf]
1887     #  @param Method Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
1888     #  @return TRUE in case of success, FALSE otherwise.
1889     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
1890                                MaxNbOfIterations, MaxAspectRatio, Method):
1891         if ( isinstance( theObject, Mesh )):
1892             theObject = theObject.GetMesh()
1893         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
1894                                                   MaxNbOfIterations, MaxAspectRatio, Method)
1895
1896     ## Converts the mesh to quadratic, deletes old elements, replacing
1897     #  them with quadratic with the same id.
1898     def ConvertToQuadratic(self, theForce3d):
1899         self.editor.ConvertToQuadratic(theForce3d)
1900
1901     ## Converts the mesh from quadratic to ordinary,
1902     #  deletes old quadratic elements, \n replacing
1903     #  them with ordinary mesh elements with the same id.
1904     #  @return TRUE in case of success, FALSE otherwise.
1905     def ConvertFromQuadratic(self):
1906         return self.editor.ConvertFromQuadratic()
1907
1908     ## Renumber mesh nodes
1909     def RenumberNodes(self):
1910         self.editor.RenumberNodes()
1911
1912     ## Renumber mesh elements
1913     def RenumberElements(self):
1914         self.editor.RenumberElements()
1915
1916     ## Generates new elements by rotation of the elements around the axis
1917     #  @param IDsOfElements the list of ids of elements to sweep
1918     #  @param Axix the axis of rotation, AxisStruct or line(geom object)
1919     #  @param AngleInRadians the angle of Rotation
1920     #  @param NbOfStep  the number of steps
1921     #  @param Tolerance tolerance
1922     #  @param MakeGroups forces the generation of new groups from existing ones
1923     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
1924     #                    of all steps, else - size of each step
1925     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
1926     def RotationSweep(self, IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance,
1927                       MakeGroups=False, TotalAngle=False):
1928         if IDsOfElements == []:
1929             IDsOfElements = self.GetElementsId()
1930         if ( isinstance( Axix, geompyDC.GEOM._objref_GEOM_Object)):
1931             Axix = self.smeshpyD.GetAxisStruct(Axix)
1932         if TotalAngle and NbOfSteps:
1933             AngleInRadians /= NbOfSteps
1934         if MakeGroups:
1935             return self.editor.RotationSweepMakeGroups(IDsOfElements, Axix,
1936                                                        AngleInRadians, NbOfSteps, Tolerance)
1937         self.editor.RotationSweep(IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance)
1938         return []
1939
1940     ## Generates new elements by rotation of the elements of object around the axis
1941     #  @param theObject object which elements should be sweeped
1942     #  @param Axix the axis of rotation, AxisStruct or line(geom object)
1943     #  @param AngleInRadians the angle of Rotation
1944     #  @param NbOfSteps number of steps
1945     #  @param Tolerance tolerance
1946     #  @param MakeGroups forces the generation of new groups from existing ones
1947     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
1948     #                    of all steps, else - size of each step
1949     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
1950     def RotationSweepObject(self, theObject, Axix, AngleInRadians, NbOfSteps, Tolerance,
1951                             MakeGroups=False, TotalAngle=False):
1952         if ( isinstance( theObject, Mesh )):
1953             theObject = theObject.GetMesh()
1954         if ( isinstance( Axix, geompyDC.GEOM._objref_GEOM_Object)):
1955             Axix = self.smeshpyD.GetAxisStruct(Axix)
1956         if TotalAngle and NbOfSteps:
1957             AngleInRadians /= NbOfSteps
1958         if MakeGroups:
1959             return self.editor.RotationSweepObjectMakeGroups(theObject, Axix, AngleInRadians,
1960                                                              NbOfSteps, Tolerance)
1961         self.editor.RotationSweepObject(theObject, Axix, AngleInRadians, NbOfSteps, Tolerance)
1962         return []
1963
1964     ## Generates new elements by extrusion of the elements with given ids
1965     #  @param IDsOfElements the list of elements ids for extrusion
1966     #  @param StepVector vector, defining the direction and value of extrusion
1967     #  @param NbOfSteps the number of steps
1968     #  @param MakeGroups forces the generation of new groups from existing ones
1969     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
1970     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False):
1971         if IDsOfElements == []:
1972             IDsOfElements = self.GetElementsId()
1973         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
1974             StepVector = self.smeshpyD.GetDirStruct(StepVector)
1975         if MakeGroups:
1976             return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
1977         self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
1978         return []
1979
1980     ## Generates new elements by extrusion of the elements with given ids
1981     #  @param IDsOfElements is ids of elements
1982     #  @param StepVector vector, defining the direction and value of extrusion
1983     #  @param NbOfSteps the number of steps
1984     #  @param ExtrFlags sets flags for extrusion
1985     #  @param SewTolerance uses for comparing locations of nodes if flag
1986     #         EXTRUSION_FLAG_SEW is set
1987     #  @param MakeGroups forces the generation of new groups from existing ones
1988     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
1989     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance, MakeGroups=False):
1990         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
1991             StepVector = self.smeshpyD.GetDirStruct(StepVector)
1992         if MakeGroups:
1993             return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
1994                                                            ExtrFlags, SewTolerance)
1995         self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
1996                                       ExtrFlags, SewTolerance)
1997         return []
1998
1999     ## Generates new elements by extrusion of the elements which belong to the object
2000     #  @param theObject the object which elements should be processed
2001     #  @param StepVector vector, defining the direction and value of extrusion
2002     #  @param NbOfSteps the number of steps
2003     #  @param MakeGroups forces the generation of new groups from existing ones
2004     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2005     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
2006         if ( isinstance( theObject, Mesh )):
2007             theObject = theObject.GetMesh()
2008         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
2009             StepVector = self.smeshpyD.GetDirStruct(StepVector)
2010         if MakeGroups:
2011             return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
2012         self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
2013         return []
2014
2015     ## Generates new elements by extrusion of the elements which belong to the object
2016     #  @param theObject object which elements should be processed
2017     #  @param StepVector vector, defining the direction and value of extrusion
2018     #  @param NbOfSteps the number of steps
2019     #  @param MakeGroups to generate new groups from existing ones
2020     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2021     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
2022         if ( isinstance( theObject, Mesh )):
2023             theObject = theObject.GetMesh()
2024         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
2025             StepVector = self.smeshpyD.GetDirStruct(StepVector)
2026         if MakeGroups:
2027             return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
2028         self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
2029         return []
2030
2031     ## Generates new elements by extrusion of the elements which belong to the object
2032     #  @param theObject object which elements should be processed
2033     #  @param StepVector vector, defining the direction and value of extrusion
2034     #  @param NbOfSteps the number of steps
2035     #  @param MakeGroups forces the generation of new groups from existing ones
2036     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2037     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
2038         if ( isinstance( theObject, Mesh )):
2039             theObject = theObject.GetMesh()
2040         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
2041             StepVector = self.smeshpyD.GetDirStruct(StepVector)
2042         if MakeGroups:
2043             return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
2044         self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
2045         return []
2046
2047     ## Generates new elements by extrusion of the given elements
2048     #  The path of extrusion must be a meshed edge.
2049     #  @param IDsOfElements ids of elements
2050     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2051     #  @param PathShape shape(edge) defines the sub-mesh for the path
2052     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
2053     #  @param HasAngles allows the shape to be rotated around the path
2054     #                   to get the resulting mesh in a helical fashion
2055     #  @param Angles list of angles
2056     #  @param HasRefPoint allows using the reference point
2057     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
2058     #         The User can specify any point as the Reference Point.
2059     #  @param MakeGroups forces the generation of new groups from existing ones
2060     #  @param LinearVariation forces the computation of rotation angles as linear
2061     #                         variation of the given Angles along path steps
2062     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
2063     #          only SMESH::Extrusion_Error otherwise
2064     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
2065                            HasAngles, Angles, HasRefPoint, RefPoint,
2066                            MakeGroups=False, LinearVariation=False):
2067         if IDsOfElements == []:
2068             IDsOfElements = self.GetElementsId()
2069         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
2070             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
2071             pass
2072         if ( isinstance( PathMesh, Mesh )):
2073             PathMesh = PathMesh.GetMesh()
2074         if HasAngles and Angles and LinearVariation:
2075             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
2076             pass
2077         if MakeGroups:
2078             return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
2079                                                             PathShape, NodeStart, HasAngles,
2080                                                             Angles, HasRefPoint, RefPoint)
2081         return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
2082                                               NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
2083
2084     ## Generates new elements by extrusion of the elements which belong to the object
2085     #  The path of extrusion must be a meshed edge.
2086     #  @param IDsOfElements is ids of elements
2087     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
2088     #  @param PathShape shape(edge) defines the sub-mesh for the path
2089     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
2090     #  @param HasAngles allows the shape to be rotated around the path
2091     #                   to get the resulting mesh in a helical fashion
2092     #  @param Angles list of angles
2093     #  @param HasRefPoint allows using the reference point
2094     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
2095     #         The User can specify any point as the Reference Point.
2096     #  @param MakeGroups forces the generation of new groups from existing ones
2097     #  @param LinearVariation forces the computation of rotation angles as linear
2098     #                         variation of the given Angles along path steps
2099     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
2100     #          only SMESH::Extrusion_Error otherwise
2101     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
2102                                  HasAngles, Angles, HasRefPoint, RefPoint,
2103                                  MakeGroups=False, LinearVariation=False):
2104         if ( isinstance( theObject, Mesh )):
2105             theObject = theObject.GetMesh()
2106         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
2107             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
2108         if ( isinstance( PathMesh, Mesh )):
2109             PathMesh = PathMesh.GetMesh()
2110         if HasAngles and Angles and LinearVariation:
2111             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
2112             pass
2113         if MakeGroups:
2114             return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
2115                                                                   PathShape, NodeStart, HasAngles,
2116                                                                   Angles, HasRefPoint, RefPoint)
2117         return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
2118                                                     NodeStart, HasAngles, Angles, HasRefPoint,
2119                                                     RefPoint)
2120
2121     ## Creates a symmetrical copy of mesh elements
2122     #  @param IDsOfElements list of elements ids
2123     #  @param Mirror is AxisStruct or geom object(point, line, plane)
2124     #  @param theMirrorType is  POINT, AXIS or PLANE
2125     #  If the Mirror is a geom object this parameter is unnecessary
2126     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
2127     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
2128     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2129     def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
2130         if IDsOfElements == []:
2131             IDsOfElements = self.GetElementsId()
2132         if ( isinstance( Mirror, geompyDC.GEOM._objref_GEOM_Object)):
2133             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
2134         if Copy and MakeGroups:
2135             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
2136         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
2137         return []
2138
2139     ## Creates a new mesh by a symmetrical copy of mesh elements
2140     #  @param IDsOfElements the list of elements ids
2141     #  @param Mirror is AxisStruct or geom object (point, line, plane)
2142     #  @param theMirrorType is  POINT, AXIS or PLANE
2143     #  If the Mirror is a geom object this parameter is unnecessary
2144     #  @param MakeGroups to generate new groups from existing ones
2145     #  @param NewMeshName a name of the new mesh to create
2146     #  @return instance of Mesh class
2147     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
2148         if IDsOfElements == []:
2149             IDsOfElements = self.GetElementsId()
2150         if ( isinstance( Mirror, geompyDC.GEOM._objref_GEOM_Object)):
2151             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
2152         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
2153                                           MakeGroups, NewMeshName)
2154         return Mesh(self.smeshpyD,self.geompyD,mesh)
2155
2156     ## Creates a symmetrical copy of the object
2157     #  @param theObject mesh, submesh or group
2158     #  @param Mirror AxisStruct or geom object (point, line, plane)
2159     #  @param theMirrorType is  POINT, AXIS or PLANE
2160     #  If the Mirror is a geom object this parameter is unnecessary
2161     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
2162     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
2163     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2164     def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
2165         if ( isinstance( theObject, Mesh )):
2166             theObject = theObject.GetMesh()
2167         if ( isinstance( Mirror, geompyDC.GEOM._objref_GEOM_Object)):
2168             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
2169         if Copy and MakeGroups:
2170             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
2171         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
2172         return []
2173
2174     ## Creates a new mesh by a symmetrical copy of the object
2175     #  @param theObject mesh, submesh or group
2176     #  @param Mirror AxisStruct or geom object (point, line, plane)
2177     #  @param theMirrorType POINT, AXIS or PLANE
2178     #  If the Mirror is a geom object this parameter is unnecessary
2179     #  @param MakeGroups forces the generation of new groups from existing ones
2180     #  @param NewMeshName the name of the new mesh to create
2181     #  @return instance of Mesh class
2182     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
2183         if ( isinstance( theObject, Mesh )):
2184             theObject = theObject.GetMesh()
2185         if (isinstance(Mirror, geompyDC.GEOM._objref_GEOM_Object)):
2186             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
2187         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
2188                                                 MakeGroups, NewMeshName)
2189         return Mesh( self.smeshpyD,self.geompyD,mesh )
2190
2191     ## Translates the elements
2192     #  @param IDsOfElements list of elements ids
2193     #  @param Vector the direction of translation (DirStruct or vector)
2194     #  @param Copy allows copying the translated elements
2195     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
2196     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2197     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
2198         if IDsOfElements == []:
2199             IDsOfElements = self.GetElementsId()
2200         if ( isinstance( Vector, geompyDC.GEOM._objref_GEOM_Object)):
2201             Vector = self.smeshpyD.GetDirStruct(Vector)
2202         if Copy and MakeGroups:
2203             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
2204         self.editor.Translate(IDsOfElements, Vector, Copy)
2205         return []
2206
2207     ## Creates a new mesh of translated elements
2208     #  @param IDsOfElements list of elements ids
2209     #  @param Vector the direction of translation (DirStruct or vector)
2210     #  @param MakeGroups forces the generation of new groups from existing ones
2211     #  @param NewMeshName the name of the newly created mesh
2212     #  @return instance of Mesh class
2213     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
2214         if IDsOfElements == []:
2215             IDsOfElements = self.GetElementsId()
2216         if ( isinstance( Vector, geompyDC.GEOM._objref_GEOM_Object)):
2217             Vector = self.smeshpyD.GetDirStruct(Vector)
2218         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
2219         return Mesh ( self.smeshpyD, self.geompyD, mesh )
2220
2221     ## Translates the object
2222     #  @param theObject the object to translate (mesh, submesh, or group)
2223     #  @param Vector direction of translation (DirStruct or geom vector)
2224     #  @param Copy allows copying the translated elements
2225     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
2226     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2227     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
2228         if ( isinstance( theObject, Mesh )):
2229             theObject = theObject.GetMesh()
2230         if ( isinstance( Vector, geompyDC.GEOM._objref_GEOM_Object)):
2231             Vector = self.smeshpyD.GetDirStruct(Vector)
2232         if Copy and MakeGroups:
2233             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
2234         self.editor.TranslateObject(theObject, Vector, Copy)
2235         return []
2236
2237     ## Creates a new mesh from the translated object
2238     #  @param theObject the object to translate (mesh, submesh, or group)
2239     #  @param Vector the direction of translation (DirStruct or geom vector)
2240     #  @param MakeGroups forces the generation of new groups from existing ones
2241     #  @param NewMeshName the name of the newly created mesh
2242     #  @return instance of Mesh class
2243     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
2244         if (isinstance(theObject, Mesh)):
2245             theObject = theObject.GetMesh()
2246         if (isinstance(Vector, geompyDC.GEOM._objref_GEOM_Object)):
2247             Vector = self.smeshpyD.GetDirStruct(Vector)
2248         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
2249         return Mesh( self.smeshpyD, self.geompyD, mesh )
2250
2251     ## Rotates the elements
2252     #  @param IDsOfElements list of elements ids
2253     #  @param Axis the axis of rotation (AxisStruct or geom line)
2254     #  @param AngleInRadians the angle of rotation (in radians)
2255     #  @param Copy allows copying the rotated elements
2256     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
2257     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2258     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
2259         if IDsOfElements == []:
2260             IDsOfElements = self.GetElementsId()
2261         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
2262             Axis = self.smeshpyD.GetAxisStruct(Axis)
2263         if Copy and MakeGroups:
2264             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
2265         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
2266         return []
2267
2268     ## Creates a new mesh of rotated elements
2269     #  @param IDsOfElements list of element ids
2270     #  @param Axis the axis of rotation (AxisStruct or geom line)
2271     #  @param AngleInRadians the angle of rotation (in radians)
2272     #  @param MakeGroups forces the generation of new groups from existing ones
2273     #  @param NewMeshName the name of the newly created mesh
2274     #  @return instance of Mesh class
2275     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
2276         if IDsOfElements == []:
2277             IDsOfElements = self.GetElementsId()
2278         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
2279             Axis = self.smeshpyD.GetAxisStruct(Axis)
2280         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
2281                                           MakeGroups, NewMeshName)
2282         return Mesh( self.smeshpyD, self.geompyD, mesh )
2283
2284     ## Rotates the object
2285     #  @param theObject the object to rotate( mesh, submesh, or group)
2286     #  @param Axis the axis of rotation (AxisStruct or geom line)
2287     #  @param AngleInRadians the angle of rotation (in radians)
2288     #  @param Copy allows copying the rotated elements
2289     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
2290     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
2291     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
2292         if (isinstance(theObject, Mesh)):
2293             theObject = theObject.GetMesh()
2294         if (isinstance(Axis, geompyDC.GEOM._objref_GEOM_Object)):
2295             Axis = self.smeshpyD.GetAxisStruct(Axis)
2296         if Copy and MakeGroups:
2297             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
2298         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
2299         return []
2300
2301     ## Creates a new mesh from the rotated object
2302     #  @param theObject the object to rotate (mesh, submesh, or group)
2303     #  @param Axis the axis of rotation (AxisStruct or geom line)
2304     #  @param AngleInRadians the angle of rotation (in radians)
2305     #  @param MakeGroups forces the generation of new groups from existing ones
2306     #  @param NewMeshName the name of the newly created mesh
2307     #  @return instance of Mesh class
2308     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
2309         if (isinstance( theObject, Mesh )):
2310             theObject = theObject.GetMesh()
2311         if (isinstance(Axis, geompyDC.GEOM._objref_GEOM_Object)):
2312             Axis = self.smeshpyD.GetAxisStruct(Axis)
2313         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
2314                                                        MakeGroups, NewMeshName)
2315         return Mesh( self.smeshpyD, self.geompyD, mesh )
2316
2317     ## Finds groups of ajacent nodes within Tolerance.
2318     #  @param Tolerance the value of tolerance
2319     #  @return the list of groups of nodes
2320     def FindCoincidentNodes (self, Tolerance):
2321         return self.editor.FindCoincidentNodes(Tolerance)
2322
2323     ## Finds groups of ajacent nodes within Tolerance.
2324     #  @param Tolerance the value of tolerance
2325     #  @param SubMeshOrGroup SubMesh or Group
2326     #  @return the list of groups of nodes
2327     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance):
2328         return self.editor.FindCoincidentNodesOnPart(SubMeshOrGroup, Tolerance)
2329
2330     ## Merges nodes
2331     #  @param GroupsOfNodes the list of groups of nodes
2332     def MergeNodes (self, GroupsOfNodes):
2333         self.editor.MergeNodes(GroupsOfNodes)
2334
2335     ## Finds the elements built on the same nodes.
2336     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
2337     #  @return a list of groups of equal elements
2338     def FindEqualElements (self, MeshOrSubMeshOrGroup):
2339         return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
2340
2341     ## Merges elements in each given group.
2342     #  @param GroupsOfElementsID groups of elements for merging
2343     def MergeElements(self, GroupsOfElementsID):
2344         self.editor.MergeElements(GroupsOfElementsID)
2345
2346     ## Leaves one element and removes all other elements built on the same nodes.
2347     def MergeEqualElements(self):
2348         self.editor.MergeEqualElements()
2349
2350     ## Sews free borders
2351     #  @return SMESH::Sew_Error
2352     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2353                         FirstNodeID2, SecondNodeID2, LastNodeID2,
2354                         CreatePolygons, CreatePolyedrs):
2355         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2356                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
2357                                           CreatePolygons, CreatePolyedrs)
2358
2359     ## Sews conform free borders
2360     #  @return SMESH::Sew_Error
2361     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2362                                FirstNodeID2, SecondNodeID2):
2363         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2364                                                  FirstNodeID2, SecondNodeID2)
2365
2366     ## Sews border to side
2367     #  @return SMESH::Sew_Error
2368     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2369                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
2370         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2371                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
2372
2373     ## Sews two sides of a mesh. The nodes belonging to Side1 are
2374     #  merged with the nodes of elements of Side2.
2375     #  The number of elements in theSide1 and in theSide2 must be
2376     #  equal and they should have similar nodal connectivity.
2377     #  The nodes to merge should belong to side borders and
2378     #  the first node should be linked to the second.
2379     #  @return SMESH::Sew_Error
2380     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
2381                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2382                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
2383         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
2384                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2385                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
2386
2387     ## Sets new nodes for the given element.
2388     #  @param ide the element id
2389     #  @param newIDs nodes ids
2390     #  @return If the number of nodes does not correspond to the type of element - returns false
2391     def ChangeElemNodes(self, ide, newIDs):
2392         return self.editor.ChangeElemNodes(ide, newIDs)
2393
2394     ## If during the last operation of MeshEditor some nodes were
2395     #  created, this method returns the list of their IDs, \n
2396     #  if new nodes were not created - returns empty list
2397     #  @return the list of integer values (can be empty)
2398     def GetLastCreatedNodes(self):
2399         return self.editor.GetLastCreatedNodes()
2400
2401     ## If during the last operation of MeshEditor some elements were
2402     #  created this method returns the list of their IDs, \n
2403     #  if new elements were not created - returns empty list
2404     #  @return the list of integer values (can be empty)
2405     def GetLastCreatedElems(self):
2406         return self.editor.GetLastCreatedElems()
2407
2408 ## The mother class to define algorithm, it is not recommended to use it directly.
2409 #
2410 #  More details.
2411 class Mesh_Algorithm:
2412     #  @class Mesh_Algorithm
2413     #  @brief Class Mesh_Algorithm
2414
2415     #def __init__(self,smesh):
2416     #    self.smesh=smesh
2417     def __init__(self):
2418         self.mesh = None
2419         self.geom = None
2420         self.subm = None
2421         self.algo = None
2422
2423     ## Finds a hypothesis in the study by its type name and parameters.
2424     #  Finds only the hypotheses created in smeshpyD engine.
2425     #  @return SMESH.SMESH_Hypothesis
2426     def FindHypothesis (self, hypname, args, CompareMethod, smeshpyD):
2427         study = smeshpyD.GetCurrentStudy()
2428         #to do: find component by smeshpyD object, not by its data type
2429         scomp = study.FindComponent(smeshpyD.ComponentDataType())
2430         if scomp is not None:
2431             res,hypRoot = scomp.FindSubObject(SMESH.Tag_HypothesisRoot)
2432             # Check if the root label of the hypotheses exists
2433             if res and hypRoot is not None:
2434                 iter = study.NewChildIterator(hypRoot)
2435                 # Check all published hypotheses
2436                 while iter.More():
2437                     hypo_so_i = iter.Value()
2438                     attr = hypo_so_i.FindAttribute("AttributeIOR")[1]
2439                     if attr is not None:
2440                         anIOR = attr.Value()
2441                         hypo_o_i = salome.orb.string_to_object(anIOR)
2442                         if hypo_o_i is not None:
2443                             # Check if this is a hypothesis
2444                             hypo_i = hypo_o_i._narrow(SMESH.SMESH_Hypothesis)
2445                             if hypo_i is not None:
2446                                 # Check if the hypothesis belongs to current engine
2447                                 if smeshpyD.GetObjectId(hypo_i) > 0:
2448                                     # Check if this is the required hypothesis
2449                                     if hypo_i.GetName() == hypname:
2450                                         # Check arguments
2451                                         if CompareMethod(hypo_i, args):
2452                                             # found!!!
2453                                             return hypo_i
2454                                         pass
2455                                     pass
2456                                 pass
2457                             pass
2458                         pass
2459                     iter.Next()
2460                     pass
2461                 pass
2462             pass
2463         return None
2464
2465     ## Finds the algorithm in the study by its type name.
2466     #  Finds only the algorithms, which have been created in smeshpyD engine.
2467     #  @return SMESH.SMESH_Algo
2468     def FindAlgorithm (self, algoname, smeshpyD):
2469         study = smeshpyD.GetCurrentStudy()
2470         #to do: find component by smeshpyD object, not by its data type
2471         scomp = study.FindComponent(smeshpyD.ComponentDataType())
2472         if scomp is not None:
2473             res,hypRoot = scomp.FindSubObject(SMESH.Tag_AlgorithmsRoot)
2474             # Check if the root label of the algorithms exists
2475             if res and hypRoot is not None:
2476                 iter = study.NewChildIterator(hypRoot)
2477                 # Check all published algorithms
2478                 while iter.More():
2479                     algo_so_i = iter.Value()
2480                     attr = algo_so_i.FindAttribute("AttributeIOR")[1]
2481                     if attr is not None:
2482                         anIOR = attr.Value()
2483                         algo_o_i = salome.orb.string_to_object(anIOR)
2484                         if algo_o_i is not None:
2485                             # Check if this is an algorithm
2486                             algo_i = algo_o_i._narrow(SMESH.SMESH_Algo)
2487                             if algo_i is not None:
2488                                 # Checks if the algorithm belongs to the current engine
2489                                 if smeshpyD.GetObjectId(algo_i) > 0:
2490                                     # Check if this is the required algorithm
2491                                     if algo_i.GetName() == algoname:
2492                                         # found!!!
2493                                         return algo_i
2494                                     pass
2495                                 pass
2496                             pass
2497                         pass
2498                     iter.Next()
2499                     pass
2500                 pass
2501             pass
2502         return None
2503
2504     ## If the algorithm is global, returns 0; \n
2505     #  else returns the submesh associated to this algorithm.
2506     def GetSubMesh(self):
2507         return self.subm
2508
2509     ## Returns the wrapped mesher.
2510     def GetAlgorithm(self):
2511         return self.algo
2512
2513     ## Gets the list of hypothesis that can be used with this algorithm
2514     def GetCompatibleHypothesis(self):
2515         mylist = []
2516         if self.algo:
2517             mylist = self.algo.GetCompatibleHypothesis()
2518         return mylist
2519
2520     ## Gets the name of the algorithm
2521     def GetName(self):
2522         GetName(self.algo)
2523
2524     ## Sets the name to the algorithm
2525     def SetName(self, name):
2526         SetName(self.algo, name)
2527
2528     ## Gets the id of the algorithm
2529     def GetId(self):
2530         return self.algo.GetId()
2531
2532     ## Private method.
2533     def Create(self, mesh, geom, hypo, so="libStdMeshersEngine.so"):
2534         if geom is None:
2535             raise RuntimeError, "Attemp to create " + hypo + " algoritm on None shape"
2536         algo = self.FindAlgorithm(hypo, mesh.smeshpyD)
2537         if algo is None:
2538             algo = mesh.smeshpyD.CreateHypothesis(hypo, so)
2539             pass
2540         self.Assign(algo, mesh, geom)
2541         return self.algo
2542
2543     ## Private method
2544     def Assign(self, algo, mesh, geom):
2545         if geom is None:
2546             raise RuntimeError, "Attemp to create " + algo + " algoritm on None shape"
2547         self.mesh = mesh
2548         piece = mesh.geom
2549         if not geom:
2550             self.geom = piece
2551         else:
2552             self.geom = geom
2553             name = GetName(geom)
2554             if name==NO_NAME:
2555                 name = mesh.geompyD.SubShapeName(geom, piece)
2556                 mesh.geompyD.addToStudyInFather(piece, geom, name)
2557             self.subm = mesh.mesh.GetSubMesh(geom, algo.GetName())
2558
2559         self.algo = algo
2560         status = mesh.mesh.AddHypothesis(self.geom, self.algo)
2561         TreatHypoStatus( status, algo.GetName(), GetName(self.geom), True )
2562
2563     def CompareHyp (self, hyp, args):
2564         print "CompareHyp is not implemented for ", self.__class__.__name__, ":", hyp.GetName()
2565         return False
2566
2567     def CompareEqualHyp (self, hyp, args):
2568         return True
2569
2570     ## Private method
2571     def Hypothesis (self, hyp, args=[], so="libStdMeshersEngine.so",
2572                     UseExisting=0, CompareMethod=""):
2573         hypo = None
2574         if UseExisting:
2575             if CompareMethod == "": CompareMethod = self.CompareHyp
2576             hypo = self.FindHypothesis(hyp, args, CompareMethod, self.mesh.smeshpyD)
2577             pass
2578         if hypo is None:
2579             hypo = self.mesh.smeshpyD.CreateHypothesis(hyp, so)
2580             a = ""
2581             s = "="
2582             i = 0
2583             n = len(args)
2584             while i<n:
2585                 a = a + s + str(args[i])
2586                 s = ","
2587                 i = i + 1
2588                 pass
2589             SetName(hypo, hyp + a)
2590             pass
2591         status = self.mesh.mesh.AddHypothesis(self.geom, hypo)
2592         TreatHypoStatus( status, GetName(hypo), GetName(self.geom), 0 )
2593         return hypo
2594
2595
2596 # Public class: Mesh_Segment
2597 # --------------------------
2598
2599 ## Class to define a segment 1D algorithm for discretization
2600 #
2601 #  More details.
2602 class Mesh_Segment(Mesh_Algorithm):
2603
2604     ## Private constructor.
2605     def __init__(self, mesh, geom=0):
2606         Mesh_Algorithm.__init__(self)
2607         self.Create(mesh, geom, "Regular_1D")
2608
2609     ## Defines "LocalLength" hypothesis to cut an edge in several segments with the same length
2610     #  @param l for the length of segments that cut an edge
2611     #  @param UseExisting if ==true - searches for an  existing hypothesis created with
2612     #                    the same parameters, else (default) - creates a new one
2613     #  @param p precision, used for calculation of the number of segments.
2614     #           The precision should be a positive, meaningful value within the range [0,1].
2615     #           In general, the number of segments is calculated with the formula:
2616     #           nb = ceil((edge_length / l) - p)
2617     #           Function ceil rounds its argument to the higher integer.
2618     #           So, p=0 means rounding of (edge_length / l) to the higher integer,
2619     #               p=0.5 means rounding of (edge_length / l) to the nearest integer,
2620     #               p=1 means rounding of (edge_length / l) to the lower integer.
2621     #           Default value is 1e-07.
2622     #  @return an instance of StdMeshers_LocalLength hypothesis
2623     def LocalLength(self, l, UseExisting=0, p=1e-07):
2624         hyp = self.Hypothesis("LocalLength", [l,p], UseExisting=UseExisting,
2625                               CompareMethod=self.CompareLocalLength)
2626         hyp.SetLength(l)
2627         hyp.SetPrecision(p)
2628         return hyp
2629
2630     ## Private method
2631     ## Checks if the given "LocalLength" hypothesis has the same parameters as the given arguments
2632     def CompareLocalLength(self, hyp, args):
2633         if IsEqual(hyp.GetLength(), args[0]):
2634             return IsEqual(hyp.GetPrecision(), args[1])
2635         return False
2636
2637     ## Defines "NumberOfSegments" hypothesis to cut an edge in a fixed number of segments
2638     #  @param n for the number of segments that cut an edge
2639     #  @param s for the scale factor (optional)
2640     #  @param UseExisting if ==true - searches for an existing hypothesis created with
2641     #                     the same parameters, else (default) - create a new one
2642     #  @return an instance of StdMeshers_NumberOfSegments hypothesis
2643     def NumberOfSegments(self, n, s=[], UseExisting=0):
2644         if s == []:
2645             hyp = self.Hypothesis("NumberOfSegments", [n], UseExisting=UseExisting,
2646                                   CompareMethod=self.CompareNumberOfSegments)
2647         else:
2648             hyp = self.Hypothesis("NumberOfSegments", [n,s], UseExisting=UseExisting,
2649                                   CompareMethod=self.CompareNumberOfSegments)
2650             hyp.SetDistrType( 1 )
2651             hyp.SetScaleFactor(s)
2652         hyp.SetNumberOfSegments(n)
2653         return hyp
2654
2655     ## Private method
2656     ## Checks if the given "NumberOfSegments" hypothesis has the same parameters as the given arguments
2657     def CompareNumberOfSegments(self, hyp, args):
2658         if hyp.GetNumberOfSegments() == args[0]:
2659             if len(args) == 1:
2660                 return True
2661             else:
2662                 if hyp.GetDistrType() == 1:
2663                     if IsEqual(hyp.GetScaleFactor(), args[1]):
2664                         return True
2665         return False
2666
2667     ## Defines "Arithmetic1D" hypothesis to cut an edge in several segments with increasing arithmetic length
2668     #  @param start defines the length of the first segment
2669     #  @param end   defines the length of the last  segment
2670     #  @param UseExisting if ==true - searches for an existing hypothesis created with
2671     #                     the same parameters, else (default) - creates a new one
2672     #  @return an instance of StdMeshers_Arithmetic1D hypothesis
2673     def Arithmetic1D(self, start, end, UseExisting=0):
2674         hyp = self.Hypothesis("Arithmetic1D", [start, end], UseExisting=UseExisting,
2675                               CompareMethod=self.CompareArithmetic1D)
2676         hyp.SetLength(start, 1)
2677         hyp.SetLength(end  , 0)
2678         return hyp
2679
2680     ## Private method
2681     ## Check if the given "Arithmetic1D" hypothesis has the same parameters as the given arguments
2682     def CompareArithmetic1D(self, hyp, args):
2683         if IsEqual(hyp.GetLength(1), args[0]):
2684             if IsEqual(hyp.GetLength(0), args[1]):
2685                 return True
2686         return False
2687
2688     ## Defines "StartEndLength" hypothesis to cut an edge in several segments with increasing geometric length
2689     #  @param start defines the length of the first segment
2690     #  @param end   defines the length of the last  segment
2691     #  @param UseExisting if ==true - searches for an existing hypothesis created with
2692     #                     the same parameters, else (default) - creates a new one
2693     #  @return an instance of StdMeshers_StartEndLength hypothesis
2694     def StartEndLength(self, start, end, UseExisting=0):
2695         hyp = self.Hypothesis("StartEndLength", [start, end], UseExisting=UseExisting,
2696                               CompareMethod=self.CompareStartEndLength)
2697         hyp.SetLength(start, 1)
2698         hyp.SetLength(end  , 0)
2699         return hyp
2700
2701     ## Check if the given "StartEndLength" hypothesis has the same parameters as the given arguments
2702     def CompareStartEndLength(self, hyp, args):
2703         if IsEqual(hyp.GetLength(1), args[0]):
2704             if IsEqual(hyp.GetLength(0), args[1]):
2705                 return True
2706         return False
2707
2708     ## Defines "Deflection1D" hypothesis
2709     #  @param d for the deflection
2710     #  @param UseExisting if ==true - searches for an existing hypothesis created with
2711     #                     the same parameters, else (default) - create a new one
2712     def Deflection1D(self, d, UseExisting=0):
2713         hyp = self.Hypothesis("Deflection1D", [d], UseExisting=UseExisting,
2714                               CompareMethod=self.CompareDeflection1D)
2715         hyp.SetDeflection(d)
2716         return hyp
2717
2718     ## Check if the given "Deflection1D" hypothesis has the same parameters as the given arguments
2719     def CompareDeflection1D(self, hyp, args):
2720         return IsEqual(hyp.GetDeflection(), args[0])
2721
2722     ## Defines "Propagation" hypothesis that propagates all other hypotheses on all other edges that are at
2723     #  the opposite side in case of quadrangular faces
2724     def Propagation(self):
2725         return self.Hypothesis("Propagation", UseExisting=1, CompareMethod=self.CompareEqualHyp)
2726
2727     ## Defines "AutomaticLength" hypothesis
2728     #  @param fineness for the fineness [0-1]
2729     #  @param UseExisting if ==true - searches for an existing hypothesis created with the
2730     #                     same parameters, else (default) - create a new one
2731     def AutomaticLength(self, fineness=0, UseExisting=0):
2732         hyp = self.Hypothesis("AutomaticLength",[fineness],UseExisting=UseExisting,
2733                               CompareMethod=self.CompareAutomaticLength)
2734         hyp.SetFineness( fineness )
2735         return hyp
2736
2737     ## Checks if the given "AutomaticLength" hypothesis has the same parameters as the given arguments
2738     def CompareAutomaticLength(self, hyp, args):
2739         return IsEqual(hyp.GetFineness(), args[0])
2740
2741     ## Defines "SegmentLengthAroundVertex" hypothesis
2742     #  @param length for the segment length
2743     #  @param vertex for the length localization: the vertex index [0,1] | vertex object.
2744     #         Any other integer value means that the hypothesis will be set on the
2745     #         whole 1D shape, where Mesh_Segment algorithm is assigned.
2746     #  @param UseExisting if ==true - searches for an  existing hypothesis created with
2747     #                   the same parameters, else (default) - creates a new one
2748     def LengthNearVertex(self, length, vertex=0, UseExisting=0):
2749         import types
2750         store_geom = self.geom
2751         if type(vertex) is types.IntType:
2752             if vertex == 0 or vertex == 1:
2753                 vertex = self.mesh.geompyD.SubShapeAllSorted(self.geom, geompyDC.ShapeType["VERTEX"])[vertex]
2754                 self.geom = vertex
2755                 pass
2756             pass
2757         else:
2758             self.geom = vertex
2759             pass
2760         ### 0D algorithm
2761         if self.geom is None:
2762             raise RuntimeError, "Attemp to create SegmentAroundVertex_0D algoritm on None shape"
2763         name = GetName(self.geom)
2764         if name == NO_NAME:
2765             piece = self.mesh.geom
2766             name = self.mesh.geompyD.SubShapeName(self.geom, piece)
2767             self.mesh.geompyD.addToStudyInFather(piece, self.geom, name)
2768         algo = self.FindAlgorithm("SegmentAroundVertex_0D", self.mesh.smeshpyD)
2769         if algo is None:
2770             algo = self.mesh.smeshpyD.CreateHypothesis("SegmentAroundVertex_0D", "libStdMeshersEngine.so")
2771             pass
2772         status = self.mesh.mesh.AddHypothesis(self.geom, algo)
2773         TreatHypoStatus(status, "SegmentAroundVertex_0D", name, True)
2774         ###
2775         hyp = self.Hypothesis("SegmentLengthAroundVertex", [length], UseExisting=UseExisting,
2776                               CompareMethod=self.CompareLengthNearVertex)
2777         self.geom = store_geom
2778         hyp.SetLength( length )
2779         return hyp
2780
2781     ## Checks if the given "LengthNearVertex" hypothesis has the same parameters as the given arguments
2782     def CompareLengthNearVertex(self, hyp, args):
2783         return IsEqual(hyp.GetLength(), args[0])
2784
2785     ## Defines "QuadraticMesh" hypothesis, forcing construction of quadratic edges.
2786     #  If the 2D mesher sees that all boundary edges are quadratic,
2787     #  it generates quadratic faces, else it generates linear faces using
2788     #  medium nodes as if they are vertices.
2789     #  The 3D mesher generates quadratic volumes only if all boundary faces
2790     #  are quadratic, else it fails.
2791     def QuadraticMesh(self):
2792         hyp = self.Hypothesis("QuadraticMesh", UseExisting=1, CompareMethod=self.CompareEqualHyp)
2793         return hyp
2794
2795 # Public class: Mesh_CompositeSegment
2796 # --------------------------
2797
2798 ## Defines a segment 1D algorithm for discretization
2799 #  
2800 class Mesh_CompositeSegment(Mesh_Segment):
2801
2802     ## Private constructor.
2803     def __init__(self, mesh, geom=0):
2804         self.Create(mesh, geom, "CompositeSegment_1D")
2805
2806
2807 # Public class: Mesh_Segment_Python
2808 # ---------------------------------
2809
2810 ## Defines a segment 1D algorithm for discretization with python function
2811 #
2812 class Mesh_Segment_Python(Mesh_Segment):
2813
2814     ## Private constructor.
2815     def __init__(self, mesh, geom=0):
2816         import Python1dPlugin
2817         self.Create(mesh, geom, "Python_1D", "libPython1dEngine.so")
2818
2819     ## Defines "PythonSplit1D" hypothesis
2820     #  @param n for the number of segments that cut an edge
2821     #  @param func for the python function that calculates the length of all segments
2822     #  @param UseExisting if ==true - searches for the existing hypothesis created with
2823     #                     the same parameters, else (default) - creates a new one
2824     def PythonSplit1D(self, n, func, UseExisting=0):
2825         hyp = self.Hypothesis("PythonSplit1D", [n], "libPython1dEngine.so",
2826                               UseExisting=UseExisting, CompareMethod=self.ComparePythonSplit1D)
2827         hyp.SetNumberOfSegments(n)
2828         hyp.SetPythonLog10RatioFunction(func)
2829         return hyp
2830
2831     ## Checks if the given "PythonSplit1D" hypothesis has the same parameters as the given arguments
2832     def ComparePythonSplit1D(self, hyp, args):
2833         #if hyp.GetNumberOfSegments() == args[0]:
2834         #    if hyp.GetPythonLog10RatioFunction() == args[1]:
2835         #        return True
2836         return False
2837
2838 # Public class: Mesh_Triangle
2839 # ---------------------------
2840
2841 ## Defines a triangle 2D algorithm
2842 #
2843 class Mesh_Triangle(Mesh_Algorithm):
2844
2845     # default values
2846     algoType = 0
2847     params = 0
2848
2849     _angleMeshS = 8
2850     _gradation  = 1.1
2851
2852     ## Private constructor.
2853     def __init__(self, mesh, algoType, geom=0):
2854         Mesh_Algorithm.__init__(self)
2855
2856         self.algoType = algoType
2857         if algoType == MEFISTO:
2858             self.Create(mesh, geom, "MEFISTO_2D")
2859             pass
2860         elif algoType == BLSURF:
2861             import BLSURFPlugin
2862             self.Create(mesh, geom, "BLSURF", "libBLSURFEngine.so")
2863             self.SetPhysicalMesh()
2864         elif algoType == NETGEN:
2865             if noNETGENPlugin:
2866                 print "Warning: NETGENPlugin module unavailable"
2867                 pass
2868             self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
2869             pass
2870         elif algoType == NETGEN_2D:
2871             if noNETGENPlugin:
2872                 print "Warning: NETGENPlugin module unavailable"
2873                 pass
2874             self.Create(mesh, geom, "NETGEN_2D_ONLY", "libNETGENEngine.so")
2875             pass
2876
2877     ## Defines "MaxElementArea" hypothesis basing on the definition of the maximum area of each triangle
2878     #  @param area for the maximum area of each triangle
2879     #  @param UseExisting if ==true - searches for an  existing hypothesis created with the
2880     #                     same parameters, else (default) - creates a new one
2881     #
2882     #  Only for algoType == MEFISTO || NETGEN_2D
2883     def MaxElementArea(self, area, UseExisting=0):
2884         if self.algoType == MEFISTO or self.algoType == NETGEN_2D:
2885             hyp = self.Hypothesis("MaxElementArea", [area], UseExisting=UseExisting,
2886                                   CompareMethod=self.CompareMaxElementArea)
2887             hyp.SetMaxElementArea(area)
2888             return hyp
2889         elif self.algoType == NETGEN:
2890             print "Netgen 1D-2D algo doesn't support this hypothesis"
2891             return None
2892
2893     ## Checks if the given "MaxElementArea" hypothesis has the same parameters as the given arguments
2894     def CompareMaxElementArea(self, hyp, args):
2895         return IsEqual(hyp.GetMaxElementArea(), args[0])
2896
2897     ## Defines "LengthFromEdges" hypothesis to build triangles
2898     #  based on the length of the edges taken from the wire
2899     #
2900     #  Only for algoType == MEFISTO || NETGEN_2D
2901     def LengthFromEdges(self):
2902         if self.algoType == MEFISTO or self.algoType == NETGEN_2D:
2903             hyp = self.Hypothesis("LengthFromEdges", UseExisting=1, CompareMethod=self.CompareEqualHyp)
2904             return hyp
2905         elif self.algoType == NETGEN:
2906             print "Netgen 1D-2D algo doesn't support this hypothesis"
2907             return None
2908
2909     ## Sets a way to define size of mesh elements to generate
2910     #  @param thePhysicalMesh is: DefaultSize or Custom
2911     #  Parameter of BLSURF algo
2912     def SetPhysicalMesh(self, thePhysicalMesh=DefaultSize):
2913         if self.params == 0:
2914             self.Parameters()
2915         self.params.SetPhysicalMesh(thePhysicalMesh)
2916
2917     ## Sets size of mesh elements to generate
2918     #  Parameter of BLSURF algo
2919     def SetPhySize(self, theVal):
2920         if self.params == 0:
2921             self.Parameters()
2922         self.params.SetPhySize(theVal)
2923
2924     ## Sets a way to define maximum angular deflection of mesh from CAD model
2925     #  @param theGeometricMesh is: DefaultGeom or Custom
2926     #  Parameter of BLSURF algo
2927     def SetGeometricMesh(self, theGeometricMesh=0):
2928         if self.params == 0:
2929             self.Parameters()
2930         if self.params.GetPhysicalMesh() == 0: theGeometricMesh = 1
2931         self.params.SetGeometricMesh(theGeometricMesh)
2932
2933     ## Sets angular deflection (in degrees) of mesh from CAD model
2934     #  Parameter of BLSURF algo
2935     def SetAngleMeshS(self, theVal=_angleMeshS):
2936         if self.params == 0:
2937             self.Parameters()
2938         if self.params.GetGeometricMesh() == 0: theVal = self._angleMeshS
2939         self.params.SetAngleMeshS(theVal)
2940
2941     ## Sets maximal allowed ratio between the lengths of two adjacent edges
2942     #  Parameter of BLSURF algo
2943     def SetGradation(self, theVal=_gradation):
2944         if self.params == 0:
2945             self.Parameters()
2946         if self.params.GetGeometricMesh() == 0: theVal = self._gradation
2947         self.params.SetGradation(theVal)
2948
2949     ## Sets topology usage way defining how mesh conformity is assured:
2950     # FromCAD, PreProcess or PreProcessPlus
2951     # FromCAD - mesh conformity is assured by conformity of a shape
2952     # PreProcess or PreProcessPlus - by pre-processing a CAD model
2953     #  Parameter of BLSURF algo
2954     def SetTopology(self, way):
2955         if self.params == 0:
2956             self.Parameters()
2957         self.params.SetTopology(way)
2958
2959     ## To respect geometrical edges or not
2960     #  Parameter of BLSURF algo
2961     def SetDecimesh(self, toIgnoreEdges=False):
2962         if self.params == 0:
2963             self.Parameters()
2964         self.params.SetDecimesh(toIgnoreEdges)
2965
2966     ## Sets QuadAllowed flag
2967     #
2968     #  Only for algoType == NETGEN || NETGEN_2D || BLSURF
2969     def SetQuadAllowed(self, toAllow=True):
2970         if self.algoType == NETGEN_2D:
2971             if toAllow: # add QuadranglePreference
2972                 self.Hypothesis("QuadranglePreference", UseExisting=1, CompareMethod=self.CompareEqualHyp)
2973             else:       # remove QuadranglePreference
2974                 for hyp in self.mesh.GetHypothesisList( self.geom ):
2975                     if hyp.GetName() == "QuadranglePreference":
2976                         self.mesh.RemoveHypothesis( self.geom, hyp )
2977                         pass
2978                     pass
2979                 pass
2980             return
2981         if self.params == 0:
2982             self.Parameters()
2983         if self.params:
2984             self.params.SetQuadAllowed(toAllow)
2985             return
2986
2987     ## Defines "Netgen 2D Parameters" hypothesis
2988     #
2989     #  Only for algoType == NETGEN
2990     def Parameters(self):
2991         if self.params:
2992             return self.params
2993         if self.algoType == NETGEN:
2994             self.params = self.Hypothesis("NETGEN_Parameters_2D", [],
2995                                           "libNETGENEngine.so", UseExisting=0)
2996             return self.params
2997         elif self.algoType == MEFISTO:
2998             print "Mefisto algo doesn't support NETGEN_Parameters_2D hypothesis"
2999             return None
3000         elif self.algoType == NETGEN_2D:
3001             print "NETGEN_2D_ONLY algo doesn't support 'NETGEN_Parameters_2D' hypothesis"
3002             print "NETGEN_2D_ONLY uses 'MaxElementArea' and 'LengthFromEdges' ones"
3003             return None
3004         elif self.algoType == BLSURF:
3005             self.params = self.Hypothesis("BLSURF_Parameters", [],
3006                                           "libBLSURFEngine.so", UseExisting=0)
3007             return self.params
3008         return None
3009
3010     ## Sets MaxSize
3011     #
3012     #  Only for algoType == NETGEN
3013     def SetMaxSize(self, theSize):
3014         if self.params == 0:
3015             self.Parameters()
3016         if self.params is not None:
3017             self.params.SetMaxSize(theSize)
3018
3019     ## Sets SecondOrder flag
3020     #
3021     #  Only for algoType == NETGEN
3022     def SetSecondOrder(self, theVal):
3023         if self.params == 0:
3024             self.Parameters()
3025         if self.params is not None:
3026             self.params.SetSecondOrder(theVal)
3027
3028     ## Sets Optimize flag
3029     #
3030     #  Only for algoType == NETGEN
3031     def SetOptimize(self, theVal):
3032         if self.params == 0:
3033             self.Parameters()
3034         if self.params is not None:
3035             self.params.SetOptimize(theVal)
3036
3037     ## Sets Fineness
3038     #  @param theFineness is:
3039     #  VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
3040     #
3041     #  Only for algoType == NETGEN
3042     def SetFineness(self, theFineness):
3043         if self.params == 0:
3044             self.Parameters()
3045         if self.params is not None:
3046             self.params.SetFineness(theFineness)
3047
3048     ## Sets GrowthRate
3049     #
3050     #  Only for algoType == NETGEN
3051     def SetGrowthRate(self, theRate):
3052         if self.params == 0:
3053             self.Parameters()
3054         if self.params is not None:
3055             self.params.SetGrowthRate(theRate)
3056
3057     ## Sets NbSegPerEdge
3058     #
3059     #  Only for algoType == NETGEN
3060     def SetNbSegPerEdge(self, theVal):
3061         if self.params == 0:
3062             self.Parameters()
3063         if self.params is not None:
3064             self.params.SetNbSegPerEdge(theVal)
3065
3066     ## Sets NbSegPerRadius
3067     #
3068     #  Only for algoType == NETGEN
3069     def SetNbSegPerRadius(self, theVal):
3070         if self.params == 0:
3071             self.Parameters()
3072         if self.params is not None:
3073             self.params.SetNbSegPerRadius(theVal)
3074
3075     pass
3076
3077
3078 # Public class: Mesh_Quadrangle
3079 # -----------------------------
3080
3081 ## Defines a quadrangle 2D algorithm
3082 #
3083 class Mesh_Quadrangle(Mesh_Algorithm):
3084
3085     ## Private constructor.
3086     def __init__(self, mesh, geom=0):
3087         Mesh_Algorithm.__init__(self)
3088         self.Create(mesh, geom, "Quadrangle_2D")
3089
3090     ## Defines "QuadranglePreference" hypothesis, forcing construction
3091     #  of quadrangles if the number of nodes on the opposite edges is not the same
3092     #  while the total number of nodes on edges is even
3093     def QuadranglePreference(self):
3094         hyp = self.Hypothesis("QuadranglePreference", UseExisting=1,
3095                               CompareMethod=self.CompareEqualHyp)
3096         return hyp
3097
3098 # Public class: Mesh_Tetrahedron
3099 # ------------------------------
3100
3101 ## Defines a tetrahedron 3D algorithm
3102 #
3103 class Mesh_Tetrahedron(Mesh_Algorithm):
3104
3105     params = 0
3106     algoType = 0
3107
3108     ## Private constructor.
3109     def __init__(self, mesh, algoType, geom=0):
3110         Mesh_Algorithm.__init__(self)
3111
3112         if algoType == NETGEN:
3113             self.Create(mesh, geom, "NETGEN_3D", "libNETGENEngine.so")
3114             pass
3115
3116         elif algoType == FULL_NETGEN:
3117             if noNETGENPlugin:
3118                 print "Warning: NETGENPlugin module has not been imported."
3119             self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
3120             pass
3121
3122         elif algoType == GHS3D:
3123             import GHS3DPlugin
3124             self.Create(mesh, geom, "GHS3D_3D" , "libGHS3DEngine.so")
3125             pass
3126
3127         self.algoType = algoType
3128
3129     ## Defines "MaxElementVolume" hypothesis to give the maximun volume of each tetrahedron
3130     #  @param vol for the maximum volume of each tetrahedron
3131     #  @param UseExisting if ==true - searches for the existing hypothesis created with
3132     #                   the same parameters, else (default) - creates a new one
3133     def MaxElementVolume(self, vol, UseExisting=0):
3134         hyp = self.Hypothesis("MaxElementVolume", [vol], UseExisting=UseExisting,
3135                               CompareMethod=self.CompareMaxElementVolume)
3136         hyp.SetMaxElementVolume(vol)
3137         return hyp
3138
3139     ## Checks if the given "MaxElementVolume" hypothesis has the same parameters as the given arguments
3140     def CompareMaxElementVolume(self, hyp, args):
3141         return IsEqual(hyp.GetMaxElementVolume(), args[0])
3142
3143     ## Defines "Netgen 3D Parameters" hypothesis
3144     def Parameters(self):
3145         if (self.algoType == FULL_NETGEN):
3146             self.params = self.Hypothesis("NETGEN_Parameters", [],
3147                                           "libNETGENEngine.so", UseExisting=0)
3148             return self.params
3149         if (self.algoType == GHS3D):
3150             self.params = self.Hypothesis("GHS3D_Parameters", [],
3151                                           "libGHS3DEngine.so", UseExisting=0)
3152             return self.params
3153         
3154         print "Algo doesn't support this hypothesis"
3155         return None
3156
3157     ## Sets MaxSize
3158     #  Parameter of FULL_NETGEN
3159     def SetMaxSize(self, theSize):
3160         if self.params == 0:
3161             self.Parameters()
3162         self.params.SetMaxSize(theSize)
3163
3164     ## Sets SecondOrder flag
3165     #  Parameter of FULL_NETGEN
3166     def SetSecondOrder(self, theVal):
3167         if self.params == 0:
3168             self.Parameters()
3169         self.params.SetSecondOrder(theVal)
3170
3171     ## Sets Optimize flag
3172     #  Parameter of FULL_NETGEN
3173     def SetOptimize(self, theVal):
3174         if self.params == 0:
3175             self.Parameters()
3176         self.params.SetOptimize(theVal)
3177
3178     ## Sets Fineness
3179     #  @param theFineness is:
3180     #  VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
3181     #  Parameter of FULL_NETGEN
3182     def SetFineness(self, theFineness):
3183         if self.params == 0:
3184             self.Parameters()
3185         self.params.SetFineness(theFineness)
3186
3187     ## Sets GrowthRate
3188     #  Parameter of FULL_NETGEN
3189     def SetGrowthRate(self, theRate):
3190         if self.params == 0:
3191             self.Parameters()
3192         self.params.SetGrowthRate(theRate)
3193
3194     ## Sets NbSegPerEdge
3195     #  Parameter of FULL_NETGEN
3196     def SetNbSegPerEdge(self, theVal):
3197         if self.params == 0:
3198             self.Parameters()
3199         self.params.SetNbSegPerEdge(theVal)
3200
3201     ## Sets NbSegPerRadius
3202     #  Parameter of FULL_NETGEN
3203     def SetNbSegPerRadius(self, theVal):
3204         if self.params == 0:
3205             self.Parameters()
3206         self.params.SetNbSegPerRadius(theVal)
3207
3208     ## To mesh "holes" in a solid or not. Default is to mesh.
3209     #  Parameter of GHS3D
3210     def SetToMeshHoles(self, toMesh):
3211         if self.params == 0: self.Parameters()
3212         self.params.SetToMeshHoles(toMesh)
3213
3214     ## Set Optimization level:
3215     #   None_Optimization, Light_Optimization, Medium_Optimization, Strong_Optimization.
3216     #  Default is Medium_Optimization
3217     #  Parameter of GHS3D
3218     def SetOptimizationLevel(self, level):
3219         if self.params == 0: self.Parameters()
3220         self.params.SetOptimizationLevel(level)
3221
3222     ## Maximal size of memory to be used by the algorithm (in Megabytes).
3223     #  Advanced parameter of GHS3D
3224     def SetMaximumMemory(self, MB):
3225         if self.params == 0: self.Parameters()
3226         self.params.SetMaximumMemory(MB)
3227
3228     ## Initial size of memory to be used by the algorithm (in Megabytes) in
3229     #  automatic memory adjustment mode
3230     #  Advanced parameter of GHS3D
3231     def SetInitialMemory(self, MB):
3232         if self.params == 0: self.Parameters()
3233         self.params.SetInitialMemory(MB)
3234
3235     ## Path to working directory
3236     #  Advanced parameter of GHS3D
3237     def SetWorkingDirectory(self, path):
3238         if self.params == 0: self.Parameters()
3239         self.params.SetWorkingDirectory(path)
3240
3241     ## To keep working files or remove them. Log file remains in case of errors anyway
3242     #  Advanced parameter of GHS3D
3243     def SetKeepFiles(self, toKeep):
3244         if self.params == 0: self.Parameters()
3245         self.params.SetKeepFiles(toKeep)
3246
3247 # Public class: Mesh_Hexahedron
3248 # ------------------------------
3249
3250 ## Defines a hexahedron 3D algorithm
3251 #
3252 class Mesh_Hexahedron(Mesh_Algorithm):
3253
3254     params = 0
3255     algoType = 0
3256
3257     ## Private constructor.
3258     def __init__(self, mesh, algoType=Hexa, geom=0):
3259         Mesh_Algorithm.__init__(self)
3260
3261         self.algoType = algoType
3262
3263         if algoType == Hexa:
3264             self.Create(mesh, geom, "Hexa_3D")
3265             pass
3266
3267         elif algoType == Hexotic:
3268             import HexoticPlugin
3269             self.Create(mesh, geom, "Hexotic_3D", "libHexoticEngine.so")
3270             pass
3271
3272     ## Defines "MinMaxQuad" hypothesis to give three hexotic parameters
3273     def MinMaxQuad(self, min=3, max=8, quad=True):
3274         self.params = self.Hypothesis("Hexotic_Parameters", [], "libHexoticEngine.so",
3275                                       UseExisting=0)
3276         self.params.SetHexesMinLevel(min)
3277         self.params.SetHexesMaxLevel(max)
3278         self.params.SetHexoticQuadrangles(quad)
3279         return self.params
3280
3281 # Deprecated, only for compatibility!
3282 # Public class: Mesh_Netgen
3283 # ------------------------------
3284
3285 ## Defines a NETGEN-based 2D or 3D algorithm
3286 #  that needs no discrete boundary (i.e. independent)
3287 #
3288 #  This class is deprecated, only for compatibility!
3289 #
3290 #  More details.
3291 class Mesh_Netgen(Mesh_Algorithm):
3292
3293     is3D = 0
3294
3295     ## Private constructor.
3296     def __init__(self, mesh, is3D, geom=0):
3297         Mesh_Algorithm.__init__(self)
3298
3299         if noNETGENPlugin:
3300             print "Warning: NETGENPlugin module has not been imported."
3301
3302         self.is3D = is3D
3303         if is3D:
3304             self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
3305             pass
3306
3307         else:
3308             self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
3309             pass
3310
3311     ## Defines the hypothesis containing parameters of the algorithm
3312     def Parameters(self):
3313         if self.is3D:
3314             hyp = self.Hypothesis("NETGEN_Parameters", [],
3315                                   "libNETGENEngine.so", UseExisting=0)
3316         else:
3317             hyp = self.Hypothesis("NETGEN_Parameters_2D", [],
3318                                   "libNETGENEngine.so", UseExisting=0)
3319         return hyp
3320
3321 # Public class: Mesh_Projection1D
3322 # ------------------------------
3323
3324 ## Defines a projection 1D algorithm
3325 #
3326 class Mesh_Projection1D(Mesh_Algorithm):
3327
3328     ## Private constructor.
3329     def __init__(self, mesh, geom=0):
3330         Mesh_Algorithm.__init__(self)
3331         self.Create(mesh, geom, "Projection_1D")
3332
3333     ## Defines "Source Edge" hypothesis, specifying a meshed edge, from where
3334     #  a mesh pattern is taken, and, optionally, the association of vertices
3335     #  between the source edge and a target edge (to which a hypothesis is assigned)
3336     #  @param edge from which nodes distribution is taken
3337     #  @param mesh from which nodes distribution is taken (optional)
3338     #  @param srcV a vertex of \a edge to associate with \a tgtV (optional)
3339     #  @param tgtV a vertex of \a the edge to which the algorithm is assigned,
3340     #  to associate with \a srcV (optional)
3341     #  @param UseExisting if ==true - searches for the existing hypothesis created with
3342     #                     the same parameters, else (default) - creates a new one
3343     def SourceEdge(self, edge, mesh=None, srcV=None, tgtV=None, UseExisting=0):
3344         hyp = self.Hypothesis("ProjectionSource1D", [edge,mesh,srcV,tgtV],
3345                               UseExisting=0)
3346                               #UseExisting=UseExisting, CompareMethod=self.CompareSourceEdge)
3347         hyp.SetSourceEdge( edge )
3348         if not mesh is None and isinstance(mesh, Mesh):
3349             mesh = mesh.GetMesh()
3350         hyp.SetSourceMesh( mesh )
3351         hyp.SetVertexAssociation( srcV, tgtV )
3352         return hyp
3353
3354     ## Checks if the given "SourceEdge" hypothesis has the same parameters as the given arguments
3355     #def CompareSourceEdge(self, hyp, args):
3356     #    # it does not seem to be useful to reuse the existing "SourceEdge" hypothesis
3357     #    return False
3358
3359
3360 # Public class: Mesh_Projection2D
3361 # ------------------------------
3362
3363 ## Defines a projection 2D algorithm
3364 #
3365 class Mesh_Projection2D(Mesh_Algorithm):
3366
3367     ## Private constructor.
3368     def __init__(self, mesh, geom=0):
3369         Mesh_Algorithm.__init__(self)
3370         self.Create(mesh, geom, "Projection_2D")
3371
3372     ## Defines "Source Face" hypothesis, specifying a meshed face, from where
3373     #  a mesh pattern is taken, and, optionally, the association of vertices
3374     #  between the source face and the target face (to which a hypothesis is assigned)
3375     #  @param face from which the mesh pattern is taken
3376     #  @param mesh from which the mesh pattern is taken (optional)
3377     #  @param srcV1 a vertex of \a face to associate with \a tgtV1 (optional)
3378     #  @param tgtV1 a vertex of \a the face to which the algorithm is assigned,
3379     #               to associate with \a srcV1 (optional)
3380     #  @param srcV2 a vertex of \a face to associate with \a tgtV1 (optional)
3381     #  @param tgtV2 a vertex of \a the face to which the algorithm is assigned,
3382     #               to associate with \a srcV2 (optional)
3383     #  @param UseExisting if ==true - forces the search for the existing hypothesis created with
3384     #                     the same parameters, else (default) - forces the creation a new one
3385     #
3386     #  Note: all association vertices must belong to one edge of a face
3387     def SourceFace(self, face, mesh=None, srcV1=None, tgtV1=None,
3388                    srcV2=None, tgtV2=None, UseExisting=0):
3389         hyp = self.Hypothesis("ProjectionSource2D", [face,mesh,srcV1,tgtV1,srcV2,tgtV2],
3390                               UseExisting=0)
3391                               #UseExisting=UseExisting, CompareMethod=self.CompareSourceFace)
3392         hyp.SetSourceFace( face )
3393         if not mesh is None and isinstance(mesh, Mesh):
3394             mesh = mesh.GetMesh()
3395         hyp.SetSourceMesh( mesh )
3396         hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
3397         return hyp
3398
3399     ## Checks if the given "SourceFace" hypothesis has the same parameters as the given arguments
3400     #def CompareSourceFace(self, hyp, args):
3401     #    # it does not seem to be useful to reuse the existing "SourceFace" hypothesis
3402     #    return False
3403
3404 # Public class: Mesh_Projection3D
3405 # ------------------------------
3406
3407 ## Defines a projection 3D algorithm
3408 #
3409 class Mesh_Projection3D(Mesh_Algorithm):
3410
3411     ## Private constructor.
3412     def __init__(self, mesh, geom=0):
3413         Mesh_Algorithm.__init__(self)
3414         self.Create(mesh, geom, "Projection_3D")
3415
3416     ## Defines the "Source Shape 3D" hypothesis, specifying a meshed solid, from where 
3417     #  the mesh pattern is taken, and, optionally, the  association of vertices
3418     #  between the source and the target solid  (to which a hipothesis is assigned)
3419     #  @param solid from where the mesh pattern is taken
3420     #  @param mesh from where the mesh pattern is taken (optional)
3421     #  @param srcV1 a vertex of \a solid to associate with \a tgtV1 (optional)
3422     #  @param tgtV1 a vertex of \a the solid where the algorithm is assigned,
3423     #  to associate with \a srcV1 (optional)
3424     #  @param srcV2 a vertex of \a solid to associate with \a tgtV1 (optional)
3425     #  @param tgtV2 a vertex of \a the solid to which the algorithm is assigned,
3426     #  to associate with \a srcV2 (optional)
3427     #  @param UseExisting - if ==true - searches for the existing hypothesis created with
3428     #                     the same parameters, else (default) - creates a new one
3429     #
3430     #  Note: association vertices must belong to one edge of a solid
3431     def SourceShape3D(self, solid, mesh=0, srcV1=0, tgtV1=0,
3432                       srcV2=0, tgtV2=0, UseExisting=0):
3433         hyp = self.Hypothesis("ProjectionSource3D",
3434                               [solid,mesh,srcV1,tgtV1,srcV2,tgtV2],
3435                               UseExisting=0)
3436                               #UseExisting=UseExisting, CompareMethod=self.CompareSourceShape3D)
3437         hyp.SetSource3DShape( solid )
3438         if not mesh is None and isinstance(mesh, Mesh):
3439             mesh = mesh.GetMesh()
3440         hyp.SetSourceMesh( mesh )
3441         hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
3442         return hyp
3443
3444     ## Checks if the given "SourceShape3D" hypothesis has the same parameters as given arguments
3445     #def CompareSourceShape3D(self, hyp, args):
3446     #    # seems to be not really useful to reuse existing "SourceShape3D" hypothesis
3447     #    return False
3448
3449
3450 # Public class: Mesh_Prism
3451 # ------------------------
3452
3453 ## Defines a 3D extrusion algorithm
3454 #
3455 class Mesh_Prism3D(Mesh_Algorithm):
3456
3457     ## Private constructor.
3458     def __init__(self, mesh, geom=0):
3459         Mesh_Algorithm.__init__(self)
3460         self.Create(mesh, geom, "Prism_3D")
3461
3462 # Public class: Mesh_RadialPrism
3463 # -------------------------------
3464
3465 ## Defines a Radial Prism 3D algorithm
3466 #
3467 class Mesh_RadialPrism3D(Mesh_Algorithm):
3468
3469     ## Private constructor.
3470     def __init__(self, mesh, geom=0):
3471         Mesh_Algorithm.__init__(self)
3472         self.Create(mesh, geom, "RadialPrism_3D")
3473
3474         self.distribHyp = self.Hypothesis("LayerDistribution", UseExisting=0)
3475         self.nbLayers = None
3476
3477     ## Return 3D hypothesis holding the 1D one
3478     def Get3DHypothesis(self):
3479         return self.distribHyp
3480
3481     ## Private method creating a 1D hypothesis and storing it in the LayerDistribution
3482     #  hypothesis. Returns the created hypothesis
3483     def OwnHypothesis(self, hypType, args=[], so="libStdMeshersEngine.so"):
3484         #print "OwnHypothesis",hypType
3485         if not self.nbLayers is None:
3486             self.mesh.GetMesh().RemoveHypothesis( self.geom, self.nbLayers )
3487             self.mesh.GetMesh().AddHypothesis( self.geom, self.distribHyp )
3488         study = self.mesh.smeshpyD.GetCurrentStudy() # prevents publishing own 1D hypothesis
3489         hyp = self.mesh.smeshpyD.CreateHypothesis(hypType, so)
3490         self.mesh.smeshpyD.SetCurrentStudy( study ) # enables publishing
3491         self.distribHyp.SetLayerDistribution( hyp )
3492         return hyp
3493
3494     ## Defines "NumberOfLayers" hypothesis, specifying the number of layers of
3495     #  prisms to build between the inner and outer shells
3496     #  @param UseExisting if ==true - searches for the existing hypothesis created with
3497     #                    the same parameters, else (default) - creates a new one
3498     def NumberOfLayers(self, n, UseExisting=0):
3499         self.mesh.GetMesh().RemoveHypothesis( self.geom, self.distribHyp )
3500         self.nbLayers = self.Hypothesis("NumberOfLayers", [n], UseExisting=UseExisting,
3501                                         CompareMethod=self.CompareNumberOfLayers)
3502         self.nbLayers.SetNumberOfLayers( n )
3503         return self.nbLayers
3504
3505     ## Checks if the given "NumberOfLayers" hypothesis has the same parameters as the given arguments
3506     def CompareNumberOfLayers(self, hyp, args):
3507         return IsEqual(hyp.GetNumberOfLayers(), args[0])
3508
3509     ## Defines "LocalLength" hypothesis, specifying the segment length
3510     #  to build between the inner and the outer shells
3511     #  @param l the length of segments
3512     #  @param p the precision of rounding
3513     def LocalLength(self, l, p=1e-07):
3514         hyp = self.OwnHypothesis("LocalLength", [l,p])
3515         hyp.SetLength(l)
3516         hyp.SetPrecision(p)
3517         return hyp
3518
3519     ## Defines "NumberOfSegments" hypothesis, specifying the number of layers of
3520     #  prisms to build between the inner and the outer shells.
3521     #  @param n the number of layers
3522     #  @param s the scale factor (optional)
3523     def NumberOfSegments(self, n, s=[]):
3524         if s == []:
3525             hyp = self.OwnHypothesis("NumberOfSegments", [n])
3526         else:
3527             hyp = self.OwnHypothesis("NumberOfSegments", [n,s])
3528             hyp.SetDistrType( 1 )
3529             hyp.SetScaleFactor(s)
3530         hyp.SetNumberOfSegments(n)
3531         return hyp
3532
3533     ## Defines "Arithmetic1D" hypothesis, specifying the distribution of segments
3534     #  to build between the inner and the outer shells with a length that changes in arithmetic progression
3535     #  @param start  the length of the first segment
3536     #  @param end    the length of the last  segment
3537     def Arithmetic1D(self, start, end ):
3538         hyp = self.OwnHypothesis("Arithmetic1D", [start, end])
3539         hyp.SetLength(start, 1)
3540         hyp.SetLength(end  , 0)
3541         return hyp
3542
3543     ## Defines "StartEndLength" hypothesis, specifying distribution of segments
3544     #  to build between the inner and the outer shells as geometric length increasing
3545     #  @param start for the length of the first segment
3546     #  @param end   for the length of the last  segment
3547     def StartEndLength(self, start, end):
3548         hyp = self.OwnHypothesis("StartEndLength", [start, end])
3549         hyp.SetLength(start, 1)
3550         hyp.SetLength(end  , 0)
3551         return hyp
3552
3553     ## Defines "AutomaticLength" hypothesis, specifying the number of segments
3554     #  to build between the inner and outer shells
3555     #  @param fineness defines the quality of the mesh within the range [0-1]
3556     def AutomaticLength(self, fineness=0):
3557         hyp = self.OwnHypothesis("AutomaticLength")
3558         hyp.SetFineness( fineness )
3559         return hyp
3560
3561 # Private class: Mesh_UseExisting
3562 # -------------------------------
3563 class Mesh_UseExisting(Mesh_Algorithm):
3564
3565     def __init__(self, dim, mesh, geom=0):
3566         if dim == 1:
3567             self.Create(mesh, geom, "UseExisting_1D")
3568         else:
3569             self.Create(mesh, geom, "UseExisting_2D")