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