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