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