Salome HOME
e68c3d19a2233c5499a4bfe12dfd45726c7c0573
[modules/smesh.git] / src / SMESH_SWIG / smesh.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 import salome
30 import geompy
31
32 import SMESH
33 from   SMESH import *
34
35 import StdMeshers
36
37 import SALOME
38
39 # import NETGENPlugin module if possible
40 noNETGENPlugin = 0
41 try:
42     import NETGENPlugin
43 except ImportError:
44     noNETGENPlugin = 1
45     pass
46     
47 # Types of algo
48 REGULAR    = 1
49 PYTHON     = 2
50 COMPOSITE  = 3
51
52 MEFISTO = 3
53 NETGEN  = 4
54 GHS3D   = 5
55 FULL_NETGEN = 6
56
57 # MirrorType enumeration
58 POINT = SMESH_MeshEditor.POINT
59 AXIS =  SMESH_MeshEditor.AXIS 
60 PLANE = SMESH_MeshEditor.PLANE
61
62 # Smooth_Method enumeration
63 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
64 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
65
66 # Fineness enumeration(for NETGEN)
67 VeryCoarse = 0
68 Coarse = 1
69 Moderate = 2
70 Fine = 3
71 VeryFine = 4
72 Custom = 5
73
74
75 NO_NAME = "NoName"
76
77
78 smesh = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
79 smesh.SetCurrentStudy(salome.myStudy)
80
81 # Global functions
82
83 ## Gets object name
84 def GetName(obj):
85     ior  = salome.orb.object_to_string(obj)
86     sobj = salome.myStudy.FindObjectIOR(ior)
87     if sobj is None:
88         return NO_NAME
89     else:
90         attr = sobj.FindAttribute("AttributeName")[1]
91         return attr.Value()
92
93 ## Sets name to object
94 def SetName(obj, name):
95     ior  = salome.orb.object_to_string(obj)
96     sobj = salome.myStudy.FindObjectIOR(ior)
97     if not sobj is None:
98         attr = sobj.FindAttribute("AttributeName")[1]
99         attr.SetValue(name)
100         
101 ## Returns long value from enumeration
102 #  Uses for SMESH.FunctorType enumeration
103 def EnumToLong(theItem):
104     return theItem._v
105
106 ## Get PointStruct from vertex
107 #  @param theVertex is GEOM object(vertex)
108 #  @return SMESH.PointStruct
109 def GetPointStruct(theVertex):
110     [x, y, z] = geompy.PointCoordinates(theVertex)
111     return PointStruct(x,y,z)
112
113 ## Get DirStruct from vector
114 #  @param theVector is GEOM object(vector)
115 #  @return SMESH.DirStruct
116 def GetDirStruct(theVector):
117     vertices = geompy.SubShapeAll( theVector, geompy.ShapeType["VERTEX"] )
118     if(len(vertices) != 2):
119         print "Error: vector object is incorrect."
120         return None
121     p1 = geompy.PointCoordinates(vertices[0])
122     p2 = geompy.PointCoordinates(vertices[1])
123     pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
124     dir = DirStruct(pnt)
125     return dir
126
127 ## Get AxisStruct from object
128 #  @param theObj is GEOM object(line or plane)
129 #  @return SMESH.AxisStruct
130 def GetAxisStruct(theObj):
131     edges = geompy.SubShapeAll( theObj, geompy.ShapeType["EDGE"] )
132     if len(edges) > 1:
133         vertex1, vertex2 = geompy.SubShapeAll( edges[0], geompy.ShapeType["VERTEX"] )
134         vertex3, vertex4 = geompy.SubShapeAll( edges[1], geompy.ShapeType["VERTEX"] )
135         vertex1 = geompy.PointCoordinates(vertex1)
136         vertex2 = geompy.PointCoordinates(vertex2)
137         vertex3 = geompy.PointCoordinates(vertex3)
138         vertex4 = geompy.PointCoordinates(vertex4)
139         v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
140         v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
141         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] ]
142         axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
143         return axis
144     elif len(edges) == 1:
145         vertex1, vertex2 = geompy.SubShapeAll( edges[0], geompy.ShapeType["VERTEX"] )
146         p1 = geompy.PointCoordinates( vertex1 )
147         p2 = geompy.PointCoordinates( vertex2 )
148         axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
149         return axis
150     return None
151
152 # From SMESH_Gen interface:
153 # ------------------------
154
155 ## Set the current mode
156 def SetEmbeddedMode( theMode ):
157     smesh.SetEmbeddedMode(theMode)
158
159 ## Get the current mode
160 def IsEmbeddedMode():
161     return smesh.IsEmbeddedMode()
162
163 ## Set the current study
164 def SetCurrentStudy( theStudy ):
165     smesh.SetCurrentStudy(theStudy)
166
167 ## Get the current study
168 def GetCurrentStudy():
169     return smesh.GetCurrentStudy()
170
171 ## Create Mesh object importing data from given UNV file
172 #  @return an instance of Mesh class
173 def CreateMeshesFromUNV( theFileName ):
174     aSmeshMesh = smesh.CreateMeshesFromUNV(theFileName)
175     aMesh = Mesh(aSmeshMesh)
176     return aMesh
177
178 ## Create Mesh object(s) importing data from given MED file
179 #  @return a list of Mesh class instances
180 def CreateMeshesFromMED( theFileName ):
181     aSmeshMeshes, aStatus = smesh.CreateMeshesFromMED(theFileName)
182     aMeshes = []
183     for iMesh in range(len(aSmeshMeshes)) :
184         aMesh = Mesh(aSmeshMeshes[iMesh])
185         aMeshes.append(aMesh)
186     return aMeshes, aStatus
187
188 ## Create Mesh object importing data from given STL file
189 #  @return an instance of Mesh class
190 def CreateMeshesFromSTL( theFileName ):
191     aSmeshMesh = smesh.CreateMeshesFromSTL(theFileName)
192     aMesh = Mesh(aSmeshMesh)
193     return aMesh
194
195 ## From SMESH_Gen interface
196 def GetSubShapesId( theMainObject, theListOfSubObjects ):
197     return smesh.GetSubShapesId(theMainObject, theListOfSubObjects)
198
199 ## From SMESH_Gen interface. Creates pattern
200 def GetPattern():
201     return smesh.GetPattern()
202
203
204
205 # Filtering. Auxiliary functions:
206 # ------------------------------
207
208 ## Creates an empty criterion
209 #  @return SMESH.Filter.Criterion
210 def GetEmptyCriterion():
211     Type = EnumToLong(FT_Undefined)
212     Compare = EnumToLong(FT_Undefined)
213     Threshold = 0
214     ThresholdStr = ""
215     ThresholdID = ""
216     UnaryOp = EnumToLong(FT_Undefined)
217     BinaryOp = EnumToLong(FT_Undefined)
218     Tolerance = 1e-07
219     TypeOfElement = ALL
220     Precision = -1 ##@1e-07
221     return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
222                             UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
223       
224 ## Creates a criterion by given parameters
225 #  @param elementType is the type of elements(NODE, EDGE, FACE, VOLUME)
226 #  @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
227 #  @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
228 #  @param Treshold is threshold value (range of ids as string, shape, numeric)
229 #  @param UnaryOp is FT_LogicalNOT or FT_Undefined
230 #  @param BinaryOp is binary logical operation FT_LogicalAND, FT_LogicalOR or
231 #                  FT_Undefined(must be for the last criterion in criteria)
232 #  @return SMESH.Filter.Criterion
233 def GetCriterion(elementType,
234                  CritType,
235                  Compare = FT_EqualTo,
236                  Treshold="",
237                  UnaryOp=FT_Undefined,
238                  BinaryOp=FT_Undefined):
239     aCriterion = GetEmptyCriterion()
240     aCriterion.TypeOfElement = elementType
241     aCriterion.Type = EnumToLong(CritType)
242         
243     aTreshold = Treshold
244         
245     if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
246         aCriterion.Compare = EnumToLong(Compare)
247     elif Compare == "=" or Compare == "==":
248         aCriterion.Compare = EnumToLong(FT_EqualTo)
249     elif Compare == "<":
250         aCriterion.Compare = EnumToLong(FT_LessThan)
251     elif Compare == ">":
252         aCriterion.Compare = EnumToLong(FT_MoreThan)
253     else:
254         aCriterion.Compare = EnumToLong(FT_EqualTo)
255         aTreshold = Compare
256
257     if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface, 
258                     FT_BelongToCylinder, FT_LyingOnGeom]:
259         # Check treshold
260         if isinstance(aTreshold, geompy.GEOM._objref_GEOM_Object):
261             aCriterion.ThresholdStr = GetName(aTreshold)
262             aCriterion.ThresholdID = salome.ObjectToID(aTreshold)
263         else:
264             print "Error: Treshold should be a shape."
265             return None
266     elif CritType == FT_RangeOfIds:
267         # Check treshold
268         if isinstance(aTreshold, str):
269             aCriterion.ThresholdStr = aTreshold
270         else:
271             print "Error: Treshold should be a string."
272             return None
273     elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_BadOrientedVolume]:
274         # Here we don't need treshold
275         if aTreshold ==  FT_LogicalNOT:
276             aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
277         elif aTreshold in [FT_LogicalAND, FT_LogicalOR]:
278             aCriterion.BinaryOp = aTreshold
279     else:
280         # Check treshold
281         try:
282             aTreshold = float(aTreshold)
283             aCriterion.Threshold = aTreshold
284         except:
285             print "Error: Treshold should be a number."
286             return None
287
288     if Treshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
289         aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
290
291     if Treshold in [FT_LogicalAND, FT_LogicalOR]:
292         aCriterion.BinaryOp = EnumToLong(Treshold)
293
294     if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
295         aCriterion.BinaryOp = EnumToLong(UnaryOp)
296
297     if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
298         aCriterion.BinaryOp = EnumToLong(BinaryOp)
299
300     return aCriterion
301
302 ## Creates filter by given parameters of criterion
303 #  @param elementType is the type of elements in the group
304 #  @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
305 #  @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
306 #  @param Treshold is threshold value (range of id ids as string, shape, numeric)
307 #  @param UnaryOp is FT_LogicalNOT or FT_Undefined
308 #  @return SMESH_Filter
309 def GetFilter(elementType,
310               CritType=FT_Undefined,
311               Compare=FT_EqualTo,
312               Treshold="",
313               UnaryOp=FT_Undefined):
314     aCriterion = GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
315     aFilterMgr = smesh.CreateFilterManager()
316     aFilter = aFilterMgr.CreateFilter()
317     aCriteria = []
318     aCriteria.append(aCriterion)
319     aFilter.SetCriteria(aCriteria)
320     return aFilter
321
322 ## Creates numerical functor by its type
323 #  @param theCrierion is FT_...; functor type
324 #  @return SMESH_NumericalFunctor
325 def GetFunctor(theCriterion):
326     aFilterMgr = smesh.CreateFilterManager()
327     if theCriterion == FT_AspectRatio:
328         return aFilterMgr.CreateAspectRatio()
329     elif theCriterion == FT_AspectRatio3D:
330         return aFilterMgr.CreateAspectRatio3D()
331     elif theCriterion == FT_Warping:
332         return aFilterMgr.CreateWarping()
333     elif theCriterion == FT_MinimumAngle:
334         return aFilterMgr.CreateMinimumAngle()
335     elif theCriterion == FT_Taper:
336         return aFilterMgr.CreateTaper()
337     elif theCriterion == FT_Skew:
338         return aFilterMgr.CreateSkew()
339     elif theCriterion == FT_Area:
340         return aFilterMgr.CreateArea()
341     elif theCriterion == FT_Volume3D:
342         return aFilterMgr.CreateVolume3D()
343     elif theCriterion == FT_MultiConnection:
344         return aFilterMgr.CreateMultiConnection()
345     elif theCriterion == FT_MultiConnection2D:
346         return aFilterMgr.CreateMultiConnection2D()
347     elif theCriterion == FT_Length:
348         return aFilterMgr.CreateLength()
349     elif theCriterion == FT_Length2D:
350         return aFilterMgr.CreateLength2D()
351     else:
352         print "Error: given parameter is not numerucal functor type."
353
354
355 ## Print error message if a hypothesis was not assigned.
356 def TreatHypoStatus(status, hypName, geomName, isAlgo):
357     if isAlgo:
358         hypType = "algorithm"
359     else:
360         hypType = "hypothesis"
361         pass
362     if status == HYP_UNKNOWN_FATAL :
363         reason = "for unknown reason"
364     elif status == HYP_INCOMPATIBLE :
365         reason = "this hypothesis mismatches algorithm"
366     elif status == HYP_NOTCONFORM :
367         reason = "not conform mesh would be built"
368     elif status == HYP_ALREADY_EXIST :
369         reason = hypType + " of the same dimension already assigned to this shape"
370     elif status == HYP_BAD_DIM :
371         reason = hypType + " mismatches shape"
372     elif status == HYP_CONCURENT :
373         reason = "there are concurrent hypotheses on sub-shapes"
374     elif status == HYP_BAD_SUBSHAPE :
375         reason = "shape is neither the main one, nor its subshape, nor a valid group"
376     elif status == HYP_BAD_GEOMETRY:
377         reason = "geometry mismatches algorithm's expectation"
378     elif status == HYP_HIDDEN_ALGO:
379         reason = "it is hidden by an algorithm of upper dimension generating all-dimensions elements"
380     elif status == HYP_HIDING_ALGO:
381         reason = "it hides algorithm(s) of lower dimension by generating all-dimensions elements"
382     else:
383         return
384     hypName = '"' + hypName + '"'
385     geomName= '"' + geomName+ '"'
386     if status < HYP_UNKNOWN_FATAL:
387         print hypName, "was assigned to",    geomName,"but", reason
388     else:
389         print hypName, "was not assigned to",geomName,":", reason
390         pass
391
392     
393     
394 ## Mother class to define algorithm, recommended to don't use directly.
395 #
396 #  More details.
397 class Mesh_Algorithm:
398     #  @class Mesh_Algorithm
399     #  @brief Class Mesh_Algorithm
400
401     mesh = 0
402     geom = 0
403     subm = 0
404     algo = 0
405     hypos = {}
406
407     def FindHypothesis(self,hypname, args):
408         key = "%s %s %s" % (self.__class__.__name__, hypname, args)
409         if Mesh_Algorithm.hypos.has_key( key ):
410             return Mesh_Algorithm.hypos[ key ]
411         return None
412
413     ## If the algorithm is global, return 0; \n
414     #  else return the submesh associated to this algorithm.
415     def GetSubMesh(self):
416         return self.subm
417
418     ## Return the wrapped mesher.
419     def GetAlgorithm(self):
420         return self.algo
421
422     ## Get list of hypothesis that can be used with this algorithm
423     def GetCompatibleHypothesis(self):
424         list = []
425         if self.algo:
426             list = self.algo.GetCompatibleHypothesis()
427         return list
428
429     ## Get name of algo
430     def GetName(self):
431         GetName(self.algo)
432
433     ## Set name to algo
434     def SetName(self, name):
435         SetName(self.algo, name)
436
437     ## Get id of algo
438     def GetId(self):
439         return self.algo.GetId()
440     
441     ## Private method.
442     def Create(self, mesh, geom, hypo, so="libStdMeshersEngine.so"):
443         if geom is None:
444             raise RuntimeError, "Attemp to create " + hypo + " algoritm on None shape"
445         algo = smesh.CreateHypothesis(hypo, so)
446         self.Assign(algo, mesh, geom)
447         return self.algo
448
449     ## Private method
450     def Assign(self, algo, mesh, geom):
451         if geom is None:
452             raise RuntimeError, "Attemp to create " + hypo + " algoritm on None shape"
453         self.mesh = mesh
454         piece = mesh.geom
455         if not geom:
456             self.geom = piece
457         else:
458             self.geom = geom
459             name = GetName(geom)
460             if name==NO_NAME:
461                 name = geompy.SubShapeName(geom, piece)
462                 geompy.addToStudyInFather(piece, geom, name)
463             self.subm = mesh.mesh.GetSubMesh(geom, algo.GetName())
464
465         self.algo = algo
466         status = mesh.mesh.AddHypothesis(self.geom, self.algo)
467         TreatHypoStatus( status, algo.GetName(), GetName(algo), True )
468
469     ## Private method
470     def Hypothesis(self, hyp, args=[], so="libStdMeshersEngine.so", UseExisting=0):
471         CreateNew = 1
472         if UseExisting:
473             hypo = self.FindHypothesis(hyp, args)
474             if hypo!=None: CreateNew = 0
475             pass
476         if CreateNew:
477             hypo = smesh.CreateHypothesis(hyp, so)
478             key = "%s %s %s" % (self.__class__.__name__, hyp, args)
479             Mesh_Algorithm.hypos[key] = hypo
480             a = ""
481             s = "="
482             i = 0
483             n = len(args)
484             while i<n:
485                 a = a + s + str(args[i])
486                 s = ","
487                 i = i + 1
488                 name = GetName(self.geom)
489             #SetName(hypo, name + "/" + hyp + a) - NPAL16198
490             SetName(hypo, hyp + a)
491             pass
492         status = self.mesh.mesh.AddHypothesis(self.geom, hypo)
493         TreatHypoStatus( status, hyp, GetName(hypo), 0 )
494         return hypo
495
496
497 # Public class: Mesh_Segment
498 # --------------------------
499
500 ## Class to define a segment 1D algorithm for discretization
501 #
502 #  More details.
503 class Mesh_Segment(Mesh_Algorithm):
504
505     algo = 0 # algorithm object common for all Mesh_Segment's
506
507     ## Private constructor.
508     def __init__(self, mesh, geom=0):
509         if not Mesh_Segment.algo:
510             Mesh_Segment.algo = self.Create(mesh, geom, "Regular_1D")
511         else:
512             self.Assign( Mesh_Segment.algo, mesh, geom)
513             pass
514
515     ## Define "LocalLength" hypothesis to cut an edge in several segments with the same length
516     #  @param l for the length of segments that cut an edge
517     #  @param UseExisting if ==true - search existing hypothesis created with
518     #                     same parameters, else (default) - create new
519     def LocalLength(self, l, UseExisting=0):
520         hyp = self.Hypothesis("LocalLength", [l], UseExisting=UseExisting)
521         hyp.SetLength(l)
522         return hyp
523         
524     ## Define "NumberOfSegments" hypothesis to cut an edge in several fixed number of segments
525     #  @param n for the number of segments that cut an edge
526     #  @param s for the scale factor (optional)
527     #  @param UseExisting if ==true - search existing hypothesis created with
528     #                     same parameters, else (default) - create new
529     def NumberOfSegments(self, n, s=[], UseExisting=0):
530         if s == []:
531             hyp = self.Hypothesis("NumberOfSegments", [n], UseExisting=UseExisting)
532         else:
533             hyp = self.Hypothesis("NumberOfSegments", [n,s], UseExisting=UseExisting)
534             hyp.SetDistrType( 1 )
535             hyp.SetScaleFactor(s)
536         hyp.SetNumberOfSegments(n)
537         return hyp
538         
539     ## Define "Arithmetic1D" hypothesis to cut an edge in several segments with arithmetic length increasing
540     #  @param start for the length of the first segment
541     #  @param end   for the length of the last  segment
542     #  @param UseExisting if ==true - search existing hypothesis created with
543     #                     same parameters, else (default) - create new
544     def Arithmetic1D(self, start, end, UseExisting=0):
545         hyp = self.Hypothesis("Arithmetic1D", [start, end], UseExisting=UseExisting)
546         hyp.SetLength(start, 1)
547         hyp.SetLength(end  , 0)
548         return hyp
549         
550     ## Define "StartEndLength" hypothesis to cut an edge in several segments with geometric length increasing
551     #  @param start for the length of the first segment
552     #  @param end   for the length of the last  segment
553     #  @param UseExisting if ==true - search existing hypothesis created with
554     #                     same parameters, else (default) - create new
555     def StartEndLength(self, start, end, UseExisting=0):
556         hyp = self.Hypothesis("StartEndLength", [start, end], UseExisting=UseExisting)
557         hyp.SetLength(start, 1)
558         hyp.SetLength(end  , 0)
559         return hyp
560         
561     ## Define "Deflection1D" hypothesis
562     #  @param d for the deflection
563     #  @param UseExisting if ==true - search existing hypothesis created with
564     #                     same parameters, else (default) - create new
565     def Deflection1D(self, d, UseExisting=0):
566         hyp = self.Hypothesis("Deflection1D", [d], UseExisting=UseExisting)
567         hyp.SetDeflection(d)
568         return hyp
569         
570     ## Define "Propagation" hypothesis that propagate all other hypothesis on all others edges that are in
571     #  the opposite side in the case of quadrangular faces
572     def Propagation(self):
573         return self.Hypothesis("Propagation", UseExisting=1)
574
575     ## Define "AutomaticLength" hypothesis
576     #  @param fineness for the fineness [0-1]
577     #  @param UseExisting if ==true - search existing hypothesis created with
578     #                     same parameters, else (default) - create new
579     def AutomaticLength(self, fineness=0, UseExisting=0):
580         hyp = self.Hypothesis("AutomaticLength",[fineness],UseExisting=UseExisting)
581         hyp.SetFineness( fineness )
582         return hyp
583
584     ## Define "SegmentLengthAroundVertex" hypothesis
585     #  @param length for the segment length
586     #  @param vertex for the length localization: vertex index [0,1] | verext object
587     #  @param UseExisting if ==true - search existing hypothesis created with
588     #                     same parameters, else (default) - create new
589     def LengthNearVertex(self, length, vertex=0, UseExisting=0):
590         import types
591         store_geom = self.geom
592         if vertex:
593             if type(vertex) is types.IntType:
594                 vertex = geompy.SubShapeAllSorted(self.geom,geompy.ShapeType["VERTEX"])[vertex]
595                 pass
596             self.geom = vertex
597             pass
598         hyp = self.Hypothesis("SegmentAroundVertex_0D",[length],UseExisting=UseExisting)
599         hyp = self.Hypothesis("SegmentLengthAroundVertex",[length],UseExisting=UseExisting)
600         self.geom = store_geom
601         hyp.SetLength( length )
602         return hyp
603
604     ## Define "QuadraticMesh" hypothesis, forcing construction of quadratic edges.
605     #  If the 2D mesher sees that all boundary edges are quadratic ones,
606     #  it generates quadratic faces, else it generates linear faces using
607     #  medium nodes as if they were vertex ones.
608     #  The 3D mesher generates quadratic volumes only if all boundary faces
609     #  are quadratic ones, else it fails.
610     def QuadraticMesh(self):
611         hyp = self.Hypothesis("QuadraticMesh", UseExisting=1)
612         return hyp
613
614 # Public class: Mesh_CompositeSegment
615 # --------------------------
616
617 ## Class to define a segment 1D algorithm for discretization
618 #
619 #  More details.
620 class Mesh_CompositeSegment(Mesh_Segment):
621
622     algo = 0 # algorithm object common for all Mesh_CompositeSegment's
623
624     ## Private constructor.
625     def __init__(self, mesh, geom=0):
626         if not Mesh_CompositeSegment.algo:
627             Mesh_CompositeSegment.algo = self.Create(mesh, geom, "CompositeSegment_1D")
628         else:
629             self.Assign( Mesh_CompositeSegment.algo, mesh, geom)
630             pass
631         
632
633 # Public class: Mesh_Segment_Python
634 # ---------------------------------
635
636 ## Class to define a segment 1D algorithm for discretization with python function
637 #
638 #  More details.
639 class Mesh_Segment_Python(Mesh_Segment):
640
641     algo = 0 # algorithm object common for all Mesh_Segment_Python's
642
643     ## Private constructor.
644     def __init__(self, mesh, geom=0):
645         import Python1dPlugin
646         if not Mesh_Segment_Python.algo:
647             Mesh_Segment_Python.algo = self.Create(mesh, geom, "Python_1D", "libPython1dEngine.so")
648         else:
649             self.Assign( Mesh_Segment_Python.algo, mesh, geom)
650             pass
651     
652     ## Define "PythonSplit1D" hypothesis based on the Erwan Adam patch, awaiting equivalent SALOME functionality
653     #  @param n for the number of segments that cut an edge
654     #  @param func for the python function that calculate the length of all segments
655     #  @param UseExisting if ==true - search existing hypothesis created with
656     #                     same parameters, else (default) - create new
657     def PythonSplit1D(self, n, func, UseExisting=0):
658         hyp = self.Hypothesis("PythonSplit1D", [n], "libPython1dEngine.so", UseExisting=UseExisting)
659         hyp.SetNumberOfSegments(n)
660         hyp.SetPythonLog10RatioFunction(func)
661         return hyp
662         
663 # Public class: Mesh_Triangle
664 # ---------------------------
665
666 ## Class to define a triangle 2D algorithm
667 #
668 #  More details.
669 class Mesh_Triangle(Mesh_Algorithm):
670
671     algoType = 0
672     params = 0
673    
674     algoMEF = 0 # algorithm object common for all Mesh_Triangle's
675     algoNET = 0 # algorithm object common for all Mesh_Triangle's
676
677     ## Private constructor.
678     def __init__(self, mesh, algoType, geom=0):
679         if algoType == MEFISTO:
680             if not Mesh_Triangle.algoMEF:
681                 Mesh_Triangle.algoMEF = self.Create(mesh, geom, "MEFISTO_2D")
682             else:
683                 self.Assign( Mesh_Triangle.algoMEF, mesh, geom)
684                 pass
685             pass
686         
687         elif algoType == NETGEN:
688             if noNETGENPlugin:
689                 print "Warning: NETGENPlugin module has not been imported."
690                 pass
691             if not Mesh_Triangle.algoNET:
692                 Mesh_Triangle.algoNET = self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
693             else:
694                 self.Assign( Mesh_Triangle.algoNET, mesh, geom)
695                 pass
696             pass
697
698         self.algoType = algoType
699
700     ## Define "MaxElementArea" hypothesis to give the maximun area of each triangles
701     #  @param area for the maximum area of each triangles
702     #  @param UseExisting if ==true - search existing hypothesis created with
703     #                     same parameters, else (default) - create new
704     def MaxElementArea(self, area, UseExisting=0):
705         if self.algoType == MEFISTO:
706             hyp = self.Hypothesis("MaxElementArea", [area], UseExisting=UseExisting)
707             hyp.SetMaxElementArea(area)
708             return hyp
709         elif self.algoType == NETGEN:
710             print "Netgen 1D-2D algo doesn't support this hypothesis"
711             return None
712             
713     ## Define "LengthFromEdges" hypothesis to build triangles based on the length of the edges taken from the wire
714     def LengthFromEdges(self):
715         if self.algoType == MEFISTO:
716             hyp = self.Hypothesis("LengthFromEdges", UseExisting=1)
717             return hyp
718         elif self.algoType == NETGEN:
719             print "Netgen 1D-2D algo doesn't support this hypothesis"
720             return None
721         
722     ## Define "Netgen 2D Parameters" hypothesis
723     def Parameters(self):
724         if self.algoType == NETGEN:
725             self.params = self.Hypothesis("NETGEN_Parameters_2D", [],
726                                           "libNETGENEngine.so", UseExisting=0)
727             return self.params
728         elif self.algoType == MEFISTO:
729             print "Mefisto algo doesn't support this hypothesis"
730             return None
731
732     ## Set MaxSize
733     def SetMaxSize(self, theSize):
734         if self.params == 0:
735             self.Parameters()
736         self.params.SetMaxSize(theSize)
737         
738     ## Set SecondOrder flag
739     def SetSecondOrder(seld, theVal):
740         if self.params == 0:
741             self.Parameters()
742         self.params.SetSecondOrder(theVal)
743
744     ## Set Optimize flag
745     def SetOptimize(self, theVal):
746         if self.params == 0:
747             self.Parameters()
748         self.params.SetOptimize(theVal)
749
750     ## Set Fineness
751     #  @param theFineness is:
752     #  VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
753     def SetFineness(self, theFineness):
754         if self.params == 0:
755             self.Parameters()
756         self.params.SetFineness(theFineness)
757         
758     ## Set GrowthRate  
759     def SetGrowthRate(self, theRate):
760         if self.params == 0:
761             self.Parameters()
762         self.params.SetGrowthRate(theRate)
763
764     ## Set NbSegPerEdge
765     def SetNbSegPerEdge(self, theVal):
766         if self.params == 0:
767             self.Parameters()
768         self.params.SetNbSegPerEdge(theVal)
769
770     ## Set NbSegPerRadius
771     def SetNbSegPerRadius(self, theVal):
772         if self.params == 0:
773             self.Parameters()
774         self.params.SetNbSegPerRadius(theVal)
775
776     ## Set QuadAllowed flag
777     def SetQuadAllowed(self, toAllow):
778         if self.params == 0:
779             self.Parameters()
780         self.params.SetQuadAllowed(toAllow)
781         
782     
783 # Public class: Mesh_Quadrangle
784 # -----------------------------
785
786 ## Class to define a quadrangle 2D algorithm
787 #
788 #  More details.
789 class Mesh_Quadrangle(Mesh_Algorithm):
790
791     algo = 0 # algorithm object common for all Mesh_Quadrangle's
792
793     ## Private constructor.
794     def __init__(self, mesh, geom=0):
795         if not Mesh_Quadrangle.algo:
796             Mesh_Quadrangle.algo = self.Create(mesh, geom, "Quadrangle_2D")
797         else:
798             self.Assign( Mesh_Quadrangle.algo, mesh, geom)
799             pass
800     
801     ## Define "QuadranglePreference" hypothesis, forcing construction
802     #  of quadrangles if the number of nodes on opposite edges is not the same
803     #  in the case where the global number of nodes on edges is even
804     def QuadranglePreference(self):
805         hyp = self.Hypothesis("QuadranglePreference", UseExisting=1)
806         return hyp
807     
808 # Public class: Mesh_Tetrahedron
809 # ------------------------------
810
811 ## Class to define a tetrahedron 3D algorithm
812 #
813 #  More details.
814 class Mesh_Tetrahedron(Mesh_Algorithm):
815
816     params = 0
817     algoType = 0
818
819     algoNET = 0 # algorithm object common for all Mesh_Tetrahedron's
820     algoGHS = 0 # algorithm object common for all Mesh_Tetrahedron's
821     algoFNET = 0 # algorithm object common for all Mesh_Tetrahedron's
822
823     ## Private constructor.
824     def __init__(self, mesh, algoType, geom=0):
825         if algoType == NETGEN:
826             if not Mesh_Tetrahedron.algoNET:
827                 Mesh_Tetrahedron.algoNET = self.Create(mesh, geom, "NETGEN_3D", "libNETGENEngine.so")
828             else:
829                 self.Assign( Mesh_Tetrahedron.algoNET, mesh, geom)
830                 pass
831             pass
832
833         elif algoType == GHS3D:
834             if not Mesh_Tetrahedron.algoGHS:
835                 import GHS3DPlugin
836                 Mesh_Tetrahedron.algoGHS = self.Create(mesh, geom, "GHS3D_3D" , "libGHS3DEngine.so")
837             else:
838                 self.Assign( Mesh_Tetrahedron.algoGHS, mesh, geom)
839                 pass
840             pass
841
842         elif algoType == FULL_NETGEN:
843             if noNETGENPlugin:
844                 print "Warning: NETGENPlugin module has not been imported."
845             if not Mesh_Tetrahedron.algoFNET:
846                 Mesh_Tetrahedron.algoFNET = self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
847             else:
848                 self.Assign( Mesh_Tetrahedron.algoFNET, mesh, geom)
849                 pass
850             pass
851
852         self.algoType = algoType
853
854     ## Define "MaxElementVolume" hypothesis to give the maximun volume of each tetrahedral
855     #  @param vol for the maximum volume of each tetrahedral
856     #  @param UseExisting if ==true - search existing hypothesis created with
857     #                     same parameters, else (default) - create new
858     def MaxElementVolume(self, vol, UseExisting=0):
859         hyp = self.Hypothesis("MaxElementVolume", [vol], UseExisting=UseExisting)
860         hyp.SetMaxElementVolume(vol)
861         return hyp
862
863     ## Define "Netgen 3D Parameters" hypothesis
864     def Parameters(self):
865         if (self.algoType == FULL_NETGEN):
866             self.params = self.Hypothesis("NETGEN_Parameters", [],
867                                           "libNETGENEngine.so", UseExisting=0)
868             return self.params
869         else:
870             print "Algo doesn't support this hypothesis"
871             return None 
872             
873     ## Set MaxSize
874     def SetMaxSize(self, theSize):
875         if self.params == 0:
876             self.Parameters()
877         self.params.SetMaxSize(theSize)
878         
879     ## Set SecondOrder flag
880     def SetSecondOrder(self, theVal):
881         if self.params == 0:
882             self.Parameters()
883         self.params.SetSecondOrder(theVal)
884
885     ## Set Optimize flag
886     def SetOptimize(self, theVal):
887         if self.params == 0:
888             self.Parameters()
889         self.params.SetOptimize(theVal)
890
891     ## Set Fineness
892     #  @param theFineness is:
893     #  VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
894     def SetFineness(self, theFineness):
895         if self.params == 0:
896             self.Parameters()
897         self.params.SetFineness(theFineness)
898         
899     ## Set GrowthRate  
900     def SetGrowthRate(self, theRate):
901         if self.params == 0:
902             self.Parameters()
903         self.params.SetGrowthRate(theRate)
904
905     ## Set NbSegPerEdge
906     def SetNbSegPerEdge(self, theVal):
907         if self.params == 0:
908             self.Parameters()
909         self.params.SetNbSegPerEdge(theVal)
910
911     ## Set NbSegPerRadius
912     def SetNbSegPerRadius(self, theVal):
913         if self.params == 0:
914             self.Parameters()
915         self.params.SetNbSegPerRadius(theVal)
916
917 # Public class: Mesh_Hexahedron
918 # ------------------------------
919
920 ## Class to define a hexahedron 3D algorithm
921 #
922 #  More details.
923 class Mesh_Hexahedron(Mesh_Algorithm):
924
925     algo = 0 # algorithm object common for all Mesh_Hexahedron's
926
927     ## Private constructor.
928     def __init__(self, mesh, geom=0):
929         if not Mesh_Hexahedron.algo:
930             Mesh_Hexahedron.algo = self.Create(mesh, geom, "Hexa_3D")
931         else:
932             self.Assign( Mesh_Hexahedron.algo, mesh, geom)
933             pass
934
935 # Deprecated, only for compatibility!
936 # Public class: Mesh_Netgen
937 # ------------------------------
938
939 ## Class to define a NETGEN-based 2D or 3D algorithm
940 #  that need no discrete boundary (i.e. independent)
941 #
942 #  This class is deprecated, only for compatibility!
943 #
944 #  More details.
945 class Mesh_Netgen(Mesh_Algorithm):
946
947     is3D = 0
948
949     algoNET23 = 0 # algorithm object common for all Mesh_Netgen's
950     algoNET2 = 0 # algorithm object common for all Mesh_Netgen's
951
952     ## Private constructor.
953     def __init__(self, mesh, is3D, geom=0):
954         if noNETGENPlugin:
955             print "Warning: NETGENPlugin module has not been imported."
956             
957         self.is3D = is3D
958         if is3D:
959             if not Mesh_Netgen.algoNET23:
960                 Mesh_Netgen.algoNET23 = self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
961             else:
962                 self.Assign( Mesh_Netgen.algoNET23, mesh, geom)
963                 pass
964             pass
965
966         else:
967             if not Mesh_Netgen.algoNET2:
968                 Mesh_Netgen.algoNET2 = self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
969             else:
970                 self.Assign( Mesh_Netgen.algoNET2, mesh, geom)
971                 pass
972             pass
973
974     ## Define hypothesis containing parameters of the algorithm
975     def Parameters(self):
976         if self.is3D:
977             hyp = self.Hypothesis("NETGEN_Parameters", [],
978                                   "libNETGENEngine.so", UseExisting=0)
979         else:
980             hyp = self.Hypothesis("NETGEN_Parameters_2D", [],
981                                   "libNETGENEngine.so", UseExisting=0)
982         return hyp
983
984 # Public class: Mesh_Projection1D
985 # ------------------------------
986
987 ## Class to define a projection 1D algorithm
988 #
989 #  More details.
990 class Mesh_Projection1D(Mesh_Algorithm):
991
992     algo = 0 # algorithm object common for all Mesh_Projection1D's
993
994     ## Private constructor.
995     def __init__(self, mesh, geom=0):
996         if not Mesh_Projection1D.algo:
997             Mesh_Projection1D.algo = self.Create(mesh, geom, "Projection_1D")
998         else:
999             self.Assign( Mesh_Projection1D.algo, mesh, geom)
1000             pass
1001
1002     ## Define "Source Edge" hypothesis, specifying a meshed edge to
1003     #  take a mesh pattern from, and optionally association of vertices
1004     #  between the source edge and a target one (where a hipothesis is assigned to)
1005     #  @param edge to take nodes distribution from
1006     #  @param mesh to take nodes distribution from (optional)
1007     #  @param srcV is vertex of \a edge to associate with \a tgtV (optional)
1008     #  @param tgtV is vertex of \a the edge where the algorithm is assigned,
1009     #  to associate with \a srcV (optional)
1010     #  @param UseExisting if ==true - search existing hypothesis created with
1011     #                     same parameters, else (default) - create new
1012     def SourceEdge(self, edge, mesh=None, srcV=None, tgtV=None, UseExisting=0):
1013         hyp = self.Hypothesis("ProjectionSource1D", [edge,mesh,srcV,tgtV], UseExisting=UseExisting)
1014         hyp.SetSourceEdge( edge )
1015         if not mesh is None and isinstance(mesh, Mesh):
1016             mesh = mesh.GetMesh()
1017         hyp.SetSourceMesh( mesh )
1018         hyp.SetVertexAssociation( srcV, tgtV )
1019         return hyp
1020
1021
1022 # Public class: Mesh_Projection2D
1023 # ------------------------------
1024
1025 ## Class to define a projection 2D algorithm
1026 #
1027 #  More details.
1028 class Mesh_Projection2D(Mesh_Algorithm):
1029
1030     algo = 0 # algorithm object common for all Mesh_Projection2D's
1031
1032     ## Private constructor.
1033     def __init__(self, mesh, geom=0):
1034         if not Mesh_Projection2D.algo:
1035             Mesh_Projection2D.algo = self.Create(mesh, geom, "Projection_2D")
1036         else:
1037             self.Assign( Mesh_Projection2D.algo, mesh, geom)
1038             pass
1039
1040     ## Define "Source Face" hypothesis, specifying a meshed face to
1041     #  take a mesh pattern from, and optionally association of vertices
1042     #  between the source face and a target one (where a hipothesis is assigned to)
1043     #  @param face to take mesh pattern from
1044     #  @param mesh to take mesh pattern from (optional)
1045     #  @param srcV1 is vertex of \a face to associate with \a tgtV1 (optional)
1046     #  @param tgtV1 is vertex of \a the face where the algorithm is assigned,
1047     #  to associate with \a srcV1 (optional)
1048     #  @param srcV2 is vertex of \a face to associate with \a tgtV1 (optional)
1049     #  @param tgtV2 is vertex of \a the face where the algorithm is assigned,
1050     #  to associate with \a srcV2 (optional)
1051     #  @param UseExisting if ==true - search existing hypothesis created with
1052     #                     same parameters, else (default) - create new
1053     #
1054     #  Note: association vertices must belong to one edge of a face
1055     def SourceFace(self, face, mesh=None, srcV1=None, tgtV1=None,
1056                    srcV2=None, tgtV2=None, UseExisting=0):
1057         hyp = self.Hypothesis("ProjectionSource2D", [face,mesh,srcV1,tgtV1,srcV2,tgtV2],
1058                               UseExisting=UseExisting)
1059         hyp.SetSourceFace( face )
1060         if not mesh is None and isinstance(mesh, Mesh):
1061             mesh = mesh.GetMesh()
1062         hyp.SetSourceMesh( mesh )
1063         hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
1064         return hyp
1065
1066 # Public class: Mesh_Projection3D
1067 # ------------------------------
1068
1069 ## Class to define a projection 3D algorithm
1070 #
1071 #  More details.
1072 class Mesh_Projection3D(Mesh_Algorithm):
1073
1074     algo = 0 # algorithm object common for all Mesh_Projection3D's
1075
1076     ## Private constructor.
1077     def __init__(self, mesh, geom=0):
1078         if not Mesh_Projection3D.algo:
1079             Mesh_Projection3D.algo = self.Create(mesh, geom, "Projection_3D")
1080         else:
1081             self.Assign( Mesh_Projection3D.algo, mesh, geom)
1082             pass
1083
1084     ## Define "Source Shape 3D" hypothesis, specifying a meshed solid to
1085     #  take a mesh pattern from, and optionally association of vertices
1086     #  between the source solid and a target one (where a hipothesis is assigned to)
1087     #  @param solid to take mesh pattern from
1088     #  @param mesh to take mesh pattern from (optional)
1089     #  @param srcV1 is vertex of \a solid to associate with \a tgtV1 (optional)
1090     #  @param tgtV1 is vertex of \a the solid where the algorithm is assigned,
1091     #  to associate with \a srcV1 (optional)
1092     #  @param srcV2 is vertex of \a solid to associate with \a tgtV1 (optional)
1093     #  @param tgtV2 is vertex of \a the solid where the algorithm is assigned,
1094     #  to associate with \a srcV2 (optional)
1095     #  @param UseExisting - if ==true - search existing hypothesis created with
1096     #                       same parameters, else (default) - create new
1097     #
1098     #  Note: association vertices must belong to one edge of a solid
1099     def SourceShape3D(self, solid, mesh=0, srcV1=0, tgtV1=0,
1100                       srcV2=0, tgtV2=0, UseExisting=0):
1101         hyp = self.Hypothesis("ProjectionSource3D",
1102                               [solid,mesh,srcV1,tgtV1,srcV2,tgtV2],
1103                               UseExisting=UseExisting)
1104         hyp.SetSource3DShape( solid )
1105         if not mesh is None and isinstance(mesh, Mesh):
1106             mesh = mesh.GetMesh()
1107         hyp.SetSourceMesh( mesh )
1108         hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
1109         return hyp
1110
1111
1112 # Public class: Mesh_Prism
1113 # ------------------------
1114
1115 ## Class to define a 3D extrusion algorithm
1116 #
1117 #  More details.
1118 class Mesh_Prism3D(Mesh_Algorithm):
1119
1120     algo = 0 # algorithm object common for all Mesh_Prism3D's
1121
1122     ## Private constructor.
1123     def __init__(self, mesh, geom=0):
1124         if not Mesh_Prism3D.algo:
1125             Mesh_Prism3D.algo = self.Create(mesh, geom, "Prism_3D")
1126         else:
1127             self.Assign( Mesh_Prism3D.algo, mesh, geom)
1128             pass
1129
1130 # Public class: Mesh_RadialPrism
1131 # -------------------------------
1132
1133 ## Class to define a Radial Prism 3D algorithm
1134 #
1135 #  More details.
1136 class Mesh_RadialPrism3D(Mesh_Algorithm):
1137
1138     algo = 0 # algorithm object common for all Mesh_RadialPrism3D's
1139
1140     ## Private constructor.
1141     def __init__(self, mesh, geom=0):
1142         if not Mesh_RadialPrism3D.algo:
1143             Mesh_RadialPrism3D.algo = self.Create(mesh, geom, "RadialPrism_3D")
1144         else:
1145             self.Assign( Mesh_RadialPrism3D.algo, mesh, geom)
1146             pass
1147         self.distribHyp = self.Hypothesis( "LayerDistribution", UseExisting=0)
1148         self.nbLayers = None
1149
1150     ## Return 3D hypothesis holding the 1D one
1151     def Get3DHypothesis(self):
1152         return self.distribHyp
1153
1154     ## Private method creating 1D hypothes and storing it in the LayerDistribution
1155     #  hypothes. Returns the created hypothes
1156     def OwnHypothesis(self, hypType, args=[], so="libStdMeshersEngine.so"):
1157         if not self.nbLayers is None:
1158             self.mesh.GetMesh().RemoveHypothesis( self.geom, self.nbLayers )
1159             self.mesh.GetMesh().AddHypothesis( self.geom, self.distribHyp )
1160         study = GetCurrentStudy() # prevent publishing of own 1D hypothesis
1161         hyp = smesh.CreateHypothesis(hypType, so)
1162         SetCurrentStudy( study ) # anable publishing
1163         self.distribHyp.SetLayerDistribution( hyp )
1164         return hyp
1165
1166     ## Define "NumberOfLayers" hypothesis, specifying a number of layers of
1167     #  prisms to build between the inner and outer shells
1168     #  @param UseExisting if ==true - search existing hypothesis created with
1169     #                     same parameters, else (default) - create new
1170     def NumberOfLayers(self, n, UseExisting=0):
1171         self.mesh.GetMesh().RemoveHypothesis( self.geom, self.distribHyp )
1172         self.nbLayers = self.Hypothesis("NumberOfLayers", [n], UseExisting=UseExisting)
1173         self.nbLayers.SetNumberOfLayers( n )
1174         return self.nbLayers
1175
1176     ## Define "LocalLength" hypothesis, specifying segment length
1177     #  to build between the inner and outer shells
1178     #  @param l for the length of segments
1179     def LocalLength(self, l):
1180         hyp = self.OwnHypothesis("LocalLength", [l] )
1181         hyp.SetLength(l)
1182         return hyp
1183         
1184     ## Define "NumberOfSegments" hypothesis, specifying a number of layers of
1185     #  prisms to build between the inner and outer shells
1186     #  @param n for the number of segments
1187     #  @param s for the scale factor (optional)
1188     def NumberOfSegments(self, n, s=[]):
1189         if s == []:
1190             hyp = self.OwnHypothesis("NumberOfSegments", [n] )
1191         else:
1192             hyp = self.OwnHypothesis("NumberOfSegments", [n,s])
1193             hyp.SetDistrType( 1 )
1194             hyp.SetScaleFactor(s)
1195         hyp.SetNumberOfSegments(n)
1196         return hyp
1197         
1198     ## Define "Arithmetic1D" hypothesis, specifying distribution of segments
1199     #  to build between the inner and outer shells as arithmetic length increasing
1200     #  @param start for the length of the first segment
1201     #  @param end   for the length of the last  segment
1202     def Arithmetic1D(self, start, end ):
1203         hyp = self.OwnHypothesis("Arithmetic1D", [start, end])
1204         hyp.SetLength(start, 1)
1205         hyp.SetLength(end  , 0)
1206         return hyp
1207         
1208     ## Define "StartEndLength" hypothesis, specifying distribution of segments
1209     #  to build between the inner and outer shells as geometric length increasing
1210     #  @param start for the length of the first segment
1211     #  @param end   for the length of the last  segment
1212     def StartEndLength(self, start, end):
1213         hyp = self.OwnHypothesis("StartEndLength", [start, end])
1214         hyp.SetLength(start, 1)
1215         hyp.SetLength(end  , 0)
1216         return hyp
1217         
1218     ## Define "AutomaticLength" hypothesis, specifying number of segments
1219     #  to build between the inner and outer shells
1220     #  @param fineness for the fineness [0-1]
1221     def AutomaticLength(self, fineness=0):
1222         hyp = self.OwnHypothesis("AutomaticLength")
1223         hyp.SetFineness( fineness )
1224         return hyp
1225
1226
1227 # Public class: Mesh
1228 # ==================
1229
1230 ## Class to define a mesh
1231 #
1232 #  The class contains mesh shape, SMESH_Mesh, SMESH_MeshEditor
1233 #  More details.
1234 class Mesh:
1235
1236     geom = 0
1237     mesh = 0
1238     editor = 0
1239
1240     ## Constructor
1241     #
1242     #  Creates mesh on the shape \a geom(or the empty mesh if geom equal to 0),
1243     #  sets GUI name of this mesh to \a name.
1244     #  @param obj Shape to be meshed or SMESH_Mesh object
1245     #  @param name Study name of the mesh
1246     def __init__(self, obj=0, name=0):
1247         if obj is None:
1248             obj = 0
1249         if obj != 0:
1250             if isinstance(obj, geompy.GEOM._objref_GEOM_Object):
1251                 self.geom = obj
1252                 self.mesh = smesh.CreateMesh(self.geom)
1253             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1254                 self.SetMesh(obj)
1255         else:
1256             self.mesh = smesh.CreateEmptyMesh()
1257         if name != 0:
1258             SetName(self.mesh, name)
1259         elif obj != 0:
1260             SetName(self.mesh, GetName(obj))
1261
1262         self.editor = self.mesh.GetMeshEditor()
1263
1264     ## Method that inits the Mesh object from SMESH_Mesh interface
1265     #  @param theMesh is SMESH_Mesh object
1266     def SetMesh(self, theMesh):
1267         self.mesh = theMesh
1268         self.geom = self.mesh.GetShapeToMesh()
1269             
1270     ## Method that returns the mesh
1271     #  @return SMESH_Mesh object
1272     def GetMesh(self):
1273         return self.mesh
1274
1275     ## Get mesh name
1276     def GetName(self):
1277         name = GetName(self.GetMesh())
1278         return name
1279
1280     ## Set name to mesh
1281     def SetName(self, name):
1282         SetName(self.GetMesh(), name)
1283     
1284     ## Get the subMesh object associated to a subShape. The subMesh object
1285     #  gives access to nodes and elements IDs.
1286     #  \n SubMesh will be used instead of SubShape in a next idl version to
1287     #  adress a specific subMesh...
1288     def GetSubMesh(self, theSubObject, name):
1289         submesh = self.mesh.GetSubMesh(theSubObject, name)
1290         return submesh
1291         
1292     ## Method that returns the shape associated to the mesh
1293     #  @return GEOM_Object
1294     def GetShape(self):
1295         return self.geom
1296
1297     ## Method that associates given shape to the mesh(entails the mesh recreation)
1298     #  @param geom shape to be meshed(GEOM_Object)
1299     def SetShape(self, geom):
1300         self.mesh = smesh.CreateMesh(geom)  
1301                 
1302     ## Return true if hypotheses are defined well
1303     #  @param theMesh is an instance of Mesh class
1304     #  @param theSubObject subshape of a mesh shape
1305     def IsReadyToCompute(self, theSubObject):
1306         return smesh.IsReadyToCompute(self.mesh, theSubObject)
1307
1308     ## Return errors of hypotheses definintion
1309     #  error list is empty if everything is OK
1310     #  @param theMesh is an instance of Mesh class
1311     #  @param theSubObject subshape of a mesh shape
1312     #  @return a list of errors
1313     def GetAlgoState(self, theSubObject):
1314         return smesh.GetAlgoState(self.mesh, theSubObject)
1315     
1316     ## Return geometrical object the given element is built on.
1317     #  The returned geometrical object, if not nil, is either found in the 
1318     #  study or is published by this method with the given name
1319     #  @param theMesh is an instance of Mesh class
1320     #  @param theElementID an id of the mesh element
1321     #  @param theGeomName user defined name of geometrical object
1322     #  @return GEOM::GEOM_Object instance
1323     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1324         return smesh.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1325         
1326     ## Returns mesh dimension depending on shape one
1327     def MeshDimension(self):
1328         shells = geompy.SubShapeAllIDs( self.geom, geompy.ShapeType["SHELL"] )
1329         if len( shells ) > 0 :
1330             return 3
1331         elif geompy.NumberOfFaces( self.geom ) > 0 :
1332             return 2
1333         elif geompy.NumberOfEdges( self.geom ) > 0 :
1334             return 1
1335         else:
1336             return 0;
1337         pass
1338         
1339     ## Creates a segment discretization 1D algorithm.
1340     #  If the optional \a algo parameter is not sets, this algorithm is REGULAR.
1341     #  If the optional \a geom parameter is not sets, this algorithm is global.
1342     #  \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1343     #  @param algo values are smesh.REGULAR or smesh.PYTHON for discretization via python function
1344     #  @param geom If defined, subshape to be meshed
1345     def Segment(self, algo=REGULAR, geom=0):
1346         ## if Segment(geom) is called by mistake
1347         if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1348             algo, geom = geom, algo
1349             pass
1350         if algo == REGULAR:
1351             return Mesh_Segment(self, geom)
1352         elif algo == PYTHON:
1353             return Mesh_Segment_Python(self, geom)
1354         elif algo == COMPOSITE:
1355             return Mesh_CompositeSegment(self, geom)
1356         else:
1357             return Mesh_Segment(self, geom)
1358         
1359     ## Creates a triangle 2D algorithm for faces.
1360     #  If the optional \a geom parameter is not sets, this algorithm is global.
1361     #  \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1362     #  @param algo values are: smesh.MEFISTO or smesh.NETGEN
1363     #  @param geom If defined, subshape to be meshed
1364     def Triangle(self, algo=MEFISTO, geom=0):
1365         ## if Triangle(geom) is called by mistake
1366         if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1367             geom = algo
1368             algo = MEFISTO
1369         
1370         return Mesh_Triangle(self, algo, geom)
1371         
1372     ## Creates a quadrangle 2D algorithm for faces.
1373     #  If the optional \a geom parameter is not sets, this algorithm is global.
1374     #  \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1375     #  @param geom If defined, subshape to be meshed
1376     def Quadrangle(self, geom=0):
1377         return Mesh_Quadrangle(self, geom)
1378
1379     ## Creates a tetrahedron 3D algorithm for solids.
1380     #  The parameter \a algo permits to choice the algorithm: NETGEN or GHS3D
1381     #  If the optional \a geom parameter is not sets, this algorithm is global.
1382     #  \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1383     #  @param algo values are: smesh.NETGEN, smesh.GHS3D, smesh.FULL_NETGEN
1384     #  @param geom If defined, subshape to be meshed
1385     def Tetrahedron(self, algo=NETGEN, geom=0):
1386         ## if Tetrahedron(geom) is called by mistake
1387         if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1388             algo, geom = geom, algo
1389             pass
1390         return Mesh_Tetrahedron(self, algo, geom)
1391         
1392     ## Creates a hexahedron 3D algorithm for solids.
1393     #  If the optional \a geom parameter is not sets, this algorithm is global.
1394     #  \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1395     #  @param geom If defined, subshape to be meshed
1396     def Hexahedron(self, geom=0):
1397         return Mesh_Hexahedron(self, geom)
1398
1399     ## Deprecated, only for compatibility!
1400     def Netgen(self, is3D, geom=0):
1401         return Mesh_Netgen(self, is3D, geom)
1402
1403     ## Creates a projection 1D algorithm for edges.
1404     #  If the optional \a geom parameter is not sets, this algorithm is global.
1405     #  Otherwise, this algorithm define a submesh based on \a geom subshape.
1406     #  @param geom If defined, subshape to be meshed
1407     def Projection1D(self, geom=0):
1408         return Mesh_Projection1D(self, geom)
1409
1410     ## Creates a projection 2D algorithm for faces.
1411     #  If the optional \a geom parameter is not sets, this algorithm is global.
1412     #  Otherwise, this algorithm define a submesh based on \a geom subshape.
1413     #  @param geom If defined, subshape to be meshed
1414     def Projection2D(self, geom=0):
1415         return Mesh_Projection2D(self, geom)
1416
1417     ## Creates a projection 3D algorithm for solids.
1418     #  If the optional \a geom parameter is not sets, this algorithm is global.
1419     #  Otherwise, this algorithm define a submesh based on \a geom subshape.
1420     #  @param geom If defined, subshape to be meshed
1421     def Projection3D(self, geom=0):
1422         return Mesh_Projection3D(self, geom)
1423
1424     ## Creates a 3D extrusion (Prism 3D) or RadialPrism 3D algorithm for solids.
1425     #  If the optional \a geom parameter is not sets, this algorithm is global.
1426     #  Otherwise, this algorithm define a submesh based on \a geom subshape.
1427     #  @param geom If defined, subshape to be meshed
1428     def Prism(self, geom=0):
1429         shape = geom
1430         if shape==0:
1431             shape = self.geom
1432         nbSolids = len( geompy.SubShapeAll( shape, geompy.ShapeType["SOLID"] ))
1433         nbShells = len( geompy.SubShapeAll( shape, geompy.ShapeType["SHELL"] ))
1434         if nbSolids == 0 or nbSolids == nbShells:
1435             return Mesh_Prism3D(self, geom)
1436         return Mesh_RadialPrism3D(self, geom)
1437
1438     ## Compute the mesh and return the status of the computation
1439     def Compute(self, geom=0):
1440         if geom == 0 or not isinstance(geom, geompy.GEOM._objref_GEOM_Object):
1441             if self.geom == 0:
1442                 print "Compute impossible: mesh is not constructed on geom shape."
1443                 return 0
1444             else:
1445                 geom = self.geom
1446         ok = False
1447         try:
1448             ok = smesh.Compute(self.mesh, geom)
1449         except SALOME.SALOME_Exception, ex:
1450             print "Mesh computation failed, exception cought:"
1451             print "    ", ex.details.text
1452         except:
1453             import traceback
1454             print "Mesh computation failed, exception cought:"
1455             traceback.print_exc()
1456         if not ok:
1457             errors = smesh.GetAlgoState( self.mesh, geom )
1458             allReasons = ""
1459             for err in errors:
1460                 if err.isGlobalAlgo:
1461                     glob = " global "
1462                 else:
1463                     glob = " local "
1464                     pass
1465                 dim = str(err.algoDim)
1466                 if err.name == MISSING_ALGO:
1467                     reason = glob + dim + "D algorithm is missing"
1468                 elif err.name == MISSING_HYPO:
1469                     name = '"' + err.algoName + '"'
1470                     reason = glob + dim + "D algorithm " + name + " misses " + dim + "D hypothesis"
1471                 elif err.name == NOT_CONFORM_MESH:
1472                     reason = "Global \"Not Conform mesh allowed\" hypothesis is missing"
1473                 elif err.name == BAD_PARAM_VALUE:
1474                     name = '"' + err.algoName + '"'
1475                     reason = "Hypothesis of" + glob + dim + "D algorithm " + name +\
1476                              " has a bad parameter value"
1477                 else:
1478                     reason = "For unknown reason."+\
1479                              " Revise Mesh.Compute() implementation in smesh.py!"
1480                     pass
1481                 if allReasons != "":
1482                     allReasons += "\n"
1483                     pass
1484                 allReasons += reason
1485                 pass
1486             if allReasons != "":
1487                 print '"' + GetName(self.mesh) + '"',"has not been computed:"
1488                 print allReasons
1489             else:
1490                 print '"' + GetName(self.mesh) + '"',"has not been computed."
1491                 pass
1492             pass
1493         if salome.sg.hasDesktop():
1494             smeshgui = salome.ImportComponentGUI("SMESH")
1495             smeshgui.Init(salome.myStudyId)
1496             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1497             salome.sg.updateObjBrowser(1)
1498             pass
1499         return ok
1500
1501     ## Compute tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1502     #  The parameter \a fineness [0,-1] defines mesh fineness
1503     def AutomaticTetrahedralization(self, fineness=0):
1504         dim = self.MeshDimension()
1505         # assign hypotheses
1506         self.RemoveGlobalHypotheses()
1507         self.Segment().AutomaticLength(fineness)
1508         if dim > 1 :
1509             self.Triangle().LengthFromEdges()
1510             pass
1511         if dim > 2 :
1512             self.Tetrahedron(NETGEN)
1513             pass
1514         return self.Compute()
1515         
1516     ## Compute hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1517     #  The parameter \a fineness [0,-1] defines mesh fineness
1518     def AutomaticHexahedralization(self, fineness=0):
1519         dim = self.MeshDimension()
1520         # assign hypotheses
1521         self.RemoveGlobalHypotheses()
1522         self.Segment().AutomaticLength(fineness)
1523         if dim > 1 :
1524             self.Quadrangle()
1525             pass
1526         if dim > 2 :
1527             self.Hexahedron()            
1528             pass
1529         return self.Compute()
1530
1531     ## Assign hypothesis
1532     #  @param hyp is a hypothesis to assign
1533     #  @param geom is subhape of mesh geometry
1534     def AddHypothesis(self, hyp, geom=0 ):
1535         if isinstance( hyp, Mesh_Algorithm ):
1536             hyp = hyp.GetAlgorithm()
1537             pass
1538         if not geom:
1539             geom = self.geom
1540             pass
1541         status = self.mesh.AddHypothesis(geom, hyp)
1542         isAlgo = hyp._narrow( SMESH.SMESH_Algo )
1543         TreatHypoStatus( status, GetName( hyp ), GetName( geom ), isAlgo )
1544         return status
1545     
1546     ## Get the list of hypothesis added on a geom
1547     #  @param geom is subhape of mesh geometry
1548     def GetHypothesisList(self, geom):
1549         return self.mesh.GetHypothesisList( geom )
1550                 
1551     ## Removes all global hypotheses
1552     def RemoveGlobalHypotheses(self):
1553         current_hyps = self.mesh.GetHypothesisList( self.geom )
1554         for hyp in current_hyps:
1555             self.mesh.RemoveHypothesis( self.geom, hyp )
1556             pass
1557         pass
1558         
1559     ## Create a mesh group based on geometric object \a grp
1560     #  and give a \a name, \n if this parameter is not defined
1561     #  the name is the same as the geometric group name \n
1562     #  Note: Works like GroupOnGeom(). 
1563     #  @param grp  is a geometric group, a vertex, an edge, a face or a solid
1564     #  @param name is the name of the mesh group
1565     #  @return SMESH_GroupOnGeom
1566     def Group(self, grp, name=""):
1567         return self.GroupOnGeom(grp, name)
1568        
1569     ## Deprecated, only for compatibility! Please, use ExportMED() method instead.
1570     #  Export the mesh in a file with the MED format and choice the \a version of MED format
1571     #  @param f is the file name
1572     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1573     def ExportToMED(self, f, version, opt=0):
1574         self.mesh.ExportToMED(f, opt, version)
1575         
1576     ## Export the mesh in a file with the MED format
1577     #  @param f is the file name
1578     #  @param auto_groups boolean parameter for creating/not creating
1579     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1580     #  the typical use is auto_groups=false.
1581     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1582     def ExportMED(self, f, auto_groups=0, version=MED_V2_2):
1583         self.mesh.ExportToMED(f, auto_groups, version)
1584         
1585     ## Export the mesh in a file with the DAT format
1586     #  @param f is the file name
1587     def ExportDAT(self, f):
1588         self.mesh.ExportDAT(f)
1589         
1590     ## Export the mesh in a file with the UNV format
1591     #  @param f is the file name
1592     def ExportUNV(self, f):
1593         self.mesh.ExportUNV(f)
1594         
1595     ## Export the mesh in a file with the STL format
1596     #  @param f is the file name
1597     #  @param ascii defined the kind of file contents
1598     def ExportSTL(self, f, ascii=1):
1599         self.mesh.ExportSTL(f, ascii)
1600    
1601         
1602     # Operations with groups:
1603     # ----------------------
1604
1605     ## Creates an empty mesh group
1606     #  @param elementType is the type of elements in the group
1607     #  @param name is the name of the mesh group
1608     #  @return SMESH_Group
1609     def CreateEmptyGroup(self, elementType, name):
1610         return self.mesh.CreateGroup(elementType, name)
1611     
1612     ## Creates a mesh group based on geometric object \a grp
1613     #  and give a \a name, \n if this parameter is not defined
1614     #  the name is the same as the geometric group name
1615     #  @param grp  is a geometric group, a vertex, an edge, a face or a solid
1616     #  @param name is the name of the mesh group
1617     #  @return SMESH_GroupOnGeom
1618     def GroupOnGeom(self, grp, name="", type=None):
1619         if name == "":
1620             name = grp.GetName()
1621
1622         if type == None:
1623             tgeo = str(grp.GetShapeType())
1624             if tgeo == "VERTEX":
1625                 type = NODE
1626             elif tgeo == "EDGE":
1627                 type = EDGE
1628             elif tgeo == "FACE":
1629                 type = FACE
1630             elif tgeo == "SOLID":
1631                 type = VOLUME
1632             elif tgeo == "SHELL":
1633                 type = VOLUME
1634             elif tgeo == "COMPOUND":
1635                 if len( geompy.GetObjectIDs( grp )) == 0:
1636                     print "Mesh.Group: empty geometric group", GetName( grp )
1637                     return 0
1638                 tgeo = geompy.GetType(grp)
1639                 if tgeo == geompy.ShapeType["VERTEX"]:
1640                     type = NODE
1641                 elif tgeo == geompy.ShapeType["EDGE"]:
1642                     type = EDGE
1643                 elif tgeo == geompy.ShapeType["FACE"]:
1644                     type = FACE
1645                 elif tgeo == geompy.ShapeType["SOLID"]:
1646                     type = VOLUME
1647
1648         if type == None:
1649             print "Mesh.Group: bad first argument: expected a group, a vertex, an edge, a face or a solid"
1650             return 0
1651         else:
1652             return self.mesh.CreateGroupFromGEOM(type, name, grp)
1653
1654     ## Create a mesh group by the given ids of elements
1655     #  @param groupName is the name of the mesh group
1656     #  @param elementType is the type of elements in the group
1657     #  @param elemIDs is the list of ids
1658     #  @return SMESH_Group
1659     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1660         group = self.mesh.CreateGroup(elementType, groupName)
1661         group.Add(elemIDs)
1662         return group
1663     
1664     ## Create a mesh group by the given conditions
1665     #  @param groupName is the name of the mesh group
1666     #  @param elementType is the type of elements in the group
1667     #  @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1668     #  @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1669     #  @param Treshold is threshold value (range of id ids as string, shape, numeric)
1670     #  @param UnaryOp is FT_LogicalNOT or FT_Undefined
1671     #  @return SMESH_Group
1672     def MakeGroup(self,
1673                   groupName,
1674                   elementType,
1675                   CritType=FT_Undefined,
1676                   Compare=FT_EqualTo,
1677                   Treshold="",
1678                   UnaryOp=FT_Undefined):
1679         aCriterion = GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
1680         group = self.MakeGroupByCriterion(groupName, aCriterion)
1681         return group
1682
1683     ## Create a mesh group by the given criterion
1684     #  @param groupName is the name of the mesh group
1685     #  @param Criterion is the instance of Criterion class
1686     #  @return SMESH_Group
1687     def MakeGroupByCriterion(self, groupName, Criterion):
1688         aFilterMgr = smesh.CreateFilterManager()
1689         aFilter = aFilterMgr.CreateFilter()
1690         aCriteria = []
1691         aCriteria.append(Criterion)
1692         aFilter.SetCriteria(aCriteria)
1693         group = self.MakeGroupByFilter(groupName, aFilter)
1694         return group
1695     
1696     ## Create a mesh group by the given criteria(list of criterions)
1697     #  @param groupName is the name of the mesh group
1698     #  @param Criteria is the list of criterions
1699     #  @return SMESH_Group
1700     def MakeGroupByCriteria(self, groupName, theCriteria):
1701         aFilterMgr = smesh.CreateFilterManager()
1702         aFilter = aFilterMgr.CreateFilter()
1703         aFilter.SetCriteria(theCriteria)
1704         group = self.MakeGroupByFilter(groupName, aFilter)
1705         return group
1706     
1707     ## Create a mesh group by the given filter
1708     #  @param groupName is the name of the mesh group
1709     #  @param Criterion is the instance of Filter class
1710     #  @return SMESH_Group
1711     def MakeGroupByFilter(self, groupName, theFilter):
1712         anIds = theFilter.GetElementsId(self.mesh)
1713         anElemType = theFilter.GetElementType()
1714         group = self.MakeGroupByIds(groupName, anElemType, anIds)
1715         return group
1716
1717     ## Pass mesh elements through the given filter and return ids
1718     #  @param theFilter is SMESH_Filter
1719     #  @return list of ids
1720     def GetIdsFromFilter(self, theFilter):
1721         return theFilter.GetElementsId(self.mesh)
1722
1723     ## Verify whether 2D mesh element has free edges(edges connected to one face only)\n
1724     #  Returns list of special structures(borders).
1725     #  @return list of SMESH.FreeEdges.Border structure: edge id and two its nodes ids.
1726     def GetFreeBorders(self):
1727         aFilterMgr = smesh.CreateFilterManager()
1728         aPredicate = aFilterMgr.CreateFreeEdges()
1729         aPredicate.SetMesh(self.mesh)
1730         aBorders = aPredicate.GetBorders()
1731         return aBorders
1732                 
1733     ## Remove a group
1734     def RemoveGroup(self, group):
1735         self.mesh.RemoveGroup(group)
1736
1737     ## Remove group with its contents
1738     def RemoveGroupWithContents(self, group):
1739         self.mesh.RemoveGroupWithContents(group)
1740         
1741     ## Get the list of groups existing in the mesh
1742     def GetGroups(self):
1743         return self.mesh.GetGroups()
1744
1745     ## Get the list of names of groups existing in the mesh
1746     def GetGroupNames(self):
1747         groups = self.GetGroups()
1748         names = []
1749         for group in groups:
1750             names.append(group.GetName())
1751         return names
1752
1753     ## Union of two groups
1754     #  New group is created. All mesh elements that are
1755     #  present in initial groups are added to the new one
1756     def UnionGroups(self, group1, group2, name):
1757         return self.mesh.UnionGroups(group1, group2, name)
1758
1759     ## Intersection of two groups
1760     #  New group is created. All mesh elements that are
1761     #  present in both initial groups are added to the new one.
1762     def IntersectGroups(self, group1, group2, name):
1763         return self.mesh.IntersectGroups(group1, group2, name)
1764     
1765     ## Cut of two groups
1766     #  New group is created. All mesh elements that are present in
1767     #  main group but do not present in tool group are added to the new one
1768     def CutGroups(self, mainGroup, toolGroup, name):
1769         return self.mesh.CutGroups(mainGroup, toolGroup, name)
1770          
1771     
1772     # Get some info about mesh:
1773     # ------------------------
1774
1775     ## Get the log of nodes and elements added or removed since previous
1776     #  clear of the log.
1777     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
1778     #  @return list of log_block structures:
1779     #                                        commandType
1780     #                                        number
1781     #                                        coords
1782     #                                        indexes
1783     def GetLog(self, clearAfterGet):
1784         return self.mesh.GetLog(clearAfterGet)
1785
1786     ## Clear the log of nodes and elements added or removed since previous
1787     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
1788     def ClearLog(self):
1789         self.mesh.ClearLog()
1790
1791     ## Get the internal Id
1792     def GetId(self):
1793         return self.mesh.GetId()
1794
1795     ## Get the study Id
1796     def GetStudyId(self):
1797         return self.mesh.GetStudyId()
1798
1799     ## Check group names for duplications.
1800     #  Consider maximum group name length stored in MED file.
1801     def HasDuplicatedGroupNamesMED(self):
1802         return self.mesh.GetStudyId()
1803         
1804     ## Obtain instance of SMESH_MeshEditor
1805     def GetMeshEditor(self):
1806         return self.mesh.GetMeshEditor()
1807
1808     ## Get MED Mesh
1809     def GetMEDMesh(self):
1810         return self.mesh.GetMEDMesh()
1811     
1812     
1813     # Get informations about mesh contents:
1814     # ------------------------------------
1815
1816     ## Returns number of nodes in mesh
1817     def NbNodes(self):
1818         return self.mesh.NbNodes()
1819
1820     ## Returns number of elements in mesh
1821     def NbElements(self):
1822         return self.mesh.NbElements()
1823
1824     ## Returns number of edges in mesh
1825     def NbEdges(self):
1826         return self.mesh.NbEdges()
1827
1828     ## Returns number of edges with given order in mesh
1829     #  @param elementOrder is order of elements:
1830     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1831     def NbEdgesOfOrder(self, elementOrder):
1832         return self.mesh.NbEdgesOfOrder(elementOrder)
1833     
1834     ## Returns number of faces in mesh
1835     def NbFaces(self):
1836         return self.mesh.NbFaces()
1837
1838     ## Returns number of faces with given order in mesh
1839     #  @param elementOrder is order of elements:
1840     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1841     def NbFacesOfOrder(self, elementOrder):
1842         return self.mesh.NbFacesOfOrder(elementOrder)
1843
1844     ## Returns number of triangles in mesh
1845     def NbTriangles(self):
1846         return self.mesh.NbTriangles()
1847
1848     ## Returns number of triangles with given order in mesh
1849     #  @param elementOrder is order of elements:
1850     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1851     def NbTrianglesOfOrder(self, elementOrder):
1852         return self.mesh.NbTrianglesOfOrder(elementOrder)
1853
1854     ## Returns number of quadrangles in mesh
1855     def NbQuadrangles(self):
1856         return self.mesh.NbQuadrangles()
1857
1858     ## Returns number of quadrangles with given order in mesh
1859     #  @param elementOrder is order of elements:
1860     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1861     def NbQuadranglesOfOrder(self, elementOrder):
1862         return self.mesh.NbQuadranglesOfOrder(elementOrder)
1863
1864     ## Returns number of polygons in mesh
1865     def NbPolygons(self):
1866         return self.mesh.NbPolygons()
1867
1868     ## Returns number of volumes in mesh
1869     def NbVolumes(self):
1870         return self.mesh.NbVolumes()
1871
1872     ## Returns number of volumes with given order in mesh
1873     #  @param elementOrder is order of elements:
1874     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1875     def NbVolumesOfOrder(self, elementOrder):
1876         return self.mesh.NbVolumesOfOrder(elementOrder)
1877
1878     ## Returns number of tetrahedrons in mesh
1879     def NbTetras(self):
1880         return self.mesh.NbTetras()
1881
1882     ## Returns number of tetrahedrons with given order in mesh
1883     #  @param elementOrder is order of elements:
1884     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1885     def NbTetrasOfOrder(self, elementOrder):
1886         return self.mesh.NbTetrasOfOrder(elementOrder)
1887
1888     ## Returns number of hexahedrons in mesh
1889     def NbHexas(self):
1890         return self.mesh.NbHexas()
1891
1892     ## Returns number of hexahedrons with given order in mesh
1893     #  @param elementOrder is order of elements:
1894     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1895     def NbHexasOfOrder(self, elementOrder):
1896         return self.mesh.NbHexasOfOrder(elementOrder)
1897
1898     ## Returns number of pyramids in mesh
1899     def NbPyramids(self):
1900         return self.mesh.NbPyramids()
1901
1902     ## Returns number of pyramids with given order in mesh
1903     #  @param elementOrder is order of elements:
1904     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1905     def NbPyramidsOfOrder(self, elementOrder):
1906         return self.mesh.NbPyramidsOfOrder(elementOrder)
1907
1908     ## Returns number of prisms in mesh
1909     def NbPrisms(self):
1910         return self.mesh.NbPrisms()
1911
1912     ## Returns number of prisms with given order in mesh
1913     #  @param elementOrder is order of elements:
1914     #  ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1915     def NbPrismsOfOrder(self, elementOrder):
1916         return self.mesh.NbPrismsOfOrder(elementOrder)
1917
1918     ## Returns number of polyhedrons in mesh
1919     def NbPolyhedrons(self):
1920         return self.mesh.NbPolyhedrons()
1921
1922     ## Returns number of submeshes in mesh
1923     def NbSubMesh(self):
1924         return self.mesh.NbSubMesh()
1925
1926     ## Returns list of mesh elements ids
1927     def GetElementsId(self):
1928         return self.mesh.GetElementsId()
1929
1930     ## Returns list of ids of mesh elements with given type
1931     #  @param elementType is required type of elements
1932     def GetElementsByType(self, elementType):
1933         return self.mesh.GetElementsByType(elementType)
1934
1935     ## Returns list of mesh nodes ids
1936     def GetNodesId(self):
1937         return self.mesh.GetNodesId()
1938     
1939     # Get informations about mesh elements:
1940     # ------------------------------------
1941     
1942     ## Returns type of mesh element
1943     def GetElementType(self, id, iselem):
1944         return self.mesh.GetElementType(id, iselem)
1945
1946     ## Returns list of submesh elements ids
1947     #  @param shapeID is geom object(subshape) IOR
1948     def GetSubMeshElementsId(self, shapeID):
1949         return self.mesh.GetSubMeshElementsId(shapeID)
1950
1951     ## Returns list of submesh nodes ids
1952     #  @param shapeID is geom object(subshape) IOR
1953     def GetSubMeshNodesId(self, shapeID, all):
1954         return self.mesh.GetSubMeshNodesId(shapeID, all)
1955     
1956     ## Returns list of ids of submesh elements with given type
1957     #  @param shapeID is geom object(subshape) IOR
1958     def GetSubMeshElementType(self, shapeID):
1959         return self.mesh.GetSubMeshElementType(shapeID)
1960       
1961     ## Get mesh description
1962     def Dump(self):
1963         return self.mesh.Dump()
1964
1965     
1966     # Get information about nodes and elements of mesh by its ids:
1967     # -----------------------------------------------------------
1968
1969     ## Get XYZ coordinates of node as list of double
1970     #  \n If there is not node for given ID - returns empty list
1971     def GetNodeXYZ(self, id):
1972         return self.mesh.GetNodeXYZ(id)
1973
1974     ## For given node returns list of IDs of inverse elements
1975     #  \n If there is not node for given ID - returns empty list
1976     def GetNodeInverseElements(self, id):
1977         return self.mesh.GetNodeInverseElements(id)
1978
1979     ## If given element is node returns IDs of shape from position
1980     #  \n If there is not node for given ID - returns -1
1981     def GetShapeID(self, id):
1982         return self.mesh.GetShapeID(id)
1983
1984     ## For given element returns ID of result shape after 
1985     #  FindShape() from SMESH_MeshEditor
1986     #  \n If there is not element for given ID - returns -1
1987     def GetShapeIDForElem(id):
1988         return self.mesh.GetShapeIDForElem(id)
1989     
1990     ## Returns number of nodes for given element
1991     #  \n If there is not element for given ID - returns -1
1992     def GetElemNbNodes(self, id):
1993         return self.mesh.GetElemNbNodes(id)
1994
1995     ## Returns ID of node by given index for given element
1996     #  \n If there is not element for given ID - returns -1
1997     #  \n If there is not node for given index - returns -2
1998     def GetElemNode(self, id, index):
1999         return self.mesh.GetElemNode(id, index)
2000
2001     ## Returns true if given node is medium node
2002     #  in given quadratic element
2003     def IsMediumNode(self, elementID, nodeID):
2004         return self.mesh.IsMediumNode(elementID, nodeID)
2005     
2006     ## Returns true if given node is medium node
2007     #  in one of quadratic elements
2008     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2009         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2010
2011     ## Returns number of edges for given element
2012     def ElemNbEdges(self, id):
2013         return self.mesh.ElemNbEdges(id)
2014         
2015     ## Returns number of faces for given element
2016     def ElemNbFaces(self, id):
2017         return self.mesh.ElemNbFaces(id)
2018
2019     ## Returns true if given element is polygon
2020     def IsPoly(self, id):
2021         return self.mesh.IsPoly(id)
2022
2023     ## Returns true if given element is quadratic
2024     def IsQuadratic(self, id):
2025         return self.mesh.IsQuadratic(id)
2026
2027     ## Returns XYZ coordinates of bary center for given element
2028     #  as list of double
2029     #  \n If there is not element for given ID - returns empty list
2030     def BaryCenter(self, id):
2031         return self.mesh.BaryCenter(id)
2032     
2033     
2034     # Mesh edition (SMESH_MeshEditor functionality):
2035     # ---------------------------------------------
2036
2037     ## Removes elements from mesh by ids
2038     #  @param IDsOfElements is list of ids of elements to remove
2039     def RemoveElements(self, IDsOfElements):
2040         return self.editor.RemoveElements(IDsOfElements)
2041
2042     ## Removes nodes from mesh by ids
2043     #  @param IDsOfNodes is list of ids of nodes to remove
2044     def RemoveNodes(self, IDsOfNodes):
2045         return self.editor.RemoveNodes(IDsOfNodes)
2046
2047     ## Add node to mesh by coordinates
2048     def AddNode(self, x, y, z):
2049         return self.editor.AddNode( x, y, z)
2050
2051     
2052     ## Create edge both similar and quadratic (this is determed
2053     #  by number of given nodes).
2054     #  @param IdsOfNodes List of node IDs for creation of element.
2055     #  Needed order of nodes in this list corresponds to description
2056     #  of MED. \n This description is located by the following link:
2057     #  http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
2058     def AddEdge(self, IDsOfNodes):
2059         return self.editor.AddEdge(IDsOfNodes)
2060
2061     ## Create face both similar and quadratic (this is determed
2062     #  by number of given nodes).
2063     #  @param IdsOfNodes List of node IDs for creation of element.
2064     #  Needed order of nodes in this list corresponds to description
2065     #  of MED. \n This description is located by the following link:
2066     #  http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
2067     def AddFace(self, IDsOfNodes):
2068         return self.editor.AddFace(IDsOfNodes)
2069     
2070     ## Add polygonal face to mesh by list of nodes ids
2071     def AddPolygonalFace(self, IdsOfNodes):
2072         return self.editor.AddPolygonalFace(IdsOfNodes)
2073     
2074     ## Create volume both similar and quadratic (this is determed
2075     #  by number of given nodes).
2076     #  @param IdsOfNodes List of node IDs for creation of element.
2077     #  Needed order of nodes in this list corresponds to description
2078     #  of MED. \n This description is located by the following link:
2079     #  http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
2080     def AddVolume(self, IDsOfNodes):
2081         return self.editor.AddVolume(IDsOfNodes)
2082
2083     ## Create volume of many faces, giving nodes for each face.
2084     #  @param IdsOfNodes List of node IDs for volume creation face by face.
2085     #  @param Quantities List of integer values, Quantities[i]
2086     #         gives quantity of nodes in face number i.
2087     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2088         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2089
2090     ## Create volume of many faces, giving IDs of existing faces.
2091     #  @param IdsOfFaces List of face IDs for volume creation.
2092     #
2093     #  Note:  The created volume will refer only to nodes
2094     #         of the given faces, not to the faces itself.
2095     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2096         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2097     
2098     ## Move node with given id
2099     #  @param NodeID id of the node
2100     #  @param x new X coordinate
2101     #  @param y new Y coordinate
2102     #  @param z new Z coordinate
2103     def MoveNode(self, NodeID, x, y, z):
2104         return self.editor.MoveNode(NodeID, x, y, z)
2105
2106     ## Find a node closest to a point
2107     #  @param x X coordinate of a point
2108     #  @param y Y coordinate of a point
2109     #  @param z Z coordinate of a point
2110     #  @return id of a node
2111     def FindNodeClosestTo(self, x, y, z):
2112         preview = self.mesh.GetMeshEditPreviewer()
2113         return preview.MoveClosestNodeToPoint(x, y, z, -1)
2114
2115     ## Find a node closest to a point and move it to a point location
2116     #  @param x X coordinate of a point
2117     #  @param y Y coordinate of a point
2118     #  @param z Z coordinate of a point
2119     #  @return id of a moved node
2120     def MeshToPassThroughAPoint(self, x, y, z):
2121         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2122
2123     ## Replace two neighbour triangles sharing Node1-Node2 link
2124     #  with ones built on the same 4 nodes but having other common link.
2125     #  @param NodeID1 first node id
2126     #  @param NodeID2 second node id
2127     #  @return false if proper faces not found
2128     def InverseDiag(self, NodeID1, NodeID2):
2129         return self.editor.InverseDiag(NodeID1, NodeID2)
2130
2131     ## Replace two neighbour triangles sharing Node1-Node2 link
2132     #  with a quadrangle built on the same 4 nodes.
2133     #  @param NodeID1 first node id
2134     #  @param NodeID2 second node id
2135     #  @return false if proper faces not found
2136     def DeleteDiag(self, NodeID1, NodeID2):
2137         return self.editor.DeleteDiag(NodeID1, NodeID2)
2138
2139     ## Reorient elements by ids
2140     #  @param IDsOfElements if undefined reorient all mesh elements
2141     def Reorient(self, IDsOfElements=None):
2142         if IDsOfElements == None:
2143             IDsOfElements = self.GetElementsId()
2144         return self.editor.Reorient(IDsOfElements)
2145
2146     ## Reorient all elements of the object
2147     #  @param theObject is mesh, submesh or group
2148     def ReorientObject(self, theObject):
2149         return self.editor.ReorientObject(theObject)
2150
2151     ## Fuse neighbour triangles into quadrangles.
2152     #  @param IDsOfElements The triangles to be fused,
2153     #  @param theCriterion     is FT_...; used to choose a neighbour to fuse with.
2154     #  @param MaxAngle      is a max angle between element normals at which fusion
2155     #                       is still performed; theMaxAngle is mesured in radians.
2156     #  @return TRUE in case of success, FALSE otherwise.
2157     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2158         if IDsOfElements == []:
2159             IDsOfElements = self.GetElementsId()
2160         return self.editor.TriToQuad(IDsOfElements, GetFunctor(theCriterion), MaxAngle)
2161
2162     ## Fuse neighbour triangles of the object into quadrangles
2163     #  @param theObject is mesh, submesh or group
2164     #  @param theCriterion is FT_...; used to choose a neighbour to fuse with.
2165     #  @param MaxAngle  is a max angle between element normals at which fusion
2166     #                   is still performed; theMaxAngle is mesured in radians.
2167     #  @return TRUE in case of success, FALSE otherwise.
2168     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2169         return self.editor.TriToQuadObject(theObject, GetFunctor(theCriterion), MaxAngle)
2170
2171     ## Split quadrangles into triangles.
2172     #  @param IDsOfElements the faces to be splitted.
2173     #  @param theCriterion  is FT_...; used to choose a diagonal for splitting.
2174     #  @param @return TRUE in case of success, FALSE otherwise.
2175     def QuadToTri (self, IDsOfElements, theCriterion):
2176         if IDsOfElements == []:
2177             IDsOfElements = self.GetElementsId()
2178         return self.editor.QuadToTri(IDsOfElements, GetFunctor(theCriterion))
2179
2180     ## Split quadrangles into triangles.
2181     #  @param theObject object to taking list of elements from, is mesh, submesh or group
2182     #  @param theCriterion  is FT_...; used to choose a diagonal for splitting.
2183     def QuadToTriObject (self, theObject, theCriterion):
2184         return self.editor.QuadToTriObject(theObject, GetFunctor(theCriterion))
2185
2186     ## Split quadrangles into triangles.
2187     #  @param theElems  The faces to be splitted
2188     #  @param the13Diag is used to choose a diagonal for splitting.
2189     #  @return TRUE in case of success, FALSE otherwise.
2190     def SplitQuad (self, IDsOfElements, Diag13):
2191         if IDsOfElements == []:
2192             IDsOfElements = self.GetElementsId()
2193         return self.editor.SplitQuad(IDsOfElements, Diag13)
2194
2195     ## Split quadrangles into triangles.
2196     #  @param theObject is object to taking list of elements from, is mesh, submesh or group
2197     def SplitQuadObject (self, theObject, Diag13):
2198         return self.editor.SplitQuadObject(theObject, Diag13)
2199
2200     ## Find better splitting of the given quadrangle.
2201     #  @param IDOfQuad  ID of the quadrangle to be splitted.
2202     #  @param theCriterion is FT_...; a criterion to choose a diagonal for splitting.
2203     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
2204     #          diagonal is better, 0 if error occurs.
2205     def BestSplit (self, IDOfQuad, theCriterion):
2206         return self.editor.BestSplit(IDOfQuad, GetFunctor(theCriterion))
2207
2208     ## Split quafrangle faces near triangular facets of volumes
2209     #
2210     def SplitQuadsNearTriangularFacets(self):
2211         faces_array = self.GetElementsByType(SMESH.FACE)
2212         for face_id in faces_array:
2213             if self.GetElemNbNodes(face_id) == 4: # quadrangle
2214                 quad_nodes = self.mesh.GetElemNodes(face_id)
2215                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2216                 isVolumeFound = False
2217                 for node1_elem in node1_elems:
2218                     if not isVolumeFound:
2219                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2220                             nb_nodes = self.GetElemNbNodes(node1_elem)
2221                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
2222                                 volume_elem = node1_elem
2223                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
2224                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
2225                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
2226                                         isVolumeFound = True
2227                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
2228                                             self.SplitQuad([face_id], False) # diagonal 2-4
2229                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
2230                                         isVolumeFound = True
2231                                         self.SplitQuad([face_id], True) # diagonal 1-3
2232                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
2233                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
2234                                         isVolumeFound = True
2235                                         self.SplitQuad([face_id], True) # diagonal 1-3
2236
2237     ## @brief Split hexahedrons into tetrahedrons.
2238     #
2239     #  Use pattern mapping functionality for splitting.
2240     #  @param theObject object to take list of hexahedrons from; is mesh, submesh or group.
2241     #  @param theNode000,theNode001 is in range [0,7]; give an orientation of the
2242     #         pattern relatively each hexahedron: the (0,0,0) key-point of pattern
2243     #         will be mapped into <theNode000>-th node of each volume, the (0,0,1)
2244     #         key-point will be mapped into <theNode001>-th node of each volume.
2245     #         The (0,0,0) key-point of used pattern corresponds to not split corner.
2246     #  @return TRUE in case of success, FALSE otherwise.
2247     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
2248         # Pattern:     5.---------.6
2249         #              /|#*      /|
2250         #             / | #*    / |
2251         #            /  |  # * /  |
2252         #           /   |   # /*  |
2253         # (0,0,1) 4.---------.7 * |
2254         #          |#*  |1   | # *|
2255         #          | # *.----|---#.2
2256         #          |  #/ *   |   /
2257         #          |  /#  *  |  /
2258         #          | /   # * | /
2259         #          |/      #*|/
2260         # (0,0,0) 0.---------.3
2261         pattern_tetra = "!!! Nb of points: \n 8 \n\
2262         !!! Points: \n\
2263         0 0 0  !- 0 \n\
2264         0 1 0  !- 1 \n\
2265         1 1 0  !- 2 \n\
2266         1 0 0  !- 3 \n\
2267         0 0 1  !- 4 \n\
2268         0 1 1  !- 5 \n\
2269         1 1 1  !- 6 \n\
2270         1 0 1  !- 7 \n\
2271         !!! Indices of points of 6 tetras: \n\
2272         0 3 4 1 \n\
2273         7 4 3 1 \n\
2274         4 7 5 1 \n\
2275         6 2 5 7 \n\
2276         1 5 2 7 \n\
2277         2 3 1 7 \n"
2278
2279         pattern = GetPattern()
2280         isDone  = pattern.LoadFromFile(pattern_tetra)
2281         if not isDone:
2282             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2283             return isDone
2284
2285         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2286         isDone = pattern.MakeMesh(self.mesh, False, False)
2287         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2288
2289         # split quafrangle faces near triangular facets of volumes
2290         self.SplitQuadsNearTriangularFacets()
2291
2292         return isDone
2293
2294     ## @brief Split hexahedrons into prisms.
2295     #
2296     #  Use pattern mapping functionality for splitting.
2297     #  @param theObject object to take list of hexahedrons from; is mesh, submesh or group.
2298     #  @param theNode000,theNode001 is in range [0,7]; give an orientation of the
2299     #         pattern relatively each hexahedron: the (0,0,0) key-point of pattern
2300     #         will be mapped into <theNode000>-th node of each volume, the (0,0,1)
2301     #         key-point will be mapped into <theNode001>-th node of each volume.
2302     #         The edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
2303     #  @param @return TRUE in case of success, FALSE otherwise.
2304     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
2305         # Pattern:     5.---------.6
2306         #              /|#       /|
2307         #             / | #     / |
2308         #            /  |  #   /  |
2309         #           /   |   # /   |
2310         # (0,0,1) 4.---------.7   |
2311         #          |    |    |    |
2312         #          |   1.----|----.2
2313         #          |   / *   |   /
2314         #          |  /   *  |  /
2315         #          | /     * | /
2316         #          |/       *|/
2317         # (0,0,0) 0.---------.3
2318         pattern_prism = "!!! Nb of points: \n 8 \n\
2319         !!! Points: \n\
2320         0 0 0  !- 0 \n\
2321         0 1 0  !- 1 \n\
2322         1 1 0  !- 2 \n\
2323         1 0 0  !- 3 \n\
2324         0 0 1  !- 4 \n\
2325         0 1 1  !- 5 \n\
2326         1 1 1  !- 6 \n\
2327         1 0 1  !- 7 \n\
2328         !!! Indices of points of 2 prisms: \n\
2329         0 1 3 4 5 7 \n\
2330         2 3 1 6 7 5 \n"
2331
2332         pattern = GetPattern()
2333         isDone  = pattern.LoadFromFile(pattern_prism)
2334         if not isDone:
2335             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2336             return isDone
2337
2338         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2339         isDone = pattern.MakeMesh(self.mesh, False, False)
2340         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2341
2342         # split quafrangle faces near triangular facets of volumes
2343         self.SplitQuadsNearTriangularFacets()
2344
2345         return isDone
2346     
2347     ## Smooth elements
2348     #  @param IDsOfElements list if ids of elements to smooth
2349     #  @param IDsOfFixedNodes list of ids of fixed nodes.
2350     #  Note that nodes built on edges and boundary nodes are always fixed.
2351     #  @param MaxNbOfIterations maximum number of iterations
2352     #  @param MaxAspectRatio varies in range [1.0, inf]
2353     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2354     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
2355                MaxNbOfIterations, MaxAspectRatio, Method):
2356         if IDsOfElements == []:
2357             IDsOfElements = self.GetElementsId()
2358         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
2359                                   MaxNbOfIterations, MaxAspectRatio, Method)
2360     
2361     ## Smooth elements belong to given object
2362     #  @param theObject object to smooth
2363     #  @param IDsOfFixedNodes list of ids of fixed nodes.
2364     #  Note that nodes built on edges and boundary nodes are always fixed.
2365     #  @param MaxNbOfIterations maximum number of iterations
2366     #  @param MaxAspectRatio varies in range [1.0, inf]
2367     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2368     def SmoothObject(self, theObject, IDsOfFixedNodes, 
2369                      MaxNbOfIterations, MaxxAspectRatio, Method):
2370         return self.editor.SmoothObject(theObject, IDsOfFixedNodes, 
2371                                         MaxNbOfIterations, MaxxAspectRatio, Method)
2372
2373     ## Parametric smooth the given elements
2374     #  @param IDsOfElements list if ids of elements to smooth
2375     #  @param IDsOfFixedNodes list of ids of fixed nodes.
2376     #  Note that nodes built on edges and boundary nodes are always fixed.
2377     #  @param MaxNbOfIterations maximum number of iterations
2378     #  @param MaxAspectRatio varies in range [1.0, inf]
2379     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2380     def SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2381                          MaxNbOfIterations, MaxAspectRatio, Method):
2382         if IDsOfElements == []:
2383             IDsOfElements = self.GetElementsId()
2384         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2385                                             MaxNbOfIterations, MaxAspectRatio, Method)
2386     
2387     ## Parametric smooth elements belong to given object
2388     #  @param theObject object to smooth
2389     #  @param IDsOfFixedNodes list of ids of fixed nodes.
2390     #  Note that nodes built on edges and boundary nodes are always fixed.
2391     #  @param MaxNbOfIterations maximum number of iterations
2392     #  @param MaxAspectRatio varies in range [1.0, inf]
2393     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2394     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
2395                                MaxNbOfIterations, MaxAspectRatio, Method):
2396         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
2397                                                   MaxNbOfIterations, MaxAspectRatio, Method)
2398
2399     ## Converts all mesh to quadratic one, deletes old elements, replacing 
2400     #  them with quadratic ones with the same id.
2401     def ConvertToQuadratic(self, theForce3d):
2402         self.editor.ConvertToQuadratic(theForce3d)
2403
2404     ## Converts all mesh from quadratic to ordinary ones,
2405     #  deletes old quadratic elements, \n replacing 
2406     #  them with ordinary mesh elements with the same id.
2407     def ConvertFromQuadratic(self):
2408         return self.editor.ConvertFromQuadratic()
2409
2410     ## Renumber mesh nodes
2411     def RenumberNodes(self):
2412         self.editor.RenumberNodes()
2413
2414     ## Renumber mesh elements
2415     def RenumberElements(self):
2416         self.editor.RenumberElements()
2417
2418     ## Generate new elements by rotation of the elements around the axis
2419     #  @param IDsOfElements list of ids of elements to sweep
2420     #  @param Axix axis of rotation, AxisStruct or line(geom object)
2421     #  @param AngleInRadians angle of Rotation
2422     #  @param NbOfSteps number of steps
2423     #  @param Tolerance tolerance
2424     def RotationSweep(self, IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance):
2425         if IDsOfElements == []:
2426             IDsOfElements = self.GetElementsId()
2427         if ( isinstance( Axix, geompy.GEOM._objref_GEOM_Object)):
2428             Axix = GetAxisStruct(Axix)
2429         self.editor.RotationSweep(IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance)
2430
2431     ## Generate new elements by rotation of the elements of object around the axis
2432     #  @param theObject object wich elements should be sweeped
2433     #  @param Axix axis of rotation, AxisStruct or line(geom object)
2434     #  @param AngleInRadians angle of Rotation
2435     #  @param NbOfSteps number of steps
2436     #  @param Tolerance tolerance
2437     def RotationSweepObject(self, theObject, Axix, AngleInRadians, NbOfSteps, Tolerance):
2438         if ( isinstance( Axix, geompy.GEOM._objref_GEOM_Object)):
2439             Axix = GetAxisStruct(Axix)
2440         self.editor.RotationSweepObject(theObject, Axix, AngleInRadians, NbOfSteps, Tolerance)
2441
2442     ## Generate new elements by extrusion of the elements with given ids
2443     #  @param IDsOfElements list of elements ids for extrusion
2444     #  @param StepVector vector, defining the direction and value of extrusion 
2445     #  @param NbOfSteps the number of steps
2446     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps):
2447         if IDsOfElements == []:
2448             IDsOfElements = self.GetElementsId()
2449         if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2450             StepVector = GetDirStruct(StepVector)
2451         self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
2452
2453     ## Generate new elements by extrusion of the elements with given ids
2454     #  @param IDsOfElements is ids of elements
2455     #  @param StepVector vector, defining the direction and value of extrusion 
2456     #  @param NbOfSteps the number of steps
2457     #  @param ExtrFlags set flags for performing extrusion
2458     #  @param SewTolerance uses for comparing locations of nodes if flag
2459     #         EXTRUSION_FLAG_SEW is set
2460     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance):
2461         if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2462             StepVector = GetDirStruct(StepVector)
2463         self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance)
2464
2465     ## Generate new elements by extrusion of the elements belong to object
2466     #  @param theObject object wich elements should be processed
2467     #  @param StepVector vector, defining the direction and value of extrusion 
2468     #  @param NbOfSteps the number of steps
2469     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps):
2470         if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2471             StepVector = GetDirStruct(StepVector)
2472         self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
2473
2474     ## Generate new elements by extrusion of the elements belong to object
2475     #  @param theObject object wich elements should be processed
2476     #  @param StepVector vector, defining the direction and value of extrusion 
2477     #  @param NbOfSteps the number of steps
2478     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps):
2479         if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2480             StepVector = GetDirStruct(StepVector)
2481         self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
2482     
2483     ## Generate new elements by extrusion of the elements belong to object
2484     #  @param theObject object wich elements should be processed
2485     #  @param StepVector vector, defining the direction and value of extrusion 
2486     #  @param NbOfSteps the number of steps    
2487     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps):
2488         if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2489             StepVector = GetDirStruct(StepVector)
2490         self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
2491
2492     ## Generate new elements by extrusion of the given elements
2493     #  A path of extrusion must be a meshed edge.
2494     #  @param IDsOfElements is ids of elements
2495     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2496     #  @param PathShape is shape(edge); as the mesh can be complex, the edge is used to define the sub-mesh for the path
2497     #  @param NodeStart the first or the last node on the edge. It is used to define the direction of extrusion
2498     #  @param HasAngles allows the shape to be rotated around the path to get the resulting mesh in a helical fashion
2499     #  @param Angles list of angles
2500     #  @param HasRefPoint allows to use base point 
2501     #  @param RefPoint point around which the shape is rotated(the mass center of the shape by default).
2502     #         User can specify any point as the Base Point and the shape will be rotated with respect to this point.
2503     #  @param LinearVariation makes compute rotation angles as linear variation of given Angles along path steps
2504     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
2505                            HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation=False):
2506         if IDsOfElements == []:
2507             IDsOfElements = self.GetElementsId()
2508         if ( isinstance( RefPoint, geompy.GEOM._objref_GEOM_Object)):
2509             RefPoint = GetPointStruct(RefPoint)
2510             pass
2511         return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh.GetMesh(), PathShape, NodeStart,
2512                                               HasAngles, Angles, HasRefPoint, RefPoint)
2513
2514     ## Generate new elements by extrusion of the elements belong to object
2515     #  A path of extrusion must be a meshed edge.
2516     #  @param IDsOfElements is ids of elements
2517     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2518     #  @param PathShape is shape(edge); as the mesh can be complex, the edge is used to define the sub-mesh for the path
2519     #  @param NodeStart the first or the last node on the edge. It is used to define the direction of extrusion
2520     #  @param HasAngles allows the shape to be rotated around the path to get the resulting mesh in a helical fashion
2521     #  @param Angles list of angles
2522     #  @param HasRefPoint allows to use base point 
2523     #  @param RefPoint point around which the shape is rotated(the mass center of the shape by default).
2524     #         User can specify any point as the Base Point and the shape will be rotated with respect to this point.
2525     #  @param LinearVariation makes compute rotation angles as linear variation of given Angles along path steps
2526     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
2527                                  HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation=False):
2528         if ( isinstance( RefPoint, geompy.GEOM._objref_GEOM_Object)):
2529             RefPoint = GetPointStruct(RefPoint) 
2530         return self.editor.ExtrusionAlongPathObject(theObject, PathMesh.GetMesh(), PathShape, NodeStart,
2531                                                     HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation)
2532     
2533     ## Symmetrical copy of mesh elements
2534     #  @param IDsOfElements list of elements ids
2535     #  @param Mirror is AxisStruct or geom object(point, line, plane)
2536     #  @param theMirrorType is  POINT, AXIS or PLANE
2537     #  If the Mirror is geom object this parameter is unnecessary
2538     #  @param Copy allows to copy element(Copy is 1) or to replace with its mirroring(Copy is 0)
2539     def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0):
2540         if IDsOfElements == []:
2541             IDsOfElements = self.GetElementsId()
2542         if ( isinstance( Mirror, geompy.GEOM._objref_GEOM_Object)):
2543             Mirror = GetAxisStruct(Mirror)
2544         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
2545
2546     ## Symmetrical copy of object
2547     #  @param theObject mesh, submesh or group
2548     #  @param Mirror is AxisStruct or geom object(point, line, plane)
2549     #  @param theMirrorType is  POINT, AXIS or PLANE
2550     #  If the Mirror is geom object this parameter is unnecessary
2551     #  @param Copy allows to copy element(Copy is 1) or to replace with its mirroring(Copy is 0)
2552     def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0):
2553         if ( isinstance( Mirror, geompy.GEOM._objref_GEOM_Object)):
2554             Mirror = GetAxisStruct(Mirror)
2555         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
2556
2557     ## Translates the elements
2558     #  @param IDsOfElements list of elements ids
2559     #  @param Vector direction of translation(DirStruct or vector)
2560     #  @param Copy allows to copy the translated elements
2561     def Translate(self, IDsOfElements, Vector, Copy):
2562         if IDsOfElements == []:
2563             IDsOfElements = self.GetElementsId()
2564         if ( isinstance( Vector, geompy.GEOM._objref_GEOM_Object)):
2565             Vector = GetDirStruct(Vector)
2566         self.editor.Translate(IDsOfElements, Vector, Copy)
2567
2568     ## Translates the object
2569     #  @param theObject object to translate(mesh, submesh, or group)
2570     #  @param Vector direction of translation(DirStruct or geom vector)
2571     #  @param Copy allows to copy the translated elements
2572     def TranslateObject(self, theObject, Vector, Copy):
2573         if ( isinstance( Vector, geompy.GEOM._objref_GEOM_Object)):
2574             Vector = GetDirStruct(Vector)
2575         self.editor.TranslateObject(theObject, Vector, Copy)
2576
2577     ## Rotates the elements
2578     #  @param IDsOfElements list of elements ids
2579     #  @param Axis axis of rotation(AxisStruct or geom line)
2580     #  @param AngleInRadians angle of rotation(in radians)
2581     #  @param Copy allows to copy the rotated elements   
2582     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy):
2583         if IDsOfElements == []:
2584             IDsOfElements = self.GetElementsId()
2585         if ( isinstance( Axis, geompy.GEOM._objref_GEOM_Object)):
2586             Axis = GetAxisStruct(Axis)
2587         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
2588
2589     ## Rotates the object
2590     #  @param theObject object to rotate(mesh, submesh, or group)
2591     #  @param Axis axis of rotation(AxisStruct or geom line)
2592     #  @param AngleInRadians angle of rotation(in radians)
2593     #  @param Copy allows to copy the rotated elements
2594     def RotateObject (self, theObject, Axis, AngleInRadians, Copy):
2595         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
2596
2597     ## Find group of nodes close to each other within Tolerance.
2598     #  @param Tolerance tolerance value
2599     #  @param list of group of nodes
2600     def FindCoincidentNodes (self, Tolerance):
2601         return self.editor.FindCoincidentNodes(Tolerance)
2602
2603     ## Find group of nodes close to each other within Tolerance.
2604     #  @param Tolerance tolerance value
2605     #  @param SubMeshOrGroup SubMesh or Group
2606     #  @param list of group of nodes
2607     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance):
2608         return self.editor.FindCoincidentNodesOnPart(SubMeshOrGroup, Tolerance)
2609
2610     ## Merge nodes
2611     #  @param list of group of nodes
2612     def MergeNodes (self, GroupsOfNodes):
2613         self.editor.MergeNodes(GroupsOfNodes)
2614
2615     ## Find elements built on the same nodes.
2616     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
2617     #  @return a list of groups of equal elements
2618     def FindEqualElements (self, MeshOrSubMeshOrGroup):
2619         return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
2620
2621     ## Merge elements in each given group.
2622     #  @param GroupsOfElementsID groups of elements for merging
2623     def MergeElements(self, GroupsOfElementsID):
2624         self.editor.MergeElements(GroupsOfElementsID)
2625
2626     ## Remove all but one of elements built on the same nodes.
2627     def MergeEqualElements(self):
2628         self.editor.MergeEqualElements()
2629         
2630     ## Sew free borders
2631     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2632                         FirstNodeID2, SecondNodeID2, LastNodeID2,
2633                         CreatePolygons, CreatePolyedrs):
2634         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2635                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
2636                                           CreatePolygons, CreatePolyedrs)
2637
2638     ## Sew conform free borders
2639     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2640                                FirstNodeID2, SecondNodeID2):
2641         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2642                                                  FirstNodeID2, SecondNodeID2)
2643     
2644     ## Sew border to side
2645     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2646                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
2647         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2648                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
2649
2650     ## Sew two sides of a mesh. Nodes belonging to Side1 are
2651     #  merged with nodes of elements of Side2.
2652     #  Number of elements in theSide1 and in theSide2 must be
2653     #  equal and they should have similar node connectivity.
2654     #  The nodes to merge should belong to sides borders and
2655     #  the first node should be linked to the second.
2656     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
2657                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2658                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
2659         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
2660                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2661                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
2662
2663     ## Set new nodes for given element.
2664     #  @param ide the element id
2665     #  @param newIDs nodes ids
2666     #  @return If number of nodes is not corresponded to type of element - returns false
2667     def ChangeElemNodes(self, ide, newIDs):
2668         return self.editor.ChangeElemNodes(ide, newIDs)
2669     
2670     ## If during last operation of MeshEditor some nodes were
2671     #  created this method returns list of it's IDs, \n
2672     #  if new nodes not created - returns empty list
2673     def GetLastCreatedNodes(self):
2674         return self.editor.GetLastCreatedNodes()
2675
2676     ## If during last operation of MeshEditor some elements were
2677     #  created this method returns list of it's IDs, \n
2678     #  if new elements not creared - returns empty list
2679     def GetLastCreatedElems(self):
2680         return self.editor.GetLastCreatedElems()