Salome HOME
0021308: EDF 1923 SMESH: Remove hard-coded dependency of the external mesh plugins...
[modules/smesh.git] / src / SMESH_SWIG / smeshDC.py
1 # Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 #  File   : smesh.py
20 #  Author : Francis KLOSS, OCC
21 #  Module : SMESH
22
23 ## @package smesh
24 #  Python API for SALOME %Mesh module
25
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating  Creating meshes
28 ## @{
29 ##   @defgroup l2_impexp     Importing and exporting meshes
30 ##   @defgroup l2_construct  Constructing meshes
31 ##   @defgroup l2_algorithms Defining Algorithms
32 ##   @{
33 ##     @defgroup l3_algos_basic   Basic meshing algorithms
34 ##     @defgroup l3_algos_proj    Projection Algorithms
35 ##     @defgroup l3_algos_radialp Radial Prism
36 ##     @defgroup l3_algos_segmarv Segments around Vertex
37 ##     @defgroup l3_algos_3dextr  3D extrusion meshing algorithm
38
39 ##   @}
40 ##   @defgroup l2_hypotheses Defining hypotheses
41 ##   @{
42 ##     @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ##     @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ##     @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ##     @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ##     @defgroup l3_hypos_additi Additional Hypotheses
47
48 ##   @}
49 ##   @defgroup l2_submeshes Constructing submeshes
50 ##   @defgroup l2_compounds Building Compounds
51 ##   @defgroup l2_editing   Editing Meshes
52
53 ## @}
54 ## @defgroup l1_meshinfo  Mesh Information
55 ## @defgroup l1_controls  Quality controls and Filtering
56 ## @defgroup l1_grouping  Grouping elements
57 ## @{
58 ##   @defgroup l2_grps_create Creating groups
59 ##   @defgroup l2_grps_edit   Editing groups
60 ##   @defgroup l2_grps_operon Using operations on groups
61 ##   @defgroup l2_grps_delete Deleting Groups
62
63 ## @}
64 ## @defgroup l1_modifying Modifying meshes
65 ## @{
66 ##   @defgroup l2_modif_add      Adding nodes and elements
67 ##   @defgroup l2_modif_del      Removing nodes and elements
68 ##   @defgroup l2_modif_edit     Modifying nodes and elements
69 ##   @defgroup l2_modif_renumber Renumbering nodes and elements
70 ##   @defgroup l2_modif_trsf     Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ##   @defgroup l2_modif_movenode Moving nodes
72 ##   @defgroup l2_modif_throughp Mesh through point
73 ##   @defgroup l2_modif_invdiag  Diagonal inversion of elements
74 ##   @defgroup l2_modif_unitetri Uniting triangles
75 ##   @defgroup l2_modif_changori Changing orientation of elements
76 ##   @defgroup l2_modif_cutquadr Cutting quadrangles
77 ##   @defgroup l2_modif_smooth   Smoothing
78 ##   @defgroup l2_modif_extrurev Extrusion and Revolution
79 ##   @defgroup l2_modif_patterns Pattern mapping
80 ##   @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
81
82 ## @}
83 ## @defgroup l1_measurements Measurements
84
85 import salome
86 import geompyDC
87
88 import SMESH # This is necessary for back compatibility
89 from   SMESH import *
90
91 import SALOME
92 import SALOMEDS
93
94 ## @addtogroup l1_auxiliary
95 ## @{
96
97 # MirrorType enumeration
98 POINT = SMESH_MeshEditor.POINT
99 AXIS =  SMESH_MeshEditor.AXIS
100 PLANE = SMESH_MeshEditor.PLANE
101
102 # Smooth_Method enumeration
103 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
104 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
105
106 PrecisionConfusion = 1e-07
107
108 # TopAbs_State enumeration
109 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
110
111 # Methods of splitting a hexahedron into tetrahedra
112 Hex_5Tet, Hex_6Tet, Hex_24Tet = 1, 2, 3
113
114 ## Converts an angle from degrees to radians
115 def DegreesToRadians(AngleInDegrees):
116     from math import pi
117     return AngleInDegrees * pi / 180.0
118
119 import salome_notebook
120 notebook = salome_notebook.notebook
121 # Salome notebook variable separator
122 var_separator = ":"
123
124 ## Return list of variable values from salome notebook.
125 #  The last argument, if is callable, is used to modify values got from notebook
126 def ParseParameters(*args):
127     Result = []
128     Parameters = ""
129     hasVariables = False
130     varModifFun=None
131     if args and callable( args[-1] ):
132         args, varModifFun = args[:-1], args[-1]
133     for parameter in args:
134
135         Parameters += str(parameter) + var_separator
136
137         if isinstance(parameter,str):
138             # check if there is an inexistent variable name
139             if not notebook.isVariable(parameter):
140                 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
141             parameter = notebook.get(parameter)
142             hasVariables = True
143             if varModifFun:
144                 parameter = varModifFun(parameter)
145                 pass
146             pass
147         Result.append(parameter)
148
149         pass
150     Parameters = Parameters[:-1]
151     Result.append( Parameters )
152     Result.append( hasVariables )
153     return Result
154
155 # Parse parameters converting variables to radians
156 def ParseAngles(*args):
157     return ParseParameters( *( args + (DegreesToRadians, )))
158
159 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
160 # Parameters are stored in PointStruct.parameters attribute
161 def __initPointStruct(point,*args):
162     point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
163     pass
164 SMESH.PointStruct.__init__ = __initPointStruct
165
166 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
167 # Parameters are stored in AxisStruct.parameters attribute
168 def __initAxisStruct(ax,*args):
169     ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
170     pass
171 SMESH.AxisStruct.__init__ = __initAxisStruct
172
173
174 def IsEqual(val1, val2, tol=PrecisionConfusion):
175     if abs(val1 - val2) < tol:
176         return True
177     return False
178
179 NO_NAME = "NoName"
180
181 ## Gets object name
182 def GetName(obj):
183     if obj:
184         # object not null
185         if isinstance(obj, SALOMEDS._objref_SObject):
186             # study object
187             return obj.GetName()
188         ior  = salome.orb.object_to_string(obj)
189         if ior:
190             # CORBA object
191             studies = salome.myStudyManager.GetOpenStudies()
192             for sname in studies:
193                 s = salome.myStudyManager.GetStudyByName(sname)
194                 if not s: continue
195                 sobj = s.FindObjectIOR(ior)
196                 if not sobj: continue
197                 return sobj.GetName()
198             if hasattr(obj, "GetName"):
199                 # unknown CORBA object, having GetName() method
200                 return obj.GetName()
201             else:
202                 # unknown CORBA object, no GetName() method
203                 return NO_NAME
204             pass
205         if hasattr(obj, "GetName"):
206             # unknown non-CORBA object, having GetName() method
207             return obj.GetName()
208         pass
209     raise RuntimeError, "Null or invalid object"
210
211 ## Prints error message if a hypothesis was not assigned.
212 def TreatHypoStatus(status, hypName, geomName, isAlgo):
213     if isAlgo:
214         hypType = "algorithm"
215     else:
216         hypType = "hypothesis"
217         pass
218     if status == HYP_UNKNOWN_FATAL :
219         reason = "for unknown reason"
220     elif status == HYP_INCOMPATIBLE :
221         reason = "this hypothesis mismatches the algorithm"
222     elif status == HYP_NOTCONFORM :
223         reason = "a non-conform mesh would be built"
224     elif status == HYP_ALREADY_EXIST :
225         if isAlgo: return # it does not influence anything
226         reason = hypType + " of the same dimension is already assigned to this shape"
227     elif status == HYP_BAD_DIM :
228         reason = hypType + " mismatches the shape"
229     elif status == HYP_CONCURENT :
230         reason = "there are concurrent hypotheses on sub-shapes"
231     elif status == HYP_BAD_SUBSHAPE :
232         reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
233     elif status == HYP_BAD_GEOMETRY:
234         reason = "geometry mismatches the expectation of the algorithm"
235     elif status == HYP_HIDDEN_ALGO:
236         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
237     elif status == HYP_HIDING_ALGO:
238         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
239     elif status == HYP_NEED_SHAPE:
240         reason = "Algorithm can't work without shape"
241     else:
242         return
243     hypName = '"' + hypName + '"'
244     geomName= '"' + geomName+ '"'
245     if status < HYP_UNKNOWN_FATAL and not geomName =='""':
246         print hypName, "was assigned to",    geomName,"but", reason
247     elif not geomName == '""':
248         print hypName, "was not assigned to",geomName,":", reason
249     else:
250         print hypName, "was not assigned:", reason
251         pass
252
253 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
254 def AssureGeomPublished(mesh, geom, name=''):
255     if not isinstance( geom, geompyDC.GEOM._objref_GEOM_Object ):
256         return
257     if not geom.IsSame( mesh.geom ) and \
258            not geom.GetStudyEntry() and \
259            mesh.smeshpyD.GetCurrentStudy():
260         ## set the study
261         studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
262         if studyID != mesh.geompyD.myStudyId:
263             mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
264         ## get a name
265         if not name and geom.GetShapeType() != geompyDC.GEOM.COMPOUND:
266             # for all groups SubShapeName() returns "Compound_-1"
267             name = mesh.geompyD.SubShapeName(geom, mesh.geom)
268         if not name:
269             name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
270         ## publish
271         mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
272     return
273
274 ## Return the first vertex of a geomertical edge by ignoring orienation
275 def FirstVertexOnCurve(edge):
276     from geompy import SubShapeAll, ShapeType, KindOfShape, PointCoordinates
277     vv = SubShapeAll( edge, ShapeType["VERTEX"])
278     if not vv:
279         raise TypeError, "Given object has no vertices"
280     if len( vv ) == 1: return vv[0]
281     info = KindOfShape(edge)
282     xyz = info[1:4] # coords of the first vertex
283     xyz1  = PointCoordinates( vv[0] )
284     xyz2  = PointCoordinates( vv[1] )
285     dist1, dist2 = 0,0
286     for i in range(3):
287         dist1 += abs( xyz[i] - xyz1[i] )
288         dist2 += abs( xyz[i] - xyz2[i] )
289     if dist1 < dist2:
290         return vv[0]
291     else:
292         return vv[1]
293
294 # end of l1_auxiliary
295 ## @}
296
297 # All methods of this class are accessible directly from the smesh.py package.
298 class smeshDC(SMESH._objref_SMESH_Gen):
299
300     ## Dump component to the Python script
301     #  This method overrides IDL function to allow default values for the parameters.
302     def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
303         return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
304
305     ## Set mode of DumpPython(), \a historical or \a snapshot.
306     # In the \a historical mode, the Python Dump script includes all commands
307     # performed by SMESH engine. In the \a snapshot mode, commands
308     # relating to objects removed from the Study are excluded from the script
309     # as well as commands not influencing the current state of meshes
310     def SetDumpPythonHistorical(self, isHistorical):
311         if isHistorical: val = "true"
312         else:            val = "false"
313         SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
314
315     ## Sets the current study and Geometry component
316     #  @ingroup l1_auxiliary
317     def init_smesh(self,theStudy,geompyD):
318         self.SetCurrentStudy(theStudy,geompyD)
319
320     ## Creates an empty Mesh. This mesh can have an underlying geometry.
321     #  @param obj the Geometrical object on which the mesh is built. If not defined,
322     #             the mesh will have no underlying geometry.
323     #  @param name the name for the new mesh.
324     #  @return an instance of Mesh class.
325     #  @ingroup l2_construct
326     def Mesh(self, obj=0, name=0):
327         if isinstance(obj,str):
328             obj,name = name,obj
329         return Mesh(self,self.geompyD,obj,name)
330
331     ## Returns a long value from enumeration
332     #  Should be used for SMESH.FunctorType enumeration
333     #  @ingroup l1_controls
334     def EnumToLong(self,theItem):
335         return theItem._v
336
337     ## Returns a string representation of the color.
338     #  To be used with filters.
339     #  @param c color value (SALOMEDS.Color)
340     #  @ingroup l1_controls
341     def ColorToString(self,c):
342         val = ""
343         if isinstance(c, SALOMEDS.Color):
344             val = "%s;%s;%s" % (c.R, c.G, c.B)
345         elif isinstance(c, str):
346             val = c
347         else:
348             raise ValueError, "Color value should be of string or SALOMEDS.Color type"
349         return val
350
351     ## Gets PointStruct from vertex
352     #  @param theVertex a GEOM object(vertex)
353     #  @return SMESH.PointStruct
354     #  @ingroup l1_auxiliary
355     def GetPointStruct(self,theVertex):
356         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
357         return PointStruct(x,y,z)
358
359     ## Gets DirStruct from vector
360     #  @param theVector a GEOM object(vector)
361     #  @return SMESH.DirStruct
362     #  @ingroup l1_auxiliary
363     def GetDirStruct(self,theVector):
364         vertices = self.geompyD.SubShapeAll( theVector, geompyDC.ShapeType["VERTEX"] )
365         if(len(vertices) != 2):
366             print "Error: vector object is incorrect."
367             return None
368         p1 = self.geompyD.PointCoordinates(vertices[0])
369         p2 = self.geompyD.PointCoordinates(vertices[1])
370         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
371         dirst = DirStruct(pnt)
372         return dirst
373
374     ## Makes DirStruct from a triplet
375     #  @param x,y,z vector components
376     #  @return SMESH.DirStruct
377     #  @ingroup l1_auxiliary
378     def MakeDirStruct(self,x,y,z):
379         pnt = PointStruct(x,y,z)
380         return DirStruct(pnt)
381
382     ## Get AxisStruct from object
383     #  @param theObj a GEOM object (line or plane)
384     #  @return SMESH.AxisStruct
385     #  @ingroup l1_auxiliary
386     def GetAxisStruct(self,theObj):
387         edges = self.geompyD.SubShapeAll( theObj, geompyDC.ShapeType["EDGE"] )
388         if len(edges) > 1:
389             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geompyDC.ShapeType["VERTEX"] )
390             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geompyDC.ShapeType["VERTEX"] )
391             vertex1 = self.geompyD.PointCoordinates(vertex1)
392             vertex2 = self.geompyD.PointCoordinates(vertex2)
393             vertex3 = self.geompyD.PointCoordinates(vertex3)
394             vertex4 = self.geompyD.PointCoordinates(vertex4)
395             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
396             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
397             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] ]
398             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
399             return axis
400         elif len(edges) == 1:
401             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geompyDC.ShapeType["VERTEX"] )
402             p1 = self.geompyD.PointCoordinates( vertex1 )
403             p2 = self.geompyD.PointCoordinates( vertex2 )
404             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
405             return axis
406         return None
407
408     # From SMESH_Gen interface:
409     # ------------------------
410
411     ## Sets the given name to the object
412     #  @param obj the object to rename
413     #  @param name a new object name
414     #  @ingroup l1_auxiliary
415     def SetName(self, obj, name):
416         if isinstance( obj, Mesh ):
417             obj = obj.GetMesh()
418         elif isinstance( obj, Mesh_Algorithm ):
419             obj = obj.GetAlgorithm()
420         ior  = salome.orb.object_to_string(obj)
421         SMESH._objref_SMESH_Gen.SetName(self, ior, name)
422
423     ## Sets the current mode
424     #  @ingroup l1_auxiliary
425     def SetEmbeddedMode( self,theMode ):
426         #self.SetEmbeddedMode(theMode)
427         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
428
429     ## Gets the current mode
430     #  @ingroup l1_auxiliary
431     def IsEmbeddedMode(self):
432         #return self.IsEmbeddedMode()
433         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
434
435     ## Sets the current study
436     #  @ingroup l1_auxiliary
437     def SetCurrentStudy( self, theStudy, geompyD = None ):
438         #self.SetCurrentStudy(theStudy)
439         if not geompyD:
440             import geompy
441             geompyD = geompy.geom
442             pass
443         self.geompyD=geompyD
444         self.SetGeomEngine(geompyD)
445         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
446         global notebook
447         if theStudy:
448             notebook = salome_notebook.NoteBook( theStudy )
449         else:
450             notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
451
452     ## Gets the current study
453     #  @ingroup l1_auxiliary
454     def GetCurrentStudy(self):
455         #return self.GetCurrentStudy()
456         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
457
458     ## Creates a Mesh object importing data from the given UNV file
459     #  @return an instance of Mesh class
460     #  @ingroup l2_impexp
461     def CreateMeshesFromUNV( self,theFileName ):
462         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
463         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
464         return aMesh
465
466     ## Creates a Mesh object(s) importing data from the given MED file
467     #  @return a list of Mesh class instances
468     #  @ingroup l2_impexp
469     def CreateMeshesFromMED( self,theFileName ):
470         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
471         aMeshes = []
472         for iMesh in range(len(aSmeshMeshes)) :
473             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
474             aMeshes.append(aMesh)
475         return aMeshes, aStatus
476
477     ## Creates a Mesh object(s) importing data from the given SAUV file
478     #  @return a list of Mesh class instances
479     #  @ingroup l2_impexp
480     def CreateMeshesFromSAUV( self,theFileName ):
481         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
482         aMeshes = []
483         for iMesh in range(len(aSmeshMeshes)) :
484             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
485             aMeshes.append(aMesh)
486         return aMeshes, aStatus
487
488     ## Creates a Mesh object importing data from the given STL file
489     #  @return an instance of Mesh class
490     #  @ingroup l2_impexp
491     def CreateMeshesFromSTL( self, theFileName ):
492         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
493         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
494         return aMesh
495
496     ## Creates Mesh objects importing data from the given CGNS file
497     #  @return an instance of Mesh class
498     #  @ingroup l2_impexp
499     def CreateMeshesFromCGNS( self, theFileName ):
500         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
501         aMeshes = []
502         for iMesh in range(len(aSmeshMeshes)) :
503             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
504             aMeshes.append(aMesh)
505         return aMeshes, aStatus
506
507     ## Concatenate the given meshes into one mesh.
508     #  @return an instance of Mesh class
509     #  @param meshes the meshes to combine into one mesh
510     #  @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
511     #  @param mergeNodesAndElements if true, equal nodes and elements aremerged
512     #  @param mergeTolerance tolerance for merging nodes
513     #  @param allGroups forces creation of groups of all elements
514     def Concatenate( self, meshes, uniteIdenticalGroups,
515                      mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False):
516         if not meshes: return None
517         for i,m in enumerate(meshes):
518             if isinstance(m, Mesh):
519                 meshes[i] = m.GetMesh()
520         mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
521         meshes[0].SetParameters(Parameters)
522         if allGroups:
523             aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
524                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
525         else:
526             aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
527                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
528         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
529         return aMesh
530
531     ## Create a mesh by copying a part of another mesh.
532     #  @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
533     #                  to copy nodes or elements not contained in any mesh object,
534     #                  pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
535     #  @param meshName a name of the new mesh
536     #  @param toCopyGroups to create in the new mesh groups the copied elements belongs to
537     #  @param toKeepIDs to preserve IDs of the copied elements or not
538     #  @return an instance of Mesh class
539     def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
540         if (isinstance( meshPart, Mesh )):
541             meshPart = meshPart.GetMesh()
542         mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
543         return Mesh(self, self.geompyD, mesh)
544
545     ## From SMESH_Gen interface
546     #  @return the list of integer values
547     #  @ingroup l1_auxiliary
548     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
549         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
550
551     ## From SMESH_Gen interface. Creates a pattern
552     #  @return an instance of SMESH_Pattern
553     #
554     #  <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
555     #  @ingroup l2_modif_patterns
556     def GetPattern(self):
557         return SMESH._objref_SMESH_Gen.GetPattern(self)
558
559     ## Sets number of segments per diagonal of boundary box of geometry by which
560     #  default segment length of appropriate 1D hypotheses is defined.
561     #  Default value is 10
562     #  @ingroup l1_auxiliary
563     def SetBoundaryBoxSegmentation(self, nbSegments):
564         SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
565
566     # Filtering. Auxiliary functions:
567     # ------------------------------
568
569     ## Creates an empty criterion
570     #  @return SMESH.Filter.Criterion
571     #  @ingroup l1_controls
572     def GetEmptyCriterion(self):
573         Type = self.EnumToLong(FT_Undefined)
574         Compare = self.EnumToLong(FT_Undefined)
575         Threshold = 0
576         ThresholdStr = ""
577         ThresholdID = ""
578         UnaryOp = self.EnumToLong(FT_Undefined)
579         BinaryOp = self.EnumToLong(FT_Undefined)
580         Tolerance = 1e-07
581         TypeOfElement = ALL
582         Precision = -1 ##@1e-07
583         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
584                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
585
586     ## Creates a criterion by the given parameters
587     #  \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
588     #  @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
589     #  @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
590     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
591     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
592     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
593     #  @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
594     #                  FT_Undefined (must be for the last criterion of all criteria)
595     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
596     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
597     #  @return SMESH.Filter.Criterion
598     #
599     #  <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
600     #  @ingroup l1_controls
601     def GetCriterion(self,elementType,
602                      CritType,
603                      Compare = FT_EqualTo,
604                      Threshold="",
605                      UnaryOp=FT_Undefined,
606                      BinaryOp=FT_Undefined,
607                      Tolerance=1e-07):
608         if not CritType in SMESH.FunctorType._items:
609             raise TypeError, "CritType should be of SMESH.FunctorType"
610         aCriterion = self.GetEmptyCriterion()
611         aCriterion.TypeOfElement = elementType
612         aCriterion.Type = self.EnumToLong(CritType)
613         aCriterion.Tolerance = Tolerance
614
615         aThreshold = Threshold
616
617         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
618             aCriterion.Compare = self.EnumToLong(Compare)
619         elif Compare == "=" or Compare == "==":
620             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
621         elif Compare == "<":
622             aCriterion.Compare = self.EnumToLong(FT_LessThan)
623         elif Compare == ">":
624             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
625         elif Compare != FT_Undefined:
626             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
627             aThreshold = Compare
628
629         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
630                         FT_BelongToCylinder, FT_LyingOnGeom]:
631             # Checks that Threshold is GEOM object
632             if isinstance(aThreshold, geompyDC.GEOM._objref_GEOM_Object):
633                 aCriterion.ThresholdStr = GetName(aThreshold)
634                 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
635                 if not aCriterion.ThresholdID:
636                     raise RuntimeError, "Threshold shape must be published"
637             else:
638                 print "Error: The Threshold should be a shape."
639                 return None
640             if isinstance(UnaryOp,float):
641                 aCriterion.Tolerance = UnaryOp
642                 UnaryOp = FT_Undefined
643                 pass
644         elif CritType == FT_RangeOfIds:
645             # Checks that Threshold is string
646             if isinstance(aThreshold, str):
647                 aCriterion.ThresholdStr = aThreshold
648             else:
649                 print "Error: The Threshold should be a string."
650                 return None
651         elif CritType == FT_CoplanarFaces:
652             # Checks the Threshold
653             if isinstance(aThreshold, int):
654                 aCriterion.ThresholdID = str(aThreshold)
655             elif isinstance(aThreshold, str):
656                 ID = int(aThreshold)
657                 if ID < 1:
658                     raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
659                 aCriterion.ThresholdID = aThreshold
660             else:
661                 raise ValueError,\
662                       "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
663         elif CritType == FT_ElemGeomType:
664             # Checks the Threshold
665             try:
666                 aCriterion.Threshold = self.EnumToLong(aThreshold)
667                 assert( aThreshold in SMESH.GeometryType._items )
668             except:
669                 if isinstance(aThreshold, int):
670                     aCriterion.Threshold = aThreshold
671                 else:
672                     print "Error: The Threshold should be an integer or SMESH.GeometryType."
673                     return None
674                 pass
675             pass
676         elif CritType == FT_GroupColor:
677             # Checks the Threshold
678             try:
679                 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
680             except:
681                 print "Error: The threshold value should be of SALOMEDS.Color type"
682                 return None
683             pass
684         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
685                           FT_LinearOrQuadratic, FT_BadOrientedVolume,
686                           FT_BareBorderFace, FT_BareBorderVolume,
687                           FT_OverConstrainedFace, FT_OverConstrainedVolume,
688                           FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
689             # At this point the Threshold is unnecessary
690             if aThreshold ==  FT_LogicalNOT:
691                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
692             elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
693                 aCriterion.BinaryOp = aThreshold
694         else:
695             # Check Threshold
696             try:
697                 aThreshold = float(aThreshold)
698                 aCriterion.Threshold = aThreshold
699             except:
700                 print "Error: The Threshold should be a number."
701                 return None
702
703         if Threshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
704             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
705
706         if Threshold in [FT_LogicalAND, FT_LogicalOR]:
707             aCriterion.BinaryOp = self.EnumToLong(Threshold)
708
709         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
710             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
711
712         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
713             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
714
715         return aCriterion
716
717     ## Creates a filter with the given parameters
718     #  @param elementType the type of elements in the group
719     #  @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
720     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
721     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
722     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
723     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
724     #         FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
725     #  @return SMESH_Filter
726     #
727     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
728     #  @ingroup l1_controls
729     def GetFilter(self,elementType,
730                   CritType=FT_Undefined,
731                   Compare=FT_EqualTo,
732                   Threshold="",
733                   UnaryOp=FT_Undefined,
734                   Tolerance=1e-07):
735         aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
736         aFilterMgr = self.CreateFilterManager()
737         aFilter = aFilterMgr.CreateFilter()
738         aCriteria = []
739         aCriteria.append(aCriterion)
740         aFilter.SetCriteria(aCriteria)
741         aFilterMgr.UnRegister()
742         return aFilter
743
744     ## Creates a filter from criteria
745     #  @param criteria a list of criteria
746     #  @return SMESH_Filter
747     #
748     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
749     #  @ingroup l1_controls
750     def GetFilterFromCriteria(self,criteria):
751         aFilterMgr = self.CreateFilterManager()
752         aFilter = aFilterMgr.CreateFilter()
753         aFilter.SetCriteria(criteria)
754         aFilterMgr.UnRegister()
755         return aFilter
756
757     ## Creates a numerical functor by its type
758     #  @param theCriterion FT_...; functor type
759     #  @return SMESH_NumericalFunctor
760     #  @ingroup l1_controls
761     def GetFunctor(self,theCriterion):
762         aFilterMgr = self.CreateFilterManager()
763         if theCriterion == FT_AspectRatio:
764             return aFilterMgr.CreateAspectRatio()
765         elif theCriterion == FT_AspectRatio3D:
766             return aFilterMgr.CreateAspectRatio3D()
767         elif theCriterion == FT_Warping:
768             return aFilterMgr.CreateWarping()
769         elif theCriterion == FT_MinimumAngle:
770             return aFilterMgr.CreateMinimumAngle()
771         elif theCriterion == FT_Taper:
772             return aFilterMgr.CreateTaper()
773         elif theCriterion == FT_Skew:
774             return aFilterMgr.CreateSkew()
775         elif theCriterion == FT_Area:
776             return aFilterMgr.CreateArea()
777         elif theCriterion == FT_Volume3D:
778             return aFilterMgr.CreateVolume3D()
779         elif theCriterion == FT_MaxElementLength2D:
780             return aFilterMgr.CreateMaxElementLength2D()
781         elif theCriterion == FT_MaxElementLength3D:
782             return aFilterMgr.CreateMaxElementLength3D()
783         elif theCriterion == FT_MultiConnection:
784             return aFilterMgr.CreateMultiConnection()
785         elif theCriterion == FT_MultiConnection2D:
786             return aFilterMgr.CreateMultiConnection2D()
787         elif theCriterion == FT_Length:
788             return aFilterMgr.CreateLength()
789         elif theCriterion == FT_Length2D:
790             return aFilterMgr.CreateLength2D()
791         else:
792             print "Error: given parameter is not numerical functor type."
793
794     ## Creates hypothesis
795     #  @param theHType mesh hypothesis type (string)
796     #  @param theLibName mesh plug-in library name
797     #  @return created hypothesis instance
798     def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
799         hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
800
801         if isinstance( hyp, SMESH._objref_SMESH_Algo ):
802             return hyp
803
804         # wrap hypothesis methods
805         #print "HYPOTHESIS", theHType
806         for meth_name in dir( hyp.__class__ ):
807             if not meth_name.startswith("Get") and \
808                not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
809                 method = getattr ( hyp.__class__, meth_name )
810                 if callable(method):
811                     setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
812
813         return hyp
814
815     ## Gets the mesh statistic
816     #  @return dictionary "element type" - "count of elements"
817     #  @ingroup l1_meshinfo
818     def GetMeshInfo(self, obj):
819         if isinstance( obj, Mesh ):
820             obj = obj.GetMesh()
821         d = {}
822         if hasattr(obj, "GetMeshInfo"):
823             values = obj.GetMeshInfo()
824             for i in range(SMESH.Entity_Last._v):
825                 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
826             pass
827         return d
828
829     ## Get minimum distance between two objects
830     #
831     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
832     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
833     #
834     #  @param src1 first source object
835     #  @param src2 second source object
836     #  @param id1 node/element id from the first source
837     #  @param id2 node/element id from the second (or first) source
838     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
839     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
840     #  @return minimum distance value
841     #  @sa GetMinDistance()
842     #  @ingroup l1_measurements
843     def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
844         result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
845         if result is None:
846             result = 0.0
847         else:
848             result = result.value
849         return result
850
851     ## Get measure structure specifying minimum distance data between two objects
852     #
853     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
854     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
855     #
856     #  @param src1 first source object
857     #  @param src2 second source object
858     #  @param id1 node/element id from the first source
859     #  @param id2 node/element id from the second (or first) source
860     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
861     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
862     #  @return Measure structure or None if input data is invalid
863     #  @sa MinDistance()
864     #  @ingroup l1_measurements
865     def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
866         if isinstance(src1, Mesh): src1 = src1.mesh
867         if isinstance(src2, Mesh): src2 = src2.mesh
868         if src2 is None and id2 != 0: src2 = src1
869         if not hasattr(src1, "_narrow"): return None
870         src1 = src1._narrow(SMESH.SMESH_IDSource)
871         if not src1: return None
872         if id1 != 0:
873             m = src1.GetMesh()
874             e = m.GetMeshEditor()
875             if isElem1:
876                 src1 = e.MakeIDSource([id1], SMESH.FACE)
877             else:
878                 src1 = e.MakeIDSource([id1], SMESH.NODE)
879             pass
880         if hasattr(src2, "_narrow"):
881             src2 = src2._narrow(SMESH.SMESH_IDSource)
882             if src2 and id2 != 0:
883                 m = src2.GetMesh()
884                 e = m.GetMeshEditor()
885                 if isElem2:
886                     src2 = e.MakeIDSource([id2], SMESH.FACE)
887                 else:
888                     src2 = e.MakeIDSource([id2], SMESH.NODE)
889                 pass
890             pass
891         aMeasurements = self.CreateMeasurements()
892         result = aMeasurements.MinDistance(src1, src2)
893         aMeasurements.UnRegister()
894         return result
895
896     ## Get bounding box of the specified object(s)
897     #  @param objects single source object or list of source objects
898     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
899     #  @sa GetBoundingBox()
900     #  @ingroup l1_measurements
901     def BoundingBox(self, objects):
902         result = self.GetBoundingBox(objects)
903         if result is None:
904             result = (0.0,)*6
905         else:
906             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
907         return result
908
909     ## Get measure structure specifying bounding box data of the specified object(s)
910     #  @param objects single source object or list of source objects
911     #  @return Measure structure
912     #  @sa BoundingBox()
913     #  @ingroup l1_measurements
914     def GetBoundingBox(self, objects):
915         if isinstance(objects, tuple):
916             objects = list(objects)
917         if not isinstance(objects, list):
918             objects = [objects]
919         srclist = []
920         for o in objects:
921             if isinstance(o, Mesh):
922                 srclist.append(o.mesh)
923             elif hasattr(o, "_narrow"):
924                 src = o._narrow(SMESH.SMESH_IDSource)
925                 if src: srclist.append(src)
926                 pass
927             pass
928         aMeasurements = self.CreateMeasurements()
929         result = aMeasurements.BoundingBox(srclist)
930         aMeasurements.UnRegister()
931         return result
932
933 import omniORB
934 #Registering the new proxy for SMESH_Gen
935 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshDC)
936
937
938 # Public class: Mesh
939 # ==================
940
941 ## This class allows defining and managing a mesh.
942 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
943 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
944 #  new nodes and elements and by changing the existing entities), to get information
945 #  about a mesh and to export a mesh into different formats.
946 class Mesh:
947
948     geom = 0
949     mesh = 0
950     editor = 0
951
952     ## Constructor
953     #
954     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
955     #  sets the GUI name of this mesh to \a name.
956     #  @param smeshpyD an instance of smeshDC class
957     #  @param geompyD an instance of geompyDC class
958     #  @param obj Shape to be meshed or SMESH_Mesh object
959     #  @param name Study name of the mesh
960     #  @ingroup l2_construct
961     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
962         self.smeshpyD=smeshpyD
963         self.geompyD=geompyD
964         if obj is None:
965             obj = 0
966         if obj != 0:
967             objHasName = True
968             if isinstance(obj, geompyDC.GEOM._objref_GEOM_Object):
969                 self.geom = obj
970                 # publish geom of mesh (issue 0021122)
971                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
972                     objHasName = False
973                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
974                     if studyID != geompyD.myStudyId:
975                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
976                         pass
977                     geo_name = "%s_%s_for_meshing"%(self.geom.GetShapeType(), id(self.geom)%100)
978                     geompyD.addToStudy( self.geom, geo_name )
979                 self.mesh = self.smeshpyD.CreateMesh(self.geom)
980
981             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
982                 self.SetMesh(obj)
983         else:
984             self.mesh = self.smeshpyD.CreateEmptyMesh()
985         if name != 0:
986             self.smeshpyD.SetName(self.mesh, name)
987         elif obj != 0 and objHasName:
988             self.smeshpyD.SetName(self.mesh, GetName(obj))
989
990         if not self.geom:
991             self.geom = self.mesh.GetShapeToMesh()
992
993         self.editor = self.mesh.GetMeshEditor()
994
995         # set self to algoCreator's
996         for attrName in dir(self):
997             attr = getattr( self, attrName )
998             if isinstance( attr, algoCreator ):
999                 setattr( self, attrName, attr.copy( self ))
1000
1001     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1002     #  @param theMesh a SMESH_Mesh object
1003     #  @ingroup l2_construct
1004     def SetMesh(self, theMesh):
1005         self.mesh = theMesh
1006         self.geom = self.mesh.GetShapeToMesh()
1007
1008     ## Returns the mesh, that is an instance of SMESH_Mesh interface
1009     #  @return a SMESH_Mesh object
1010     #  @ingroup l2_construct
1011     def GetMesh(self):
1012         return self.mesh
1013
1014     ## Gets the name of the mesh
1015     #  @return the name of the mesh as a string
1016     #  @ingroup l2_construct
1017     def GetName(self):
1018         name = GetName(self.GetMesh())
1019         return name
1020
1021     ## Sets a name to the mesh
1022     #  @param name a new name of the mesh
1023     #  @ingroup l2_construct
1024     def SetName(self, name):
1025         self.smeshpyD.SetName(self.GetMesh(), name)
1026
1027     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1028     #  The subMesh object gives access to the IDs of nodes and elements.
1029     #  @param geom a geometrical object (shape)
1030     #  @param name a name for the submesh
1031     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1032     #  @ingroup l2_submeshes
1033     def GetSubMesh(self, geom, name):
1034         AssureGeomPublished( self, geom, name )
1035         submesh = self.mesh.GetSubMesh( geom, name )
1036         return submesh
1037
1038     ## Returns the shape associated to the mesh
1039     #  @return a GEOM_Object
1040     #  @ingroup l2_construct
1041     def GetShape(self):
1042         return self.geom
1043
1044     ## Associates the given shape to the mesh (entails the recreation of the mesh)
1045     #  @param geom the shape to be meshed (GEOM_Object)
1046     #  @ingroup l2_construct
1047     def SetShape(self, geom):
1048         self.mesh = self.smeshpyD.CreateMesh(geom)
1049
1050     ## Loads mesh from the study after opening the study
1051     def Load(self):
1052         self.mesh.Load()
1053
1054     ## Returns true if the hypotheses are defined well
1055     #  @param theSubObject a sub-shape of a mesh shape
1056     #  @return True or False
1057     #  @ingroup l2_construct
1058     def IsReadyToCompute(self, theSubObject):
1059         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1060
1061     ## Returns errors of hypotheses definition.
1062     #  The list of errors is empty if everything is OK.
1063     #  @param theSubObject a sub-shape of a mesh shape
1064     #  @return a list of errors
1065     #  @ingroup l2_construct
1066     def GetAlgoState(self, theSubObject):
1067         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1068
1069     ## Returns a geometrical object on which the given element was built.
1070     #  The returned geometrical object, if not nil, is either found in the
1071     #  study or published by this method with the given name
1072     #  @param theElementID the id of the mesh element
1073     #  @param theGeomName the user-defined name of the geometrical object
1074     #  @return GEOM::GEOM_Object instance
1075     #  @ingroup l2_construct
1076     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1077         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1078
1079     ## Returns the mesh dimension depending on the dimension of the underlying shape
1080     #  @return mesh dimension as an integer value [0,3]
1081     #  @ingroup l1_auxiliary
1082     def MeshDimension(self):
1083         shells = self.geompyD.SubShapeAllIDs( self.geom, geompyDC.ShapeType["SHELL"] )
1084         if len( shells ) > 0 :
1085             return 3
1086         elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1087             return 2
1088         elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1089             return 1
1090         else:
1091             return 0;
1092         pass
1093
1094     ## Evaluates size of prospective mesh on a shape
1095     #  @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1096     #  To know predicted number of e.g. edges, inquire it this way
1097     #  Evaluate()[ EnumToLong( Entity_Edge )]
1098     def Evaluate(self, geom=0):
1099         if geom == 0 or not isinstance(geom, geompyDC.GEOM._objref_GEOM_Object):
1100             if self.geom == 0:
1101                 geom = self.mesh.GetShapeToMesh()
1102             else:
1103                 geom = self.geom
1104         return self.smeshpyD.Evaluate(self.mesh, geom)
1105
1106
1107     ## Computes the mesh and returns the status of the computation
1108     #  @param geom geomtrical shape on which mesh data should be computed
1109     #  @param discardModifs if True and the mesh has been edited since
1110     #         a last total re-compute and that may prevent successful partial re-compute,
1111     #         then the mesh is cleaned before Compute()
1112     #  @return True or False
1113     #  @ingroup l2_construct
1114     def Compute(self, geom=0, discardModifs=False):
1115         if geom == 0 or not isinstance(geom, geompyDC.GEOM._objref_GEOM_Object):
1116             if self.geom == 0:
1117                 geom = self.mesh.GetShapeToMesh()
1118             else:
1119                 geom = self.geom
1120         ok = False
1121         try:
1122             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1123                 self.mesh.Clear()
1124             ok = self.smeshpyD.Compute(self.mesh, geom)
1125         except SALOME.SALOME_Exception, ex:
1126             print "Mesh computation failed, exception caught:"
1127             print "    ", ex.details.text
1128         except:
1129             import traceback
1130             print "Mesh computation failed, exception caught:"
1131             traceback.print_exc()
1132         if True:#not ok:
1133             allReasons = ""
1134
1135             # Treat compute errors
1136             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1137             for err in computeErrors:
1138                 shapeText = ""
1139                 if self.mesh.HasShapeToMesh():
1140                     try:
1141                         mainIOR  = salome.orb.object_to_string(geom)
1142                         for sname in salome.myStudyManager.GetOpenStudies():
1143                             s = salome.myStudyManager.GetStudyByName(sname)
1144                             if not s: continue
1145                             mainSO = s.FindObjectIOR(mainIOR)
1146                             if not mainSO: continue
1147                             if err.subShapeID == 1:
1148                                 shapeText = ' on "%s"' % mainSO.GetName()
1149                             subIt = s.NewChildIterator(mainSO)
1150                             while subIt.More():
1151                                 subSO = subIt.Value()
1152                                 subIt.Next()
1153                                 obj = subSO.GetObject()
1154                                 if not obj: continue
1155                                 go = obj._narrow( geompyDC.GEOM._objref_GEOM_Object )
1156                                 if not go: continue
1157                                 ids = go.GetSubShapeIndices()
1158                                 if len(ids) == 1 and ids[0] == err.subShapeID:
1159                                     shapeText = ' on "%s"' % subSO.GetName()
1160                                     break
1161                         if not shapeText:
1162                             shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1163                             if shape:
1164                                 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1165                             else:
1166                                 shapeText = " on subshape #%s" % (err.subShapeID)
1167                     except:
1168                         shapeText = " on subshape #%s" % (err.subShapeID)
1169                 errText = ""
1170                 stdErrors = ["OK",                 #COMPERR_OK
1171                              "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1172                              "std::exception",     #COMPERR_STD_EXCEPTION
1173                              "OCC exception",      #COMPERR_OCC_EXCEPTION
1174                              "SALOME exception",   #COMPERR_SLM_EXCEPTION
1175                              "Unknown exception",  #COMPERR_EXCEPTION
1176                              "Memory allocation problem", #COMPERR_MEMORY_PB
1177                              "Algorithm failed",   #COMPERR_ALGO_FAILED
1178                              "Unexpected geometry"]#COMPERR_BAD_SHAPE
1179                 if err.code > 0:
1180                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1181                 else:
1182                     errText = "code %s" % -err.code
1183                 if errText: errText += ". "
1184                 errText += err.comment
1185                 if allReasons != "":allReasons += "\n"
1186                 allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1187                 pass
1188
1189             # Treat hyp errors
1190             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1191             for err in errors:
1192                 if err.isGlobalAlgo:
1193                     glob = "global"
1194                 else:
1195                     glob = "local"
1196                     pass
1197                 dim = err.algoDim
1198                 name = err.algoName
1199                 if len(name) == 0:
1200                     reason = '%s %sD algorithm is missing' % (glob, dim)
1201                 elif err.state == HYP_MISSING:
1202                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1203                               % (glob, dim, name, dim))
1204                 elif err.state == HYP_NOTCONFORM:
1205                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1206                 elif err.state == HYP_BAD_PARAMETER:
1207                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1208                               % ( glob, dim, name ))
1209                 elif err.state == HYP_BAD_GEOMETRY:
1210                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1211                               'geometry' % ( glob, dim, name ))
1212                 else:
1213                     reason = "For unknown reason."+\
1214                              " Revise Mesh.Compute() implementation in smeshDC.py!"
1215                     pass
1216                 if allReasons != "":allReasons += "\n"
1217                 allReasons += "-  " + reason
1218                 pass
1219             if not ok or allReasons != "":
1220                 msg = '"' + GetName(self.mesh) + '"'
1221                 if ok: msg += " has been computed with warnings"
1222                 else:  msg += " has not been computed"
1223                 if allReasons != "": msg += ":"
1224                 else:                msg += "."
1225                 print msg
1226                 print allReasons
1227             pass
1228         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1229             smeshgui = salome.ImportComponentGUI("SMESH")
1230             smeshgui.Init(self.mesh.GetStudyId())
1231             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1232             salome.sg.updateObjBrowser(1)
1233             pass
1234         return ok
1235
1236     ## Return submesh objects list in meshing order
1237     #  @return list of list of submesh objects
1238     #  @ingroup l2_construct
1239     def GetMeshOrder(self):
1240         return self.mesh.GetMeshOrder()
1241
1242     ## Return submesh objects list in meshing order
1243     #  @return list of list of submesh objects
1244     #  @ingroup l2_construct
1245     def SetMeshOrder(self, submeshes):
1246         return self.mesh.SetMeshOrder(submeshes)
1247
1248     ## Removes all nodes and elements
1249     #  @ingroup l2_construct
1250     def Clear(self):
1251         self.mesh.Clear()
1252         if salome.sg.hasDesktop():
1253             smeshgui = salome.ImportComponentGUI("SMESH")
1254             smeshgui.Init(self.mesh.GetStudyId())
1255             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1256             salome.sg.updateObjBrowser(1)
1257
1258     ## Removes all nodes and elements of indicated shape
1259     #  @ingroup l2_construct
1260     def ClearSubMesh(self, geomId):
1261         self.mesh.ClearSubMesh(geomId)
1262         if salome.sg.hasDesktop():
1263             smeshgui = salome.ImportComponentGUI("SMESH")
1264             smeshgui.Init(self.mesh.GetStudyId())
1265             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1266             salome.sg.updateObjBrowser(1)
1267
1268     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1269     #  @param fineness [0.0,1.0] defines mesh fineness
1270     #  @return True or False
1271     #  @ingroup l3_algos_basic
1272     def AutomaticTetrahedralization(self, fineness=0):
1273         dim = self.MeshDimension()
1274         # assign hypotheses
1275         self.RemoveGlobalHypotheses()
1276         self.Segment().AutomaticLength(fineness)
1277         if dim > 1 :
1278             self.Triangle().LengthFromEdges()
1279             pass
1280         if dim > 2 :
1281             from NETGENPluginDC import NETGEN
1282             self.Tetrahedron(NETGEN)
1283             pass
1284         return self.Compute()
1285
1286     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1287     #  @param fineness [0.0, 1.0] defines mesh fineness
1288     #  @return True or False
1289     #  @ingroup l3_algos_basic
1290     def AutomaticHexahedralization(self, fineness=0):
1291         dim = self.MeshDimension()
1292         # assign the hypotheses
1293         self.RemoveGlobalHypotheses()
1294         self.Segment().AutomaticLength(fineness)
1295         if dim > 1 :
1296             self.Quadrangle()
1297             pass
1298         if dim > 2 :
1299             self.Hexahedron()
1300             pass
1301         return self.Compute()
1302
1303     ## Assigns a hypothesis
1304     #  @param hyp a hypothesis to assign
1305     #  @param geom a subhape of mesh geometry
1306     #  @return SMESH.Hypothesis_Status
1307     #  @ingroup l2_hypotheses
1308     def AddHypothesis(self, hyp, geom=0):
1309         if isinstance( hyp, Mesh_Algorithm ):
1310             hyp = hyp.GetAlgorithm()
1311             pass
1312         if not geom:
1313             geom = self.geom
1314             if not geom:
1315                 geom = self.mesh.GetShapeToMesh()
1316             pass
1317         AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1318         status = self.mesh.AddHypothesis(geom, hyp)
1319         isAlgo = hyp._narrow( SMESH_Algo )
1320         hyp_name = GetName( hyp )
1321         geom_name = ""
1322         if geom:
1323             geom_name = GetName( geom )
1324         TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1325         return status
1326
1327     ## Return True if an algorithm of hypothesis is assigned to a given shape
1328     #  @param hyp a hypothesis to check
1329     #  @param geom a subhape of mesh geometry
1330     #  @return True of False
1331     #  @ingroup l2_hypotheses
1332     def IsUsedHypothesis(self, hyp, geom):
1333         if not hyp or not geom:
1334             return False
1335         if isinstance( hyp, Mesh_Algorithm ):
1336             hyp = hyp.GetAlgorithm()
1337             pass
1338         hyps = self.GetHypothesisList(geom)
1339         for h in hyps:
1340             if h.GetId() == hyp.GetId():
1341                 return True
1342         return False
1343
1344     ## Unassigns a hypothesis
1345     #  @param hyp a hypothesis to unassign
1346     #  @param geom a sub-shape of mesh geometry
1347     #  @return SMESH.Hypothesis_Status
1348     #  @ingroup l2_hypotheses
1349     def RemoveHypothesis(self, hyp, geom=0):
1350         if isinstance( hyp, Mesh_Algorithm ):
1351             hyp = hyp.GetAlgorithm()
1352             pass
1353         if not geom:
1354             geom = self.geom
1355             pass
1356         status = self.mesh.RemoveHypothesis(geom, hyp)
1357         return status
1358
1359     ## Gets the list of hypotheses added on a geometry
1360     #  @param geom a sub-shape of mesh geometry
1361     #  @return the sequence of SMESH_Hypothesis
1362     #  @ingroup l2_hypotheses
1363     def GetHypothesisList(self, geom):
1364         return self.mesh.GetHypothesisList( geom )
1365
1366     ## Removes all global hypotheses
1367     #  @ingroup l2_hypotheses
1368     def RemoveGlobalHypotheses(self):
1369         current_hyps = self.mesh.GetHypothesisList( self.geom )
1370         for hyp in current_hyps:
1371             self.mesh.RemoveHypothesis( self.geom, hyp )
1372             pass
1373         pass
1374
1375    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1376     ## allowing to overwrite the file if it exists or add the exported data to its contents
1377     #  @param f is the file name
1378     #  @param auto_groups boolean parameter for creating/not creating
1379     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1380     #  the typical use is auto_groups=false.
1381     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1382     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1383     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1384     #  @ingroup l2_impexp
1385     def ExportMED(self, f, auto_groups=0, version=MED_V2_2, overwrite=1, meshPart=None):
1386         if meshPart:
1387             if isinstance( meshPart, list ):
1388                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1389             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite )
1390         else:
1391             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite)
1392
1393     ## Exports the mesh in a file in SAUV format
1394     #  @param f is the file name
1395     #  @param auto_groups boolean parameter for creating/not creating
1396     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1397     #  the typical use is auto_groups=false.
1398     #  @ingroup l2_impexp
1399     def ExportSAUV(self, f, auto_groups=0):
1400         self.mesh.ExportSAUV(f, auto_groups)
1401
1402     ## Exports the mesh in a file in DAT format
1403     #  @param f the file name
1404     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1405     #  @ingroup l2_impexp
1406     def ExportDAT(self, f, meshPart=None):
1407         if meshPart:
1408             if isinstance( meshPart, list ):
1409                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1410             self.mesh.ExportPartToDAT( meshPart, f )
1411         else:
1412             self.mesh.ExportDAT(f)
1413
1414     ## Exports the mesh in a file in UNV format
1415     #  @param f the file name
1416     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1417     #  @ingroup l2_impexp
1418     def ExportUNV(self, f, meshPart=None):
1419         if meshPart:
1420             if isinstance( meshPart, list ):
1421                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1422             self.mesh.ExportPartToUNV( meshPart, f )
1423         else:
1424             self.mesh.ExportUNV(f)
1425
1426     ## Export the mesh in a file in STL format
1427     #  @param f the file name
1428     #  @param ascii defines the file encoding
1429     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1430     #  @ingroup l2_impexp
1431     def ExportSTL(self, f, ascii=1, meshPart=None):
1432         if meshPart:
1433             if isinstance( meshPart, list ):
1434                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1435             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1436         else:
1437             self.mesh.ExportSTL(f, ascii)
1438
1439     ## Exports the mesh in a file in CGNS format
1440     #  @param f is the file name
1441     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1442     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1443     #  @ingroup l2_impexp
1444     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1445         if isinstance( meshPart, list ):
1446             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1447         if isinstance( meshPart, Mesh ):
1448             meshPart = meshPart.mesh
1449         elif not meshPart:
1450             meshPart = self.mesh
1451         self.mesh.ExportCGNS(meshPart, f, overwrite)
1452
1453     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1454     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1455     ## allowing to overwrite the file if it exists or add the exported data to its contents
1456     #  @param f the file name
1457     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1458     #  @param opt boolean parameter for creating/not creating
1459     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1460     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1461     #  @ingroup l2_impexp
1462     def ExportToMED(self, f, version, opt=0, overwrite=1):
1463         self.mesh.ExportToMEDX(f, opt, version, overwrite)
1464
1465     # Operations with groups:
1466     # ----------------------
1467
1468     ## Creates an empty mesh group
1469     #  @param elementType the type of elements in the group
1470     #  @param name the name of the mesh group
1471     #  @return SMESH_Group
1472     #  @ingroup l2_grps_create
1473     def CreateEmptyGroup(self, elementType, name):
1474         return self.mesh.CreateGroup(elementType, name)
1475
1476     ## Creates a mesh group based on the geometric object \a grp
1477     #  and gives a \a name, \n if this parameter is not defined
1478     #  the name is the same as the geometric group name \n
1479     #  Note: Works like GroupOnGeom().
1480     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1481     #  @param name the name of the mesh group
1482     #  @return SMESH_GroupOnGeom
1483     #  @ingroup l2_grps_create
1484     def Group(self, grp, name=""):
1485         return self.GroupOnGeom(grp, name)
1486
1487     ## Creates a mesh group based on the geometrical object \a grp
1488     #  and gives a \a name, \n if this parameter is not defined
1489     #  the name is the same as the geometrical group name
1490     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1491     #  @param name the name of the mesh group
1492     #  @param typ  the type of elements in the group. If not set, it is
1493     #              automatically detected by the type of the geometry
1494     #  @return SMESH_GroupOnGeom
1495     #  @ingroup l2_grps_create
1496     def GroupOnGeom(self, grp, name="", typ=None):
1497         AssureGeomPublished( self, grp, name )
1498         if name == "":
1499             name = grp.GetName()
1500         if not typ:
1501             typ = self._groupTypeFromShape( grp )
1502         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1503
1504     ## Pivate method to get a type of group on geometry
1505     def _groupTypeFromShape( self, shape ):
1506         tgeo = str(shape.GetShapeType())
1507         if tgeo == "VERTEX":
1508             typ = NODE
1509         elif tgeo == "EDGE":
1510             typ = EDGE
1511         elif tgeo == "FACE" or tgeo == "SHELL":
1512             typ = FACE
1513         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1514             typ = VOLUME
1515         elif tgeo == "COMPOUND":
1516             sub = self.geompyD.SubShapeAll( shape, geompyDC.ShapeType["SHAPE"])
1517             if not sub:
1518                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1519             return self._groupTypeFromShape( sub[0] )
1520         else:
1521             raise ValueError, \
1522                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1523         return typ
1524
1525     ## Creates a mesh group with given \a name based on the \a filter which
1526     ## is a special type of group dynamically updating it's contents during
1527     ## mesh modification
1528     #  @param typ  the type of elements in the group
1529     #  @param name the name of the mesh group
1530     #  @param filter the filter defining group contents
1531     #  @return SMESH_GroupOnFilter
1532     #  @ingroup l2_grps_create
1533     def GroupOnFilter(self, typ, name, filter):
1534         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1535
1536     ## Creates a mesh group by the given ids of elements
1537     #  @param groupName the name of the mesh group
1538     #  @param elementType the type of elements in the group
1539     #  @param elemIDs the list of ids
1540     #  @return SMESH_Group
1541     #  @ingroup l2_grps_create
1542     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1543         group = self.mesh.CreateGroup(elementType, groupName)
1544         group.Add(elemIDs)
1545         return group
1546
1547     ## Creates a mesh group by the given conditions
1548     #  @param groupName the name of the mesh group
1549     #  @param elementType the type of elements in the group
1550     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1551     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1552     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
1553     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
1554     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1555     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
1556     #  @return SMESH_Group
1557     #  @ingroup l2_grps_create
1558     def MakeGroup(self,
1559                   groupName,
1560                   elementType,
1561                   CritType=FT_Undefined,
1562                   Compare=FT_EqualTo,
1563                   Threshold="",
1564                   UnaryOp=FT_Undefined,
1565                   Tolerance=1e-07):
1566         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1567         group = self.MakeGroupByCriterion(groupName, aCriterion)
1568         return group
1569
1570     ## Creates a mesh group by the given criterion
1571     #  @param groupName the name of the mesh group
1572     #  @param Criterion the instance of Criterion class
1573     #  @return SMESH_Group
1574     #  @ingroup l2_grps_create
1575     def MakeGroupByCriterion(self, groupName, Criterion):
1576         aFilterMgr = self.smeshpyD.CreateFilterManager()
1577         aFilter = aFilterMgr.CreateFilter()
1578         aCriteria = []
1579         aCriteria.append(Criterion)
1580         aFilter.SetCriteria(aCriteria)
1581         group = self.MakeGroupByFilter(groupName, aFilter)
1582         aFilterMgr.UnRegister()
1583         return group
1584
1585     ## Creates a mesh group by the given criteria (list of criteria)
1586     #  @param groupName the name of the mesh group
1587     #  @param theCriteria the list of criteria
1588     #  @return SMESH_Group
1589     #  @ingroup l2_grps_create
1590     def MakeGroupByCriteria(self, groupName, theCriteria):
1591         aFilterMgr = self.smeshpyD.CreateFilterManager()
1592         aFilter = aFilterMgr.CreateFilter()
1593         aFilter.SetCriteria(theCriteria)
1594         group = self.MakeGroupByFilter(groupName, aFilter)
1595         aFilterMgr.UnRegister()
1596         return group
1597
1598     ## Creates a mesh group by the given filter
1599     #  @param groupName the name of the mesh group
1600     #  @param theFilter the instance of Filter class
1601     #  @return SMESH_Group
1602     #  @ingroup l2_grps_create
1603     def MakeGroupByFilter(self, groupName, theFilter):
1604         group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1605         theFilter.SetMesh( self.mesh )
1606         group.AddFrom( theFilter )
1607         return group
1608
1609     ## Removes a group
1610     #  @ingroup l2_grps_delete
1611     def RemoveGroup(self, group):
1612         self.mesh.RemoveGroup(group)
1613
1614     ## Removes a group with its contents
1615     #  @ingroup l2_grps_delete
1616     def RemoveGroupWithContents(self, group):
1617         self.mesh.RemoveGroupWithContents(group)
1618
1619     ## Gets the list of groups existing in the mesh
1620     #  @return a sequence of SMESH_GroupBase
1621     #  @ingroup l2_grps_create
1622     def GetGroups(self):
1623         return self.mesh.GetGroups()
1624
1625     ## Gets the number of groups existing in the mesh
1626     #  @return the quantity of groups as an integer value
1627     #  @ingroup l2_grps_create
1628     def NbGroups(self):
1629         return self.mesh.NbGroups()
1630
1631     ## Gets the list of names of groups existing in the mesh
1632     #  @return list of strings
1633     #  @ingroup l2_grps_create
1634     def GetGroupNames(self):
1635         groups = self.GetGroups()
1636         names = []
1637         for group in groups:
1638             names.append(group.GetName())
1639         return names
1640
1641     ## Produces a union of two groups
1642     #  A new group is created. All mesh elements that are
1643     #  present in the initial groups are added to the new one
1644     #  @return an instance of SMESH_Group
1645     #  @ingroup l2_grps_operon
1646     def UnionGroups(self, group1, group2, name):
1647         return self.mesh.UnionGroups(group1, group2, name)
1648
1649     ## Produces a union list of groups
1650     #  New group is created. All mesh elements that are present in
1651     #  initial groups are added to the new one
1652     #  @return an instance of SMESH_Group
1653     #  @ingroup l2_grps_operon
1654     def UnionListOfGroups(self, groups, name):
1655       return self.mesh.UnionListOfGroups(groups, name)
1656
1657     ## Prodices an intersection of two groups
1658     #  A new group is created. All mesh elements that are common
1659     #  for the two initial groups are added to the new one.
1660     #  @return an instance of SMESH_Group
1661     #  @ingroup l2_grps_operon
1662     def IntersectGroups(self, group1, group2, name):
1663         return self.mesh.IntersectGroups(group1, group2, name)
1664
1665     ## Produces an intersection of groups
1666     #  New group is created. All mesh elements that are present in all
1667     #  initial groups simultaneously are added to the new one
1668     #  @return an instance of SMESH_Group
1669     #  @ingroup l2_grps_operon
1670     def IntersectListOfGroups(self, groups, name):
1671       return self.mesh.IntersectListOfGroups(groups, name)
1672
1673     ## Produces a cut of two groups
1674     #  A new group is created. All mesh elements that are present in
1675     #  the main group but are not present in the tool group are added to the new one
1676     #  @return an instance of SMESH_Group
1677     #  @ingroup l2_grps_operon
1678     def CutGroups(self, main_group, tool_group, name):
1679         return self.mesh.CutGroups(main_group, tool_group, name)
1680
1681     ## Produces a cut of groups
1682     #  A new group is created. All mesh elements that are present in main groups
1683     #  but do not present in tool groups are added to the new one
1684     #  @return an instance of SMESH_Group
1685     #  @ingroup l2_grps_operon
1686     def CutListOfGroups(self, main_groups, tool_groups, name):
1687       return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1688
1689     ## Produces a group of elements of specified type using list of existing groups
1690     #  A new group is created. System
1691     #  1) extracts all nodes on which groups elements are built
1692     #  2) combines all elements of specified dimension laying on these nodes
1693     #  @return an instance of SMESH_Group
1694     #  @ingroup l2_grps_operon
1695     def CreateDimGroup(self, groups, elem_type, name):
1696       return self.mesh.CreateDimGroup(groups, elem_type, name)
1697
1698
1699     ## Convert group on geom into standalone group
1700     #  @ingroup l2_grps_delete
1701     def ConvertToStandalone(self, group):
1702         return self.mesh.ConvertToStandalone(group)
1703
1704     # Get some info about mesh:
1705     # ------------------------
1706
1707     ## Returns the log of nodes and elements added or removed
1708     #  since the previous clear of the log.
1709     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
1710     #  @return list of log_block structures:
1711     #                                        commandType
1712     #                                        number
1713     #                                        coords
1714     #                                        indexes
1715     #  @ingroup l1_auxiliary
1716     def GetLog(self, clearAfterGet):
1717         return self.mesh.GetLog(clearAfterGet)
1718
1719     ## Clears the log of nodes and elements added or removed since the previous
1720     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
1721     #  @ingroup l1_auxiliary
1722     def ClearLog(self):
1723         self.mesh.ClearLog()
1724
1725     ## Toggles auto color mode on the object.
1726     #  @param theAutoColor the flag which toggles auto color mode.
1727     #  @ingroup l1_auxiliary
1728     def SetAutoColor(self, theAutoColor):
1729         self.mesh.SetAutoColor(theAutoColor)
1730
1731     ## Gets flag of object auto color mode.
1732     #  @return True or False
1733     #  @ingroup l1_auxiliary
1734     def GetAutoColor(self):
1735         return self.mesh.GetAutoColor()
1736
1737     ## Gets the internal ID
1738     #  @return integer value, which is the internal Id of the mesh
1739     #  @ingroup l1_auxiliary
1740     def GetId(self):
1741         return self.mesh.GetId()
1742
1743     ## Get the study Id
1744     #  @return integer value, which is the study Id of the mesh
1745     #  @ingroup l1_auxiliary
1746     def GetStudyId(self):
1747         return self.mesh.GetStudyId()
1748
1749     ## Checks the group names for duplications.
1750     #  Consider the maximum group name length stored in MED file.
1751     #  @return True or False
1752     #  @ingroup l1_auxiliary
1753     def HasDuplicatedGroupNamesMED(self):
1754         return self.mesh.HasDuplicatedGroupNamesMED()
1755
1756     ## Obtains the mesh editor tool
1757     #  @return an instance of SMESH_MeshEditor
1758     #  @ingroup l1_modifying
1759     def GetMeshEditor(self):
1760         return self.mesh.GetMeshEditor()
1761
1762     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
1763     #  can be passed as argument to a method accepting mesh, group or sub-mesh
1764     #  @return an instance of SMESH_IDSource
1765     #  @ingroup l1_auxiliary
1766     def GetIDSource(self, ids, elemType):
1767         return self.GetMeshEditor().MakeIDSource(ids, elemType)
1768
1769     ## Gets MED Mesh
1770     #  @return an instance of SALOME_MED::MESH
1771     #  @ingroup l1_auxiliary
1772     def GetMEDMesh(self):
1773         return self.mesh.GetMEDMesh()
1774
1775
1776     # Get informations about mesh contents:
1777     # ------------------------------------
1778
1779     ## Gets the mesh stattistic
1780     #  @return dictionary type element - count of elements
1781     #  @ingroup l1_meshinfo
1782     def GetMeshInfo(self, obj = None):
1783         if not obj: obj = self.mesh
1784         return self.smeshpyD.GetMeshInfo(obj)
1785
1786     ## Returns the number of nodes in the mesh
1787     #  @return an integer value
1788     #  @ingroup l1_meshinfo
1789     def NbNodes(self):
1790         return self.mesh.NbNodes()
1791
1792     ## Returns the number of elements in the mesh
1793     #  @return an integer value
1794     #  @ingroup l1_meshinfo
1795     def NbElements(self):
1796         return self.mesh.NbElements()
1797
1798     ## Returns the number of 0d elements in the mesh
1799     #  @return an integer value
1800     #  @ingroup l1_meshinfo
1801     def Nb0DElements(self):
1802         return self.mesh.Nb0DElements()
1803
1804     ## Returns the number of ball discrete elements in the mesh
1805     #  @return an integer value
1806     #  @ingroup l1_meshinfo
1807     def NbBalls(self):
1808         return self.mesh.NbBalls()
1809
1810     ## Returns the number of edges in the mesh
1811     #  @return an integer value
1812     #  @ingroup l1_meshinfo
1813     def NbEdges(self):
1814         return self.mesh.NbEdges()
1815
1816     ## Returns the number of edges with the given order in the mesh
1817     #  @param elementOrder the order of elements:
1818     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1819     #  @return an integer value
1820     #  @ingroup l1_meshinfo
1821     def NbEdgesOfOrder(self, elementOrder):
1822         return self.mesh.NbEdgesOfOrder(elementOrder)
1823
1824     ## Returns the number of faces in the mesh
1825     #  @return an integer value
1826     #  @ingroup l1_meshinfo
1827     def NbFaces(self):
1828         return self.mesh.NbFaces()
1829
1830     ## Returns the number of faces with the given order in the mesh
1831     #  @param elementOrder the order of elements:
1832     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1833     #  @return an integer value
1834     #  @ingroup l1_meshinfo
1835     def NbFacesOfOrder(self, elementOrder):
1836         return self.mesh.NbFacesOfOrder(elementOrder)
1837
1838     ## Returns the number of triangles in the mesh
1839     #  @return an integer value
1840     #  @ingroup l1_meshinfo
1841     def NbTriangles(self):
1842         return self.mesh.NbTriangles()
1843
1844     ## Returns the number of triangles with the given order in the mesh
1845     #  @param elementOrder is the order of elements:
1846     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1847     #  @return an integer value
1848     #  @ingroup l1_meshinfo
1849     def NbTrianglesOfOrder(self, elementOrder):
1850         return self.mesh.NbTrianglesOfOrder(elementOrder)
1851
1852     ## Returns the number of quadrangles in the mesh
1853     #  @return an integer value
1854     #  @ingroup l1_meshinfo
1855     def NbQuadrangles(self):
1856         return self.mesh.NbQuadrangles()
1857
1858     ## Returns the number of quadrangles with the given order in the mesh
1859     #  @param elementOrder the order of elements:
1860     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1861     #  @return an integer value
1862     #  @ingroup l1_meshinfo
1863     def NbQuadranglesOfOrder(self, elementOrder):
1864         return self.mesh.NbQuadranglesOfOrder(elementOrder)
1865
1866     ## Returns the number of biquadratic quadrangles in the mesh
1867     #  @return an integer value
1868     #  @ingroup l1_meshinfo
1869     def NbBiQuadQuadrangles(self):
1870         return self.mesh.NbBiQuadQuadrangles()
1871
1872     ## Returns the number of polygons in the mesh
1873     #  @return an integer value
1874     #  @ingroup l1_meshinfo
1875     def NbPolygons(self):
1876         return self.mesh.NbPolygons()
1877
1878     ## Returns the number of volumes in the mesh
1879     #  @return an integer value
1880     #  @ingroup l1_meshinfo
1881     def NbVolumes(self):
1882         return self.mesh.NbVolumes()
1883
1884     ## Returns the number of volumes with the given order in the mesh
1885     #  @param elementOrder  the order of elements:
1886     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1887     #  @return an integer value
1888     #  @ingroup l1_meshinfo
1889     def NbVolumesOfOrder(self, elementOrder):
1890         return self.mesh.NbVolumesOfOrder(elementOrder)
1891
1892     ## Returns the number of tetrahedrons in the mesh
1893     #  @return an integer value
1894     #  @ingroup l1_meshinfo
1895     def NbTetras(self):
1896         return self.mesh.NbTetras()
1897
1898     ## Returns the number of tetrahedrons with the given order in the mesh
1899     #  @param elementOrder  the order of elements:
1900     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1901     #  @return an integer value
1902     #  @ingroup l1_meshinfo
1903     def NbTetrasOfOrder(self, elementOrder):
1904         return self.mesh.NbTetrasOfOrder(elementOrder)
1905
1906     ## Returns the number of hexahedrons in the mesh
1907     #  @return an integer value
1908     #  @ingroup l1_meshinfo
1909     def NbHexas(self):
1910         return self.mesh.NbHexas()
1911
1912     ## Returns the number of hexahedrons with the given order in the mesh
1913     #  @param elementOrder  the order of elements:
1914     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1915     #  @return an integer value
1916     #  @ingroup l1_meshinfo
1917     def NbHexasOfOrder(self, elementOrder):
1918         return self.mesh.NbHexasOfOrder(elementOrder)
1919
1920     ## Returns the number of triquadratic hexahedrons in the mesh
1921     #  @return an integer value
1922     #  @ingroup l1_meshinfo
1923     def NbTriQuadraticHexas(self):
1924         return self.mesh.NbTriQuadraticHexas()
1925
1926     ## Returns the number of pyramids in the mesh
1927     #  @return an integer value
1928     #  @ingroup l1_meshinfo
1929     def NbPyramids(self):
1930         return self.mesh.NbPyramids()
1931
1932     ## Returns the number of pyramids with the given order in the mesh
1933     #  @param elementOrder  the order of elements:
1934     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1935     #  @return an integer value
1936     #  @ingroup l1_meshinfo
1937     def NbPyramidsOfOrder(self, elementOrder):
1938         return self.mesh.NbPyramidsOfOrder(elementOrder)
1939
1940     ## Returns the number of prisms in the mesh
1941     #  @return an integer value
1942     #  @ingroup l1_meshinfo
1943     def NbPrisms(self):
1944         return self.mesh.NbPrisms()
1945
1946     ## Returns the number of prisms with the given order in the mesh
1947     #  @param elementOrder  the order of elements:
1948     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1949     #  @return an integer value
1950     #  @ingroup l1_meshinfo
1951     def NbPrismsOfOrder(self, elementOrder):
1952         return self.mesh.NbPrismsOfOrder(elementOrder)
1953
1954     ## Returns the number of hexagonal prisms in the mesh
1955     #  @return an integer value
1956     #  @ingroup l1_meshinfo
1957     def NbHexagonalPrisms(self):
1958         return self.mesh.NbHexagonalPrisms()
1959
1960     ## Returns the number of polyhedrons in the mesh
1961     #  @return an integer value
1962     #  @ingroup l1_meshinfo
1963     def NbPolyhedrons(self):
1964         return self.mesh.NbPolyhedrons()
1965
1966     ## Returns the number of submeshes in the mesh
1967     #  @return an integer value
1968     #  @ingroup l1_meshinfo
1969     def NbSubMesh(self):
1970         return self.mesh.NbSubMesh()
1971
1972     ## Returns the list of mesh elements IDs
1973     #  @return the list of integer values
1974     #  @ingroup l1_meshinfo
1975     def GetElementsId(self):
1976         return self.mesh.GetElementsId()
1977
1978     ## Returns the list of IDs of mesh elements with the given type
1979     #  @param elementType  the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
1980     #  @return list of integer values
1981     #  @ingroup l1_meshinfo
1982     def GetElementsByType(self, elementType):
1983         return self.mesh.GetElementsByType(elementType)
1984
1985     ## Returns the list of mesh nodes IDs
1986     #  @return the list of integer values
1987     #  @ingroup l1_meshinfo
1988     def GetNodesId(self):
1989         return self.mesh.GetNodesId()
1990
1991     # Get the information about mesh elements:
1992     # ------------------------------------
1993
1994     ## Returns the type of mesh element
1995     #  @return the value from SMESH::ElementType enumeration
1996     #  @ingroup l1_meshinfo
1997     def GetElementType(self, id, iselem):
1998         return self.mesh.GetElementType(id, iselem)
1999
2000     ## Returns the geometric type of mesh element
2001     #  @return the value from SMESH::EntityType enumeration
2002     #  @ingroup l1_meshinfo
2003     def GetElementGeomType(self, id):
2004         return self.mesh.GetElementGeomType(id)
2005
2006     ## Returns the list of submesh elements IDs
2007     #  @param Shape a geom object(sub-shape) IOR
2008     #         Shape must be the sub-shape of a ShapeToMesh()
2009     #  @return the list of integer values
2010     #  @ingroup l1_meshinfo
2011     def GetSubMeshElementsId(self, Shape):
2012         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
2013             ShapeID = Shape.GetSubShapeIndices()[0]
2014         else:
2015             ShapeID = Shape
2016         return self.mesh.GetSubMeshElementsId(ShapeID)
2017
2018     ## Returns the list of submesh nodes IDs
2019     #  @param Shape a geom object(sub-shape) IOR
2020     #         Shape must be the sub-shape of a ShapeToMesh()
2021     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2022     #  @return the list of integer values
2023     #  @ingroup l1_meshinfo
2024     def GetSubMeshNodesId(self, Shape, all):
2025         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
2026             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2027         else:
2028             ShapeID = Shape
2029         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2030
2031     ## Returns type of elements on given shape
2032     #  @param Shape a geom object(sub-shape) IOR
2033     #         Shape must be a sub-shape of a ShapeToMesh()
2034     #  @return element type
2035     #  @ingroup l1_meshinfo
2036     def GetSubMeshElementType(self, Shape):
2037         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
2038             ShapeID = Shape.GetSubShapeIndices()[0]
2039         else:
2040             ShapeID = Shape
2041         return self.mesh.GetSubMeshElementType(ShapeID)
2042
2043     ## Gets the mesh description
2044     #  @return string value
2045     #  @ingroup l1_meshinfo
2046     def Dump(self):
2047         return self.mesh.Dump()
2048
2049
2050     # Get the information about nodes and elements of a mesh by its IDs:
2051     # -----------------------------------------------------------
2052
2053     ## Gets XYZ coordinates of a node
2054     #  \n If there is no nodes for the given ID - returns an empty list
2055     #  @return a list of double precision values
2056     #  @ingroup l1_meshinfo
2057     def GetNodeXYZ(self, id):
2058         return self.mesh.GetNodeXYZ(id)
2059
2060     ## Returns list of IDs of inverse elements for the given node
2061     #  \n If there is no node for the given ID - returns an empty list
2062     #  @return a list of integer values
2063     #  @ingroup l1_meshinfo
2064     def GetNodeInverseElements(self, id):
2065         return self.mesh.GetNodeInverseElements(id)
2066
2067     ## @brief Returns the position of a node on the shape
2068     #  @return SMESH::NodePosition
2069     #  @ingroup l1_meshinfo
2070     def GetNodePosition(self,NodeID):
2071         return self.mesh.GetNodePosition(NodeID)
2072
2073     ## If the given element is a node, returns the ID of shape
2074     #  \n If there is no node for the given ID - returns -1
2075     #  @return an integer value
2076     #  @ingroup l1_meshinfo
2077     def GetShapeID(self, id):
2078         return self.mesh.GetShapeID(id)
2079
2080     ## Returns the ID of the result shape after
2081     #  FindShape() from SMESH_MeshEditor for the given element
2082     #  \n If there is no element for the given ID - returns -1
2083     #  @return an integer value
2084     #  @ingroup l1_meshinfo
2085     def GetShapeIDForElem(self,id):
2086         return self.mesh.GetShapeIDForElem(id)
2087
2088     ## Returns the number of nodes for the given element
2089     #  \n If there is no element for the given ID - returns -1
2090     #  @return an integer value
2091     #  @ingroup l1_meshinfo
2092     def GetElemNbNodes(self, id):
2093         return self.mesh.GetElemNbNodes(id)
2094
2095     ## Returns the node ID the given index for the given element
2096     #  \n If there is no element for the given ID - returns -1
2097     #  \n If there is no node for the given index - returns -2
2098     #  @return an integer value
2099     #  @ingroup l1_meshinfo
2100     def GetElemNode(self, id, index):
2101         return self.mesh.GetElemNode(id, index)
2102
2103     ## Returns the IDs of nodes of the given element
2104     #  @return a list of integer values
2105     #  @ingroup l1_meshinfo
2106     def GetElemNodes(self, id):
2107         return self.mesh.GetElemNodes(id)
2108
2109     ## Returns true if the given node is the medium node in the given quadratic element
2110     #  @ingroup l1_meshinfo
2111     def IsMediumNode(self, elementID, nodeID):
2112         return self.mesh.IsMediumNode(elementID, nodeID)
2113
2114     ## Returns true if the given node is the medium node in one of quadratic elements
2115     #  @ingroup l1_meshinfo
2116     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2117         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2118
2119     ## Returns the number of edges for the given element
2120     #  @ingroup l1_meshinfo
2121     def ElemNbEdges(self, id):
2122         return self.mesh.ElemNbEdges(id)
2123
2124     ## Returns the number of faces for the given element
2125     #  @ingroup l1_meshinfo
2126     def ElemNbFaces(self, id):
2127         return self.mesh.ElemNbFaces(id)
2128
2129     ## Returns nodes of given face (counted from zero) for given volumic element.
2130     #  @ingroup l1_meshinfo
2131     def GetElemFaceNodes(self,elemId, faceIndex):
2132         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2133
2134     ## Returns an element based on all given nodes.
2135     #  @ingroup l1_meshinfo
2136     def FindElementByNodes(self,nodes):
2137         return self.mesh.FindElementByNodes(nodes)
2138
2139     ## Returns true if the given element is a polygon
2140     #  @ingroup l1_meshinfo
2141     def IsPoly(self, id):
2142         return self.mesh.IsPoly(id)
2143
2144     ## Returns true if the given element is quadratic
2145     #  @ingroup l1_meshinfo
2146     def IsQuadratic(self, id):
2147         return self.mesh.IsQuadratic(id)
2148
2149     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2150     #  @ingroup l1_meshinfo
2151     def GetBallDiameter(self, id):
2152         return self.mesh.GetBallDiameter(id)
2153
2154     ## Returns XYZ coordinates of the barycenter of the given element
2155     #  \n If there is no element for the given ID - returns an empty list
2156     #  @return a list of three double values
2157     #  @ingroup l1_meshinfo
2158     def BaryCenter(self, id):
2159         return self.mesh.BaryCenter(id)
2160
2161     ## Passes mesh elements through the given filter and return IDs of fitting elements
2162     #  @param theFilter SMESH_Filter
2163     #  @return a list of ids
2164     #  @ingroup l1_controls
2165     def GetIdsFromFilter(self, theFilter):
2166         theFilter.SetMesh( self.mesh )
2167         return theFilter.GetIDs()
2168
2169     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2170     #  Returns a list of special structures (borders).
2171     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2172     #  @ingroup l1_controls
2173     def GetFreeBorders(self):
2174         aFilterMgr = self.smeshpyD.CreateFilterManager()
2175         aPredicate = aFilterMgr.CreateFreeEdges()
2176         aPredicate.SetMesh(self.mesh)
2177         aBorders = aPredicate.GetBorders()
2178         aFilterMgr.UnRegister()
2179         return aBorders
2180
2181
2182     # Get mesh measurements information:
2183     # ------------------------------------
2184
2185     ## Get minimum distance between two nodes, elements or distance to the origin
2186     #  @param id1 first node/element id
2187     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2188     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2189     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2190     #  @return minimum distance value
2191     #  @sa GetMinDistance()
2192     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2193         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2194         return aMeasure.value
2195
2196     ## Get measure structure specifying minimum distance data between two objects
2197     #  @param id1 first node/element id
2198     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2199     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2200     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2201     #  @return Measure structure
2202     #  @sa MinDistance()
2203     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2204         if isElem1:
2205             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2206         else:
2207             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2208         if id2 != 0:
2209             if isElem2:
2210                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2211             else:
2212                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2213             pass
2214         else:
2215             id2 = None
2216
2217         aMeasurements = self.smeshpyD.CreateMeasurements()
2218         aMeasure = aMeasurements.MinDistance(id1, id2)
2219         aMeasurements.UnRegister()
2220         return aMeasure
2221
2222     ## Get bounding box of the specified object(s)
2223     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2224     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2225     #  @c False specifies that @a objects are nodes
2226     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2227     #  @sa GetBoundingBox()
2228     def BoundingBox(self, objects=None, isElem=False):
2229         result = self.GetBoundingBox(objects, isElem)
2230         if result is None:
2231             result = (0.0,)*6
2232         else:
2233             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2234         return result
2235
2236     ## Get measure structure specifying bounding box data of the specified object(s)
2237     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2238     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2239     #  @c False specifies that @a objects are nodes
2240     #  @return Measure structure
2241     #  @sa BoundingBox()
2242     def GetBoundingBox(self, IDs=None, isElem=False):
2243         if IDs is None:
2244             IDs = [self.mesh]
2245         elif isinstance(IDs, tuple):
2246             IDs = list(IDs)
2247         if not isinstance(IDs, list):
2248             IDs = [IDs]
2249         if len(IDs) > 0 and isinstance(IDs[0], int):
2250             IDs = [IDs]
2251         srclist = []
2252         for o in IDs:
2253             if isinstance(o, Mesh):
2254                 srclist.append(o.mesh)
2255             elif hasattr(o, "_narrow"):
2256                 src = o._narrow(SMESH.SMESH_IDSource)
2257                 if src: srclist.append(src)
2258                 pass
2259             elif isinstance(o, list):
2260                 if isElem:
2261                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2262                 else:
2263                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2264                 pass
2265             pass
2266         aMeasurements = self.smeshpyD.CreateMeasurements()
2267         aMeasure = aMeasurements.BoundingBox(srclist)
2268         aMeasurements.UnRegister()
2269         return aMeasure
2270
2271     # Mesh edition (SMESH_MeshEditor functionality):
2272     # ---------------------------------------------
2273
2274     ## Removes the elements from the mesh by ids
2275     #  @param IDsOfElements is a list of ids of elements to remove
2276     #  @return True or False
2277     #  @ingroup l2_modif_del
2278     def RemoveElements(self, IDsOfElements):
2279         return self.editor.RemoveElements(IDsOfElements)
2280
2281     ## Removes nodes from mesh by ids
2282     #  @param IDsOfNodes is a list of ids of nodes to remove
2283     #  @return True or False
2284     #  @ingroup l2_modif_del
2285     def RemoveNodes(self, IDsOfNodes):
2286         return self.editor.RemoveNodes(IDsOfNodes)
2287
2288     ## Removes all orphan (free) nodes from mesh
2289     #  @return number of the removed nodes
2290     #  @ingroup l2_modif_del
2291     def RemoveOrphanNodes(self):
2292         return self.editor.RemoveOrphanNodes()
2293
2294     ## Add a node to the mesh by coordinates
2295     #  @return Id of the new node
2296     #  @ingroup l2_modif_add
2297     def AddNode(self, x, y, z):
2298         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2299         if hasVars: self.mesh.SetParameters(Parameters)
2300         return self.editor.AddNode( x, y, z)
2301
2302     ## Creates a 0D element on a node with given number.
2303     #  @param IDOfNode the ID of node for creation of the element.
2304     #  @return the Id of the new 0D element
2305     #  @ingroup l2_modif_add
2306     def Add0DElement(self, IDOfNode):
2307         return self.editor.Add0DElement(IDOfNode)
2308
2309     ## Creates a ball element on a node with given ID.
2310     #  @param IDOfNode the ID of node for creation of the element.
2311     #  @param diameter the bal diameter.
2312     #  @return the Id of the new ball element
2313     #  @ingroup l2_modif_add
2314     def AddBall(self, IDOfNode, diameter):
2315         return self.editor.AddBall( IDOfNode, diameter )
2316
2317     ## Creates a linear or quadratic edge (this is determined
2318     #  by the number of given nodes).
2319     #  @param IDsOfNodes the list of node IDs for creation of the element.
2320     #  The order of nodes in this list should correspond to the description
2321     #  of MED. \n This description is located by the following link:
2322     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2323     #  @return the Id of the new edge
2324     #  @ingroup l2_modif_add
2325     def AddEdge(self, IDsOfNodes):
2326         return self.editor.AddEdge(IDsOfNodes)
2327
2328     ## Creates a linear or quadratic face (this is determined
2329     #  by the number of given nodes).
2330     #  @param IDsOfNodes the list of node IDs for creation of the element.
2331     #  The order of nodes in this list should correspond to the description
2332     #  of MED. \n This description is located by the following link:
2333     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2334     #  @return the Id of the new face
2335     #  @ingroup l2_modif_add
2336     def AddFace(self, IDsOfNodes):
2337         return self.editor.AddFace(IDsOfNodes)
2338
2339     ## Adds a polygonal face to the mesh by the list of node IDs
2340     #  @param IdsOfNodes the list of node IDs for creation of the element.
2341     #  @return the Id of the new face
2342     #  @ingroup l2_modif_add
2343     def AddPolygonalFace(self, IdsOfNodes):
2344         return self.editor.AddPolygonalFace(IdsOfNodes)
2345
2346     ## Creates both simple and quadratic volume (this is determined
2347     #  by the number of given nodes).
2348     #  @param IDsOfNodes the list of node IDs for creation of the element.
2349     #  The order of nodes in this list should correspond to the description
2350     #  of MED. \n This description is located by the following link:
2351     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2352     #  @return the Id of the new volumic element
2353     #  @ingroup l2_modif_add
2354     def AddVolume(self, IDsOfNodes):
2355         return self.editor.AddVolume(IDsOfNodes)
2356
2357     ## Creates a volume of many faces, giving nodes for each face.
2358     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2359     #  @param Quantities the list of integer values, Quantities[i]
2360     #         gives the quantity of nodes in face number i.
2361     #  @return the Id of the new volumic element
2362     #  @ingroup l2_modif_add
2363     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2364         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2365
2366     ## Creates a volume of many faces, giving the IDs of the existing faces.
2367     #  @param IdsOfFaces the list of face IDs for volume creation.
2368     #
2369     #  Note:  The created volume will refer only to the nodes
2370     #         of the given faces, not to the faces themselves.
2371     #  @return the Id of the new volumic element
2372     #  @ingroup l2_modif_add
2373     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2374         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2375
2376
2377     ## @brief Binds a node to a vertex
2378     #  @param NodeID a node ID
2379     #  @param Vertex a vertex or vertex ID
2380     #  @return True if succeed else raises an exception
2381     #  @ingroup l2_modif_add
2382     def SetNodeOnVertex(self, NodeID, Vertex):
2383         if ( isinstance( Vertex, geompyDC.GEOM._objref_GEOM_Object)):
2384             VertexID = Vertex.GetSubShapeIndices()[0]
2385         else:
2386             VertexID = Vertex
2387         try:
2388             self.editor.SetNodeOnVertex(NodeID, VertexID)
2389         except SALOME.SALOME_Exception, inst:
2390             raise ValueError, inst.details.text
2391         return True
2392
2393
2394     ## @brief Stores the node position on an edge
2395     #  @param NodeID a node ID
2396     #  @param Edge an edge or edge ID
2397     #  @param paramOnEdge a parameter on the edge where the node is located
2398     #  @return True if succeed else raises an exception
2399     #  @ingroup l2_modif_add
2400     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2401         if ( isinstance( Edge, geompyDC.GEOM._objref_GEOM_Object)):
2402             EdgeID = Edge.GetSubShapeIndices()[0]
2403         else:
2404             EdgeID = Edge
2405         try:
2406             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2407         except SALOME.SALOME_Exception, inst:
2408             raise ValueError, inst.details.text
2409         return True
2410
2411     ## @brief Stores node position on a face
2412     #  @param NodeID a node ID
2413     #  @param Face a face or face ID
2414     #  @param u U parameter on the face where the node is located
2415     #  @param v V parameter on the face where the node is located
2416     #  @return True if succeed else raises an exception
2417     #  @ingroup l2_modif_add
2418     def SetNodeOnFace(self, NodeID, Face, u, v):
2419         if ( isinstance( Face, geompyDC.GEOM._objref_GEOM_Object)):
2420             FaceID = Face.GetSubShapeIndices()[0]
2421         else:
2422             FaceID = Face
2423         try:
2424             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2425         except SALOME.SALOME_Exception, inst:
2426             raise ValueError, inst.details.text
2427         return True
2428
2429     ## @brief Binds a node to a solid
2430     #  @param NodeID a node ID
2431     #  @param Solid  a solid or solid ID
2432     #  @return True if succeed else raises an exception
2433     #  @ingroup l2_modif_add
2434     def SetNodeInVolume(self, NodeID, Solid):
2435         if ( isinstance( Solid, geompyDC.GEOM._objref_GEOM_Object)):
2436             SolidID = Solid.GetSubShapeIndices()[0]
2437         else:
2438             SolidID = Solid
2439         try:
2440             self.editor.SetNodeInVolume(NodeID, SolidID)
2441         except SALOME.SALOME_Exception, inst:
2442             raise ValueError, inst.details.text
2443         return True
2444
2445     ## @brief Bind an element to a shape
2446     #  @param ElementID an element ID
2447     #  @param Shape a shape or shape ID
2448     #  @return True if succeed else raises an exception
2449     #  @ingroup l2_modif_add
2450     def SetMeshElementOnShape(self, ElementID, Shape):
2451         if ( isinstance( Shape, geompyDC.GEOM._objref_GEOM_Object)):
2452             ShapeID = Shape.GetSubShapeIndices()[0]
2453         else:
2454             ShapeID = Shape
2455         try:
2456             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2457         except SALOME.SALOME_Exception, inst:
2458             raise ValueError, inst.details.text
2459         return True
2460
2461
2462     ## Moves the node with the given id
2463     #  @param NodeID the id of the node
2464     #  @param x  a new X coordinate
2465     #  @param y  a new Y coordinate
2466     #  @param z  a new Z coordinate
2467     #  @return True if succeed else False
2468     #  @ingroup l2_modif_movenode
2469     def MoveNode(self, NodeID, x, y, z):
2470         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2471         if hasVars: self.mesh.SetParameters(Parameters)
2472         return self.editor.MoveNode(NodeID, x, y, z)
2473
2474     ## Finds the node closest to a point and moves it to a point location
2475     #  @param x  the X coordinate of a point
2476     #  @param y  the Y coordinate of a point
2477     #  @param z  the Z coordinate of a point
2478     #  @param NodeID if specified (>0), the node with this ID is moved,
2479     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
2480     #  @return the ID of a node
2481     #  @ingroup l2_modif_throughp
2482     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2483         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2484         if hasVars: self.mesh.SetParameters(Parameters)
2485         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2486
2487     ## Finds the node closest to a point
2488     #  @param x  the X coordinate of a point
2489     #  @param y  the Y coordinate of a point
2490     #  @param z  the Z coordinate of a point
2491     #  @return the ID of a node
2492     #  @ingroup l2_modif_throughp
2493     def FindNodeClosestTo(self, x, y, z):
2494         #preview = self.mesh.GetMeshEditPreviewer()
2495         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2496         return self.editor.FindNodeClosestTo(x, y, z)
2497
2498     ## Finds the elements where a point lays IN or ON
2499     #  @param x  the X coordinate of a point
2500     #  @param y  the Y coordinate of a point
2501     #  @param z  the Z coordinate of a point
2502     #  @param elementType type of elements to find (SMESH.ALL type
2503     #         means elements of any type excluding nodes, discrete and 0D elements)
2504     #  @param meshPart a part of mesh (group, sub-mesh) to search within
2505     #  @return list of IDs of found elements
2506     #  @ingroup l2_modif_throughp
2507     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2508         if meshPart:
2509             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2510         else:
2511             return self.editor.FindElementsByPoint(x, y, z, elementType)
2512
2513     # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2514     # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2515     # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2516
2517     def GetPointState(self, x, y, z):
2518         return self.editor.GetPointState(x, y, z)
2519
2520     ## Finds the node closest to a point and moves it to a point location
2521     #  @param x  the X coordinate of a point
2522     #  @param y  the Y coordinate of a point
2523     #  @param z  the Z coordinate of a point
2524     #  @return the ID of a moved node
2525     #  @ingroup l2_modif_throughp
2526     def MeshToPassThroughAPoint(self, x, y, z):
2527         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2528
2529     ## Replaces two neighbour triangles sharing Node1-Node2 link
2530     #  with the triangles built on the same 4 nodes but having other common link.
2531     #  @param NodeID1  the ID of the first node
2532     #  @param NodeID2  the ID of the second node
2533     #  @return false if proper faces were not found
2534     #  @ingroup l2_modif_invdiag
2535     def InverseDiag(self, NodeID1, NodeID2):
2536         return self.editor.InverseDiag(NodeID1, NodeID2)
2537
2538     ## Replaces two neighbour triangles sharing Node1-Node2 link
2539     #  with a quadrangle built on the same 4 nodes.
2540     #  @param NodeID1  the ID of the first node
2541     #  @param NodeID2  the ID of the second node
2542     #  @return false if proper faces were not found
2543     #  @ingroup l2_modif_unitetri
2544     def DeleteDiag(self, NodeID1, NodeID2):
2545         return self.editor.DeleteDiag(NodeID1, NodeID2)
2546
2547     ## Reorients elements by ids
2548     #  @param IDsOfElements if undefined reorients all mesh elements
2549     #  @return True if succeed else False
2550     #  @ingroup l2_modif_changori
2551     def Reorient(self, IDsOfElements=None):
2552         if IDsOfElements == None:
2553             IDsOfElements = self.GetElementsId()
2554         return self.editor.Reorient(IDsOfElements)
2555
2556     ## Reorients all elements of the object
2557     #  @param theObject mesh, submesh or group
2558     #  @return True if succeed else False
2559     #  @ingroup l2_modif_changori
2560     def ReorientObject(self, theObject):
2561         if ( isinstance( theObject, Mesh )):
2562             theObject = theObject.GetMesh()
2563         return self.editor.ReorientObject(theObject)
2564
2565     ## Reorient faces contained in \a the2DObject.
2566     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2567     #  @param theDirection is a desired direction of normal of \a theFace.
2568     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
2569     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2570     #         compared with theDirection. It can be either ID of face or a point
2571     #         by which the face will be found. The point can be given as either
2572     #         a GEOM vertex or a list of point coordinates.
2573     #  @return number of reoriented faces
2574     #  @ingroup l2_modif_changori
2575     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2576         # check the2DObject
2577         if isinstance( the2DObject, Mesh ):
2578             the2DObject = the2DObject.GetMesh()
2579         if isinstance( the2DObject, list ):
2580             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2581         # check theDirection
2582         if isinstance( theDirection, geompyDC.GEOM._objref_GEOM_Object):
2583             theDirection = self.smeshpyD.GetDirStruct( theDirection )
2584         if isinstance( theDirection, list ):
2585             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
2586         # prepare theFace and thePoint
2587         theFace = theFaceOrPoint
2588         thePoint = PointStruct(0,0,0)
2589         if isinstance( theFaceOrPoint, geompyDC.GEOM._objref_GEOM_Object):
2590             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2591             theFace = -1
2592         if isinstance( theFaceOrPoint, list ):
2593             thePoint = PointStruct( *theFaceOrPoint )
2594             theFace = -1
2595         if isinstance( theFaceOrPoint, PointStruct ):
2596             thePoint = theFaceOrPoint
2597             theFace = -1
2598         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2599
2600     ## Fuses the neighbouring triangles into quadrangles.
2601     #  @param IDsOfElements The triangles to be fused,
2602     #  @param theCriterion  is FT_...; used to choose a neighbour to fuse with.
2603     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
2604     #                       is still performed; theMaxAngle is mesured in radians.
2605     #                       Also it could be a name of variable which defines angle in degrees.
2606     #  @return TRUE in case of success, FALSE otherwise.
2607     #  @ingroup l2_modif_unitetri
2608     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2609         flag = False
2610         if isinstance(MaxAngle,str):
2611             flag = True
2612         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2613         self.mesh.SetParameters(Parameters)
2614         if not IDsOfElements:
2615             IDsOfElements = self.GetElementsId()
2616         Functor = 0
2617         if ( isinstance( theCriterion, SMESH._objref_NumericalFunctor ) ):
2618             Functor = theCriterion
2619         else:
2620             Functor = self.smeshpyD.GetFunctor(theCriterion)
2621         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2622
2623     ## Fuses the neighbouring triangles of the object into quadrangles
2624     #  @param theObject is mesh, submesh or group
2625     #  @param theCriterion is FT_...; used to choose a neighbour to fuse with.
2626     #  @param MaxAngle   a max angle between element normals at which the fusion
2627     #                   is still performed; theMaxAngle is mesured in radians.
2628     #  @return TRUE in case of success, FALSE otherwise.
2629     #  @ingroup l2_modif_unitetri
2630     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2631         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2632         self.mesh.SetParameters(Parameters)
2633         if ( isinstance( theObject, Mesh )):
2634             theObject = theObject.GetMesh()
2635         return self.editor.TriToQuadObject(theObject, self.smeshpyD.GetFunctor(theCriterion), MaxAngle)
2636
2637     ## Splits quadrangles into triangles.
2638     #  @param IDsOfElements the faces to be splitted.
2639     #  @param theCriterion   FT_...; used to choose a diagonal for splitting.
2640     #  @return TRUE in case of success, FALSE otherwise.
2641     #  @ingroup l2_modif_cutquadr
2642     def QuadToTri (self, IDsOfElements, theCriterion):
2643         if IDsOfElements == []:
2644             IDsOfElements = self.GetElementsId()
2645         return self.editor.QuadToTri(IDsOfElements, self.smeshpyD.GetFunctor(theCriterion))
2646
2647     ## Splits quadrangles into triangles.
2648     #  @param theObject  the object from which the list of elements is taken, this is mesh, submesh or group
2649     #  @param theCriterion   FT_...; used to choose a diagonal for splitting.
2650     #  @return TRUE in case of success, FALSE otherwise.
2651     #  @ingroup l2_modif_cutquadr
2652     def QuadToTriObject (self, theObject, theCriterion):
2653         if ( isinstance( theObject, Mesh )):
2654             theObject = theObject.GetMesh()
2655         return self.editor.QuadToTriObject(theObject, self.smeshpyD.GetFunctor(theCriterion))
2656
2657     ## Splits quadrangles into triangles.
2658     #  @param IDsOfElements the faces to be splitted
2659     #  @param Diag13        is used to choose a diagonal for splitting.
2660     #  @return TRUE in case of success, FALSE otherwise.
2661     #  @ingroup l2_modif_cutquadr
2662     def SplitQuad (self, IDsOfElements, Diag13):
2663         if IDsOfElements == []:
2664             IDsOfElements = self.GetElementsId()
2665         return self.editor.SplitQuad(IDsOfElements, Diag13)
2666
2667     ## Splits quadrangles into triangles.
2668     #  @param theObject the object from which the list of elements is taken, this is mesh, submesh or group
2669     #  @param Diag13    is used to choose a diagonal for splitting.
2670     #  @return TRUE in case of success, FALSE otherwise.
2671     #  @ingroup l2_modif_cutquadr
2672     def SplitQuadObject (self, theObject, Diag13):
2673         if ( isinstance( theObject, Mesh )):
2674             theObject = theObject.GetMesh()
2675         return self.editor.SplitQuadObject(theObject, Diag13)
2676
2677     ## Finds a better splitting of the given quadrangle.
2678     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
2679     #  @param theCriterion  FT_...; a criterion to choose a diagonal for splitting.
2680     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
2681     #          diagonal is better, 0 if error occurs.
2682     #  @ingroup l2_modif_cutquadr
2683     def BestSplit (self, IDOfQuad, theCriterion):
2684         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
2685
2686     ## Splits volumic elements into tetrahedrons
2687     #  @param elemIDs either list of elements or mesh or group or submesh
2688     #  @param method  flags passing splitting method: Hex_5Tet, Hex_6Tet, Hex_24Tet
2689     #         Hex_5Tet - split the hexahedron into 5 tetrahedrons, etc
2690     #  @ingroup l2_modif_cutquadr
2691     def SplitVolumesIntoTetra(self, elemIDs, method=Hex_5Tet ):
2692         if isinstance( elemIDs, Mesh ):
2693             elemIDs = elemIDs.GetMesh()
2694         if ( isinstance( elemIDs, list )):
2695             elemIDs = self.editor.MakeIDSource(elemIDs, SMESH.VOLUME)
2696         self.editor.SplitVolumesIntoTetra(elemIDs, method)
2697
2698     ## Splits quadrangle faces near triangular facets of volumes
2699     #
2700     #  @ingroup l1_auxiliary
2701     def SplitQuadsNearTriangularFacets(self):
2702         faces_array = self.GetElementsByType(SMESH.FACE)
2703         for face_id in faces_array:
2704             if self.GetElemNbNodes(face_id) == 4: # quadrangle
2705                 quad_nodes = self.mesh.GetElemNodes(face_id)
2706                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2707                 isVolumeFound = False
2708                 for node1_elem in node1_elems:
2709                     if not isVolumeFound:
2710                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2711                             nb_nodes = self.GetElemNbNodes(node1_elem)
2712                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
2713                                 volume_elem = node1_elem
2714                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
2715                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
2716                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
2717                                         isVolumeFound = True
2718                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
2719                                             self.SplitQuad([face_id], False) # diagonal 2-4
2720                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
2721                                         isVolumeFound = True
2722                                         self.SplitQuad([face_id], True) # diagonal 1-3
2723                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
2724                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
2725                                         isVolumeFound = True
2726                                         self.SplitQuad([face_id], True) # diagonal 1-3
2727
2728     ## @brief Splits hexahedrons into tetrahedrons.
2729     #
2730     #  This operation uses pattern mapping functionality for splitting.
2731     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
2732     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
2733     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
2734     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
2735     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
2736     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
2737     #  @return TRUE in case of success, FALSE otherwise.
2738     #  @ingroup l1_auxiliary
2739     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
2740         # Pattern:     5.---------.6
2741         #              /|#*      /|
2742         #             / | #*    / |
2743         #            /  |  # * /  |
2744         #           /   |   # /*  |
2745         # (0,0,1) 4.---------.7 * |
2746         #          |#*  |1   | # *|
2747         #          | # *.----|---#.2
2748         #          |  #/ *   |   /
2749         #          |  /#  *  |  /
2750         #          | /   # * | /
2751         #          |/      #*|/
2752         # (0,0,0) 0.---------.3
2753         pattern_tetra = "!!! Nb of points: \n 8 \n\
2754         !!! Points: \n\
2755         0 0 0  !- 0 \n\
2756         0 1 0  !- 1 \n\
2757         1 1 0  !- 2 \n\
2758         1 0 0  !- 3 \n\
2759         0 0 1  !- 4 \n\
2760         0 1 1  !- 5 \n\
2761         1 1 1  !- 6 \n\
2762         1 0 1  !- 7 \n\
2763         !!! Indices of points of 6 tetras: \n\
2764         0 3 4 1 \n\
2765         7 4 3 1 \n\
2766         4 7 5 1 \n\
2767         6 2 5 7 \n\
2768         1 5 2 7 \n\
2769         2 3 1 7 \n"
2770
2771         pattern = self.smeshpyD.GetPattern()
2772         isDone  = pattern.LoadFromFile(pattern_tetra)
2773         if not isDone:
2774             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2775             return isDone
2776
2777         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2778         isDone = pattern.MakeMesh(self.mesh, False, False)
2779         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2780
2781         # split quafrangle faces near triangular facets of volumes
2782         self.SplitQuadsNearTriangularFacets()
2783
2784         return isDone
2785
2786     ## @brief Split hexahedrons into prisms.
2787     #
2788     #  Uses the pattern mapping functionality for splitting.
2789     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
2790     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
2791     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
2792     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
2793     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
2794     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
2795     #  @return TRUE in case of success, FALSE otherwise.
2796     #  @ingroup l1_auxiliary
2797     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
2798         # Pattern:     5.---------.6
2799         #              /|#       /|
2800         #             / | #     / |
2801         #            /  |  #   /  |
2802         #           /   |   # /   |
2803         # (0,0,1) 4.---------.7   |
2804         #          |    |    |    |
2805         #          |   1.----|----.2
2806         #          |   / *   |   /
2807         #          |  /   *  |  /
2808         #          | /     * | /
2809         #          |/       *|/
2810         # (0,0,0) 0.---------.3
2811         pattern_prism = "!!! Nb of points: \n 8 \n\
2812         !!! Points: \n\
2813         0 0 0  !- 0 \n\
2814         0 1 0  !- 1 \n\
2815         1 1 0  !- 2 \n\
2816         1 0 0  !- 3 \n\
2817         0 0 1  !- 4 \n\
2818         0 1 1  !- 5 \n\
2819         1 1 1  !- 6 \n\
2820         1 0 1  !- 7 \n\
2821         !!! Indices of points of 2 prisms: \n\
2822         0 1 3 4 5 7 \n\
2823         2 3 1 6 7 5 \n"
2824
2825         pattern = self.smeshpyD.GetPattern()
2826         isDone  = pattern.LoadFromFile(pattern_prism)
2827         if not isDone:
2828             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2829             return isDone
2830
2831         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2832         isDone = pattern.MakeMesh(self.mesh, False, False)
2833         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2834
2835         # Splits quafrangle faces near triangular facets of volumes
2836         self.SplitQuadsNearTriangularFacets()
2837
2838         return isDone
2839
2840     ## Smoothes elements
2841     #  @param IDsOfElements the list if ids of elements to smooth
2842     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
2843     #  Note that nodes built on edges and boundary nodes are always fixed.
2844     #  @param MaxNbOfIterations the maximum number of iterations
2845     #  @param MaxAspectRatio varies in range [1.0, inf]
2846     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2847     #  @return TRUE in case of success, FALSE otherwise.
2848     #  @ingroup l2_modif_smooth
2849     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
2850                MaxNbOfIterations, MaxAspectRatio, Method):
2851         if IDsOfElements == []:
2852             IDsOfElements = self.GetElementsId()
2853         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
2854         self.mesh.SetParameters(Parameters)
2855         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
2856                                   MaxNbOfIterations, MaxAspectRatio, Method)
2857
2858     ## Smoothes elements which belong to the given object
2859     #  @param theObject the object to smooth
2860     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
2861     #  Note that nodes built on edges and boundary nodes are always fixed.
2862     #  @param MaxNbOfIterations the maximum number of iterations
2863     #  @param MaxAspectRatio varies in range [1.0, inf]
2864     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2865     #  @return TRUE in case of success, FALSE otherwise.
2866     #  @ingroup l2_modif_smooth
2867     def SmoothObject(self, theObject, IDsOfFixedNodes,
2868                      MaxNbOfIterations, MaxAspectRatio, Method):
2869         if ( isinstance( theObject, Mesh )):
2870             theObject = theObject.GetMesh()
2871         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
2872                                         MaxNbOfIterations, MaxAspectRatio, Method)
2873
2874     ## Parametrically smoothes the given elements
2875     #  @param IDsOfElements the list if ids of elements to smooth
2876     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
2877     #  Note that nodes built on edges and boundary nodes are always fixed.
2878     #  @param MaxNbOfIterations the maximum number of iterations
2879     #  @param MaxAspectRatio varies in range [1.0, inf]
2880     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2881     #  @return TRUE in case of success, FALSE otherwise.
2882     #  @ingroup l2_modif_smooth
2883     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
2884                          MaxNbOfIterations, MaxAspectRatio, Method):
2885         if IDsOfElements == []:
2886             IDsOfElements = self.GetElementsId()
2887         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
2888         self.mesh.SetParameters(Parameters)
2889         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2890                                             MaxNbOfIterations, MaxAspectRatio, Method)
2891
2892     ## Parametrically smoothes the elements which belong to the given object
2893     #  @param theObject the object to smooth
2894     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
2895     #  Note that nodes built on edges and boundary nodes are always fixed.
2896     #  @param MaxNbOfIterations the maximum number of iterations
2897     #  @param MaxAspectRatio varies in range [1.0, inf]
2898     #  @param Method Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2899     #  @return TRUE in case of success, FALSE otherwise.
2900     #  @ingroup l2_modif_smooth
2901     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
2902                                MaxNbOfIterations, MaxAspectRatio, Method):
2903         if ( isinstance( theObject, Mesh )):
2904             theObject = theObject.GetMesh()
2905         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
2906                                                   MaxNbOfIterations, MaxAspectRatio, Method)
2907
2908     ## Converts the mesh to quadratic, deletes old elements, replacing
2909     #  them with quadratic with the same id.
2910     #  @param theForce3d new node creation method:
2911     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
2912     #         1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
2913     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
2914     #  @ingroup l2_modif_tofromqu
2915     def ConvertToQuadratic(self, theForce3d, theSubMesh=None):
2916         if theSubMesh:
2917             self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
2918         else:
2919             self.editor.ConvertToQuadratic(theForce3d)
2920
2921     ## Converts the mesh from quadratic to ordinary,
2922     #  deletes old quadratic elements, \n replacing
2923     #  them with ordinary mesh elements with the same id.
2924     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
2925     #  @ingroup l2_modif_tofromqu
2926     def ConvertFromQuadratic(self, theSubMesh=None):
2927         if theSubMesh:
2928             self.editor.ConvertFromQuadraticObject(theSubMesh)
2929         else:
2930             return self.editor.ConvertFromQuadratic()
2931
2932     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
2933     #  @return TRUE if operation has been completed successfully, FALSE otherwise
2934     #  @ingroup l2_modif_edit
2935     def  Make2DMeshFrom3D(self):
2936         return self.editor. Make2DMeshFrom3D()
2937
2938     ## Creates missing boundary elements
2939     #  @param elements - elements whose boundary is to be checked:
2940     #                    mesh, group, sub-mesh or list of elements
2941     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
2942     #  @param dimension - defines type of boundary elements to create:
2943     #                     SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
2944     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
2945     #  @param groupName - a name of group to store created boundary elements in,
2946     #                     "" means not to create the group
2947     #  @param meshName - a name of new mesh to store created boundary elements in,
2948     #                     "" means not to create the new mesh
2949     #  @param toCopyElements - if true, the checked elements will be copied into
2950     #     the new mesh else only boundary elements will be copied into the new mesh
2951     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
2952     #     boundary elements will be copied into the new mesh
2953     #  @return tuple (mesh, group) where bondary elements were added to
2954     #  @ingroup l2_modif_edit
2955     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
2956                          toCopyElements=False, toCopyExistingBondary=False):
2957         if isinstance( elements, Mesh ):
2958             elements = elements.GetMesh()
2959         if ( isinstance( elements, list )):
2960             elemType = SMESH.ALL
2961             if elements: elemType = self.GetElementType( elements[0], iselem=True)
2962             elements = self.editor.MakeIDSource(elements, elemType)
2963         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
2964                                                    toCopyElements,toCopyExistingBondary)
2965         if mesh: mesh = self.smeshpyD.Mesh(mesh)
2966         return mesh, group
2967
2968     ##
2969     # @brief Creates missing boundary elements around either the whole mesh or 
2970     #    groups of 2D elements
2971     #  @param dimension - defines type of boundary elements to create
2972     #  @param groupName - a name of group to store all boundary elements in,
2973     #    "" means not to create the group
2974     #  @param meshName - a name of a new mesh, which is a copy of the initial 
2975     #    mesh + created boundary elements; "" means not to create the new mesh
2976     #  @param toCopyAll - if true, the whole initial mesh will be copied into
2977     #    the new mesh else only boundary elements will be copied into the new mesh
2978     #  @param groups - groups of 2D elements to make boundary around
2979     #  @retval tuple( long, mesh, groups )
2980     #                 long - number of added boundary elements
2981     #                 mesh - the mesh where elements were added to
2982     #                 group - the group of boundary elements or None
2983     #
2984     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
2985                              toCopyAll=False, groups=[]):
2986         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
2987                                                            toCopyAll,groups)
2988         if mesh: mesh = self.smeshpyD.Mesh(mesh)
2989         return nb, mesh, group
2990
2991     ## Renumber mesh nodes
2992     #  @ingroup l2_modif_renumber
2993     def RenumberNodes(self):
2994         self.editor.RenumberNodes()
2995
2996     ## Renumber mesh elements
2997     #  @ingroup l2_modif_renumber
2998     def RenumberElements(self):
2999         self.editor.RenumberElements()
3000
3001     ## Generates new elements by rotation of the elements around the axis
3002     #  @param IDsOfElements the list of ids of elements to sweep
3003     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3004     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3005     #  @param NbOfSteps the number of steps
3006     #  @param Tolerance tolerance
3007     #  @param MakeGroups forces the generation of new groups from existing ones
3008     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3009     #                    of all steps, else - size of each step
3010     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3011     #  @ingroup l2_modif_extrurev
3012     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3013                       MakeGroups=False, TotalAngle=False):
3014         if IDsOfElements == []:
3015             IDsOfElements = self.GetElementsId()
3016         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
3017             Axis = self.smeshpyD.GetAxisStruct(Axis)
3018         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3019         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3020         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3021         self.mesh.SetParameters(Parameters)
3022         if TotalAngle and NbOfSteps:
3023             AngleInRadians /= NbOfSteps
3024         if MakeGroups:
3025             return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3026                                                        AngleInRadians, NbOfSteps, Tolerance)
3027         self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3028         return []
3029
3030     ## Generates new elements by rotation of the elements of object around the axis
3031     #  @param theObject object which elements should be sweeped.
3032     #                   It can be a mesh, a sub mesh or a group.
3033     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3034     #  @param AngleInRadians the angle of Rotation
3035     #  @param NbOfSteps number of steps
3036     #  @param Tolerance tolerance
3037     #  @param MakeGroups forces the generation of new groups from existing ones
3038     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3039     #                    of all steps, else - size of each step
3040     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3041     #  @ingroup l2_modif_extrurev
3042     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3043                             MakeGroups=False, TotalAngle=False):
3044         if ( isinstance( theObject, Mesh )):
3045             theObject = theObject.GetMesh()
3046         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
3047             Axis = self.smeshpyD.GetAxisStruct(Axis)
3048         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3049         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3050         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3051         self.mesh.SetParameters(Parameters)
3052         if TotalAngle and NbOfSteps:
3053             AngleInRadians /= NbOfSteps
3054         if MakeGroups:
3055             return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3056                                                              NbOfSteps, Tolerance)
3057         self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3058         return []
3059
3060     ## Generates new elements by rotation of the elements of object around the axis
3061     #  @param theObject object which elements should be sweeped.
3062     #                   It can be a mesh, a sub mesh or a group.
3063     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3064     #  @param AngleInRadians the angle of Rotation
3065     #  @param NbOfSteps number of steps
3066     #  @param Tolerance tolerance
3067     #  @param MakeGroups forces the generation of new groups from existing ones
3068     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3069     #                    of all steps, else - size of each step
3070     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3071     #  @ingroup l2_modif_extrurev
3072     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3073                               MakeGroups=False, TotalAngle=False):
3074         if ( isinstance( theObject, Mesh )):
3075             theObject = theObject.GetMesh()
3076         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
3077             Axis = self.smeshpyD.GetAxisStruct(Axis)
3078         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3079         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3080         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3081         self.mesh.SetParameters(Parameters)
3082         if TotalAngle and NbOfSteps:
3083             AngleInRadians /= NbOfSteps
3084         if MakeGroups:
3085             return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3086                                                                NbOfSteps, Tolerance)
3087         self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3088         return []
3089
3090     ## Generates new elements by rotation of the elements of object around the axis
3091     #  @param theObject object which elements should be sweeped.
3092     #                   It can be a mesh, a sub mesh or a group.
3093     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3094     #  @param AngleInRadians the angle of Rotation
3095     #  @param NbOfSteps number of steps
3096     #  @param Tolerance tolerance
3097     #  @param MakeGroups forces the generation of new groups from existing ones
3098     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3099     #                    of all steps, else - size of each step
3100     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3101     #  @ingroup l2_modif_extrurev
3102     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3103                               MakeGroups=False, TotalAngle=False):
3104         if ( isinstance( theObject, Mesh )):
3105             theObject = theObject.GetMesh()
3106         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
3107             Axis = self.smeshpyD.GetAxisStruct(Axis)
3108         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3109         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3110         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3111         self.mesh.SetParameters(Parameters)
3112         if TotalAngle and NbOfSteps:
3113             AngleInRadians /= NbOfSteps
3114         if MakeGroups:
3115             return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3116                                                              NbOfSteps, Tolerance)
3117         self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3118         return []
3119
3120     ## Generates new elements by extrusion of the elements with given ids
3121     #  @param IDsOfElements the list of elements ids for extrusion
3122     #  @param StepVector vector or DirStruct, defining the direction and value of extrusion for one step (the total extrusion length will be NbOfSteps * ||StepVector||)
3123     #  @param NbOfSteps the number of steps
3124     #  @param MakeGroups forces the generation of new groups from existing ones
3125     #  @param IsNodes is True if elements with given ids are nodes
3126     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3127     #  @ingroup l2_modif_extrurev
3128     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3129         if IDsOfElements == []:
3130             IDsOfElements = self.GetElementsId()
3131         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
3132             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3133         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3134         Parameters = StepVector.PS.parameters + var_separator + Parameters
3135         self.mesh.SetParameters(Parameters)
3136         if MakeGroups:
3137             if(IsNodes):
3138                 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3139             else:
3140                 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3141         if(IsNodes):
3142             self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3143         else:
3144             self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3145         return []
3146
3147     ## Generates new elements by extrusion of the elements with given ids
3148     #  @param IDsOfElements is ids of elements
3149     #  @param StepVector vector, defining the direction and value of extrusion
3150     #  @param NbOfSteps the number of steps
3151     #  @param ExtrFlags sets flags for extrusion
3152     #  @param SewTolerance uses for comparing locations of nodes if flag
3153     #         EXTRUSION_FLAG_SEW is set
3154     #  @param MakeGroups forces the generation of new groups from existing ones
3155     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3156     #  @ingroup l2_modif_extrurev
3157     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3158                           ExtrFlags, SewTolerance, MakeGroups=False):
3159         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
3160             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3161         if MakeGroups:
3162             return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3163                                                            ExtrFlags, SewTolerance)
3164         self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3165                                       ExtrFlags, SewTolerance)
3166         return []
3167
3168     ## Generates new elements by extrusion of the elements which belong to the object
3169     #  @param theObject the object which elements should be processed.
3170     #                   It can be a mesh, a sub mesh or a group.
3171     #  @param StepVector vector, defining the direction and value of extrusion for one step (the total extrusion length will be NbOfSteps * ||StepVector||)
3172     #  @param NbOfSteps the number of steps
3173     #  @param MakeGroups forces the generation of new groups from existing ones
3174     #  @param  IsNodes is True if elements which belong to the object are nodes
3175     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3176     #  @ingroup l2_modif_extrurev
3177     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3178         if ( isinstance( theObject, Mesh )):
3179             theObject = theObject.GetMesh()
3180         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
3181             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3182         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3183         Parameters = StepVector.PS.parameters + var_separator + Parameters
3184         self.mesh.SetParameters(Parameters)
3185         if MakeGroups:
3186             if(IsNodes):
3187                 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3188             else:
3189                 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3190         if(IsNodes):
3191             self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3192         else:
3193             self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3194         return []
3195
3196     ## Generates new elements by extrusion of the elements which belong to the object
3197     #  @param theObject object which elements should be processed.
3198     #                   It can be a mesh, a sub mesh or a group.
3199     #  @param StepVector vector, defining the direction and value of extrusion for one step (the total extrusion length will be NbOfSteps * ||StepVector||)
3200     #  @param NbOfSteps the number of steps
3201     #  @param MakeGroups to generate new groups from existing ones
3202     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3203     #  @ingroup l2_modif_extrurev
3204     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3205         if ( isinstance( theObject, Mesh )):
3206             theObject = theObject.GetMesh()
3207         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
3208             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3209         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3210         Parameters = StepVector.PS.parameters + var_separator + Parameters
3211         self.mesh.SetParameters(Parameters)
3212         if MakeGroups:
3213             return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3214         self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3215         return []
3216
3217     ## Generates new elements by extrusion of the elements which belong to the object
3218     #  @param theObject object which elements should be processed.
3219     #                   It can be a mesh, a sub mesh or a group.
3220     #  @param StepVector vector, defining the direction and value of extrusion for one step (the total extrusion length will be NbOfSteps * ||StepVector||)
3221     #  @param NbOfSteps the number of steps
3222     #  @param MakeGroups forces the generation of new groups from existing ones
3223     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3224     #  @ingroup l2_modif_extrurev
3225     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3226         if ( isinstance( theObject, Mesh )):
3227             theObject = theObject.GetMesh()
3228         if ( isinstance( StepVector, geompyDC.GEOM._objref_GEOM_Object)):
3229             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3230         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3231         Parameters = StepVector.PS.parameters + var_separator + Parameters
3232         self.mesh.SetParameters(Parameters)
3233         if MakeGroups:
3234             return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3235         self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3236         return []
3237
3238
3239
3240     ## Generates new elements by extrusion of the given elements
3241     #  The path of extrusion must be a meshed edge.
3242     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3243     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3244     #  @param NodeStart the start node from Path. Defines the direction of extrusion
3245     #  @param HasAngles allows the shape to be rotated around the path
3246     #                   to get the resulting mesh in a helical fashion
3247     #  @param Angles list of angles in radians
3248     #  @param LinearVariation forces the computation of rotation angles as linear
3249     #                         variation of the given Angles along path steps
3250     #  @param HasRefPoint allows using the reference point
3251     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3252     #         The User can specify any point as the Reference Point.
3253     #  @param MakeGroups forces the generation of new groups from existing ones
3254     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
3255     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3256     #          only SMESH::Extrusion_Error otherwise
3257     #  @ingroup l2_modif_extrurev
3258     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3259                             HasAngles, Angles, LinearVariation,
3260                             HasRefPoint, RefPoint, MakeGroups, ElemType):
3261         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
3262             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3263             pass
3264         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3265         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3266         self.mesh.SetParameters(Parameters)
3267
3268         if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3269
3270         if isinstance(Base, list):
3271             IDsOfElements = []
3272             if Base == []: IDsOfElements = self.GetElementsId()
3273             else: IDsOfElements = Base
3274             return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3275                                                    HasAngles, Angles, LinearVariation,
3276                                                    HasRefPoint, RefPoint, MakeGroups, ElemType)
3277         else:
3278             if isinstance(Base, Mesh): Base = Base.GetMesh()
3279             if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3280                 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3281                                                           HasAngles, Angles, LinearVariation,
3282                                                           HasRefPoint, RefPoint, MakeGroups, ElemType)
3283             else:
3284                 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3285
3286
3287     ## Generates new elements by extrusion of the given elements
3288     #  The path of extrusion must be a meshed edge.
3289     #  @param IDsOfElements ids of elements
3290     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3291     #  @param PathShape shape(edge) defines the sub-mesh for the path
3292     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3293     #  @param HasAngles allows the shape to be rotated around the path
3294     #                   to get the resulting mesh in a helical fashion
3295     #  @param Angles list of angles in radians
3296     #  @param HasRefPoint allows using the reference point
3297     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3298     #         The User can specify any point as the Reference Point.
3299     #  @param MakeGroups forces the generation of new groups from existing ones
3300     #  @param LinearVariation forces the computation of rotation angles as linear
3301     #                         variation of the given Angles along path steps
3302     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3303     #          only SMESH::Extrusion_Error otherwise
3304     #  @ingroup l2_modif_extrurev
3305     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3306                            HasAngles, Angles, HasRefPoint, RefPoint,
3307                            MakeGroups=False, LinearVariation=False):
3308         if IDsOfElements == []:
3309             IDsOfElements = self.GetElementsId()
3310         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
3311             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3312             pass
3313         if ( isinstance( PathMesh, Mesh )):
3314             PathMesh = PathMesh.GetMesh()
3315         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3316         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3317         self.mesh.SetParameters(Parameters)
3318         if HasAngles and Angles and LinearVariation:
3319             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3320             pass
3321         if MakeGroups:
3322             return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3323                                                             PathShape, NodeStart, HasAngles,
3324                                                             Angles, HasRefPoint, RefPoint)
3325         return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3326                                               NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3327
3328     ## Generates new elements by extrusion of the elements which belong to the object
3329     #  The path of extrusion must be a meshed edge.
3330     #  @param theObject the object which elements should be processed.
3331     #                   It can be a mesh, a sub mesh or a group.
3332     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3333     #  @param PathShape shape(edge) defines the sub-mesh for the path
3334     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3335     #  @param HasAngles allows the shape to be rotated around the path
3336     #                   to get the resulting mesh in a helical fashion
3337     #  @param Angles list of angles
3338     #  @param HasRefPoint allows using the reference point
3339     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3340     #         The User can specify any point as the Reference Point.
3341     #  @param MakeGroups forces the generation of new groups from existing ones
3342     #  @param LinearVariation forces the computation of rotation angles as linear
3343     #                         variation of the given Angles along path steps
3344     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3345     #          only SMESH::Extrusion_Error otherwise
3346     #  @ingroup l2_modif_extrurev
3347     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3348                                  HasAngles, Angles, HasRefPoint, RefPoint,
3349                                  MakeGroups=False, LinearVariation=False):
3350         if ( isinstance( theObject, Mesh )):
3351             theObject = theObject.GetMesh()
3352         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
3353             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3354         if ( isinstance( PathMesh, Mesh )):
3355             PathMesh = PathMesh.GetMesh()
3356         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3357         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3358         self.mesh.SetParameters(Parameters)
3359         if HasAngles and Angles and LinearVariation:
3360             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3361             pass
3362         if MakeGroups:
3363             return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3364                                                                   PathShape, NodeStart, HasAngles,
3365                                                                   Angles, HasRefPoint, RefPoint)
3366         return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3367                                                     NodeStart, HasAngles, Angles, HasRefPoint,
3368                                                     RefPoint)
3369
3370     ## Generates new elements by extrusion of the elements which belong to the object
3371     #  The path of extrusion must be a meshed edge.
3372     #  @param theObject the object which elements should be processed.
3373     #                   It can be a mesh, a sub mesh or a group.
3374     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3375     #  @param PathShape shape(edge) defines the sub-mesh for the path
3376     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3377     #  @param HasAngles allows the shape to be rotated around the path
3378     #                   to get the resulting mesh in a helical fashion
3379     #  @param Angles list of angles
3380     #  @param HasRefPoint allows using the reference point
3381     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3382     #         The User can specify any point as the Reference Point.
3383     #  @param MakeGroups forces the generation of new groups from existing ones
3384     #  @param LinearVariation forces the computation of rotation angles as linear
3385     #                         variation of the given Angles along path steps
3386     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3387     #          only SMESH::Extrusion_Error otherwise
3388     #  @ingroup l2_modif_extrurev
3389     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3390                                    HasAngles, Angles, HasRefPoint, RefPoint,
3391                                    MakeGroups=False, LinearVariation=False):
3392         if ( isinstance( theObject, Mesh )):
3393             theObject = theObject.GetMesh()
3394         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
3395             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3396         if ( isinstance( PathMesh, Mesh )):
3397             PathMesh = PathMesh.GetMesh()
3398         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3399         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3400         self.mesh.SetParameters(Parameters)
3401         if HasAngles and Angles and LinearVariation:
3402             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3403             pass
3404         if MakeGroups:
3405             return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3406                                                                     PathShape, NodeStart, HasAngles,
3407                                                                     Angles, HasRefPoint, RefPoint)
3408         return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3409                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3410                                                       RefPoint)
3411
3412     ## Generates new elements by extrusion of the elements which belong to the object
3413     #  The path of extrusion must be a meshed edge.
3414     #  @param theObject the object which elements should be processed.
3415     #                   It can be a mesh, a sub mesh or a group.
3416     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3417     #  @param PathShape shape(edge) defines the sub-mesh for the path
3418     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3419     #  @param HasAngles allows the shape to be rotated around the path
3420     #                   to get the resulting mesh in a helical fashion
3421     #  @param Angles list of angles
3422     #  @param HasRefPoint allows using the reference point
3423     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3424     #         The User can specify any point as the Reference Point.
3425     #  @param MakeGroups forces the generation of new groups from existing ones
3426     #  @param LinearVariation forces the computation of rotation angles as linear
3427     #                         variation of the given Angles along path steps
3428     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3429     #          only SMESH::Extrusion_Error otherwise
3430     #  @ingroup l2_modif_extrurev
3431     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3432                                    HasAngles, Angles, HasRefPoint, RefPoint,
3433                                    MakeGroups=False, LinearVariation=False):
3434         if ( isinstance( theObject, Mesh )):
3435             theObject = theObject.GetMesh()
3436         if ( isinstance( RefPoint, geompyDC.GEOM._objref_GEOM_Object)):
3437             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3438         if ( isinstance( PathMesh, Mesh )):
3439             PathMesh = PathMesh.GetMesh()
3440         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3441         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3442         self.mesh.SetParameters(Parameters)
3443         if HasAngles and Angles and LinearVariation:
3444             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3445             pass
3446         if MakeGroups:
3447             return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3448                                                                     PathShape, NodeStart, HasAngles,
3449                                                                     Angles, HasRefPoint, RefPoint)
3450         return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3451                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3452                                                       RefPoint)
3453
3454     ## Creates a symmetrical copy of mesh elements
3455     #  @param IDsOfElements list of elements ids
3456     #  @param Mirror is AxisStruct or geom object(point, line, plane)
3457     #  @param theMirrorType is  POINT, AXIS or PLANE
3458     #  If the Mirror is a geom object this parameter is unnecessary
3459     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3460     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3461     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3462     #  @ingroup l2_modif_trsf
3463     def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3464         if IDsOfElements == []:
3465             IDsOfElements = self.GetElementsId()
3466         if ( isinstance( Mirror, geompyDC.GEOM._objref_GEOM_Object)):
3467             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3468         self.mesh.SetParameters(Mirror.parameters)
3469         if Copy and MakeGroups:
3470             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3471         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3472         return []
3473
3474     ## Creates a new mesh by a symmetrical copy of mesh elements
3475     #  @param IDsOfElements the list of elements ids
3476     #  @param Mirror is AxisStruct or geom object (point, line, plane)
3477     #  @param theMirrorType is  POINT, AXIS or PLANE
3478     #  If the Mirror is a geom object this parameter is unnecessary
3479     #  @param MakeGroups to generate new groups from existing ones
3480     #  @param NewMeshName a name of the new mesh to create
3481     #  @return instance of Mesh class
3482     #  @ingroup l2_modif_trsf
3483     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3484         if IDsOfElements == []:
3485             IDsOfElements = self.GetElementsId()
3486         if ( isinstance( Mirror, geompyDC.GEOM._objref_GEOM_Object)):
3487             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3488         self.mesh.SetParameters(Mirror.parameters)
3489         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3490                                           MakeGroups, NewMeshName)
3491         return Mesh(self.smeshpyD,self.geompyD,mesh)
3492
3493     ## Creates a symmetrical copy of the object
3494     #  @param theObject mesh, submesh or group
3495     #  @param Mirror AxisStruct or geom object (point, line, plane)
3496     #  @param theMirrorType is  POINT, AXIS or PLANE
3497     #  If the Mirror is a geom object this parameter is unnecessary
3498     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3499     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3500     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3501     #  @ingroup l2_modif_trsf
3502     def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3503         if ( isinstance( theObject, Mesh )):
3504             theObject = theObject.GetMesh()
3505         if ( isinstance( Mirror, geompyDC.GEOM._objref_GEOM_Object)):
3506             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3507         self.mesh.SetParameters(Mirror.parameters)
3508         if Copy and MakeGroups:
3509             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3510         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3511         return []
3512
3513     ## Creates a new mesh by a symmetrical copy of the object
3514     #  @param theObject mesh, submesh or group
3515     #  @param Mirror AxisStruct or geom object (point, line, plane)
3516     #  @param theMirrorType POINT, AXIS or PLANE
3517     #  If the Mirror is a geom object this parameter is unnecessary
3518     #  @param MakeGroups forces the generation of new groups from existing ones
3519     #  @param NewMeshName the name of the new mesh to create
3520     #  @return instance of Mesh class
3521     #  @ingroup l2_modif_trsf
3522     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3523         if ( isinstance( theObject, Mesh )):
3524             theObject = theObject.GetMesh()
3525         if (isinstance(Mirror, geompyDC.GEOM._objref_GEOM_Object)):
3526             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3527         self.mesh.SetParameters(Mirror.parameters)
3528         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3529                                                 MakeGroups, NewMeshName)
3530         return Mesh( self.smeshpyD,self.geompyD,mesh )
3531
3532     ## Translates the elements
3533     #  @param IDsOfElements list of elements ids
3534     #  @param Vector the direction of translation (DirStruct or vector)
3535     #  @param Copy allows copying the translated elements
3536     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3537     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3538     #  @ingroup l2_modif_trsf
3539     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
3540         if IDsOfElements == []:
3541             IDsOfElements = self.GetElementsId()
3542         if ( isinstance( Vector, geompyDC.GEOM._objref_GEOM_Object)):
3543             Vector = self.smeshpyD.GetDirStruct(Vector)
3544         self.mesh.SetParameters(Vector.PS.parameters)
3545         if Copy and MakeGroups:
3546             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
3547         self.editor.Translate(IDsOfElements, Vector, Copy)
3548         return []
3549
3550     ## Creates a new mesh of translated elements
3551     #  @param IDsOfElements list of elements ids
3552     #  @param Vector the direction of translation (DirStruct or vector)
3553     #  @param MakeGroups forces the generation of new groups from existing ones
3554     #  @param NewMeshName the name of the newly created mesh
3555     #  @return instance of Mesh class
3556     #  @ingroup l2_modif_trsf
3557     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
3558         if IDsOfElements == []:
3559             IDsOfElements = self.GetElementsId()
3560         if ( isinstance( Vector, geompyDC.GEOM._objref_GEOM_Object)):
3561             Vector = self.smeshpyD.GetDirStruct(Vector)
3562         self.mesh.SetParameters(Vector.PS.parameters)
3563         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
3564         return Mesh ( self.smeshpyD, self.geompyD, mesh )
3565
3566     ## Translates the object
3567     #  @param theObject the object to translate (mesh, submesh, or group)
3568     #  @param Vector direction of translation (DirStruct or geom vector)
3569     #  @param Copy allows copying the translated elements
3570     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3571     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3572     #  @ingroup l2_modif_trsf
3573     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
3574         if ( isinstance( theObject, Mesh )):
3575             theObject = theObject.GetMesh()
3576         if ( isinstance( Vector, geompyDC.GEOM._objref_GEOM_Object)):
3577             Vector = self.smeshpyD.GetDirStruct(Vector)
3578         self.mesh.SetParameters(Vector.PS.parameters)
3579         if Copy and MakeGroups:
3580             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
3581         self.editor.TranslateObject(theObject, Vector, Copy)
3582         return []
3583
3584     ## Creates a new mesh from the translated object
3585     #  @param theObject the object to translate (mesh, submesh, or group)
3586     #  @param Vector the direction of translation (DirStruct or geom vector)
3587     #  @param MakeGroups forces the generation of new groups from existing ones
3588     #  @param NewMeshName the name of the newly created mesh
3589     #  @return instance of Mesh class
3590     #  @ingroup l2_modif_trsf
3591     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
3592         if (isinstance(theObject, Mesh)):
3593             theObject = theObject.GetMesh()
3594         if (isinstance(Vector, geompyDC.GEOM._objref_GEOM_Object)):
3595             Vector = self.smeshpyD.GetDirStruct(Vector)
3596         self.mesh.SetParameters(Vector.PS.parameters)
3597         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
3598         return Mesh( self.smeshpyD, self.geompyD, mesh )
3599
3600
3601
3602     ## Scales the object
3603     #  @param theObject - the object to translate (mesh, submesh, or group)
3604     #  @param thePoint - base point for scale
3605     #  @param theScaleFact - list of 1-3 scale factors for axises
3606     #  @param Copy - allows copying the translated elements
3607     #  @param MakeGroups - forces the generation of new groups from existing
3608     #                      ones (if Copy)
3609     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
3610     #          empty list otherwise
3611     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
3612         if ( isinstance( theObject, Mesh )):
3613             theObject = theObject.GetMesh()
3614         if ( isinstance( theObject, list )):
3615             theObject = self.GetIDSource(theObject, SMESH.ALL)
3616
3617         self.mesh.SetParameters(thePoint.parameters)
3618
3619         if Copy and MakeGroups:
3620             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
3621         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
3622         return []
3623
3624     ## Creates a new mesh from the translated object
3625     #  @param theObject - the object to translate (mesh, submesh, or group)
3626     #  @param thePoint - base point for scale
3627     #  @param theScaleFact - list of 1-3 scale factors for axises
3628     #  @param MakeGroups - forces the generation of new groups from existing ones
3629     #  @param NewMeshName - the name of the newly created mesh
3630     #  @return instance of Mesh class
3631     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
3632         if (isinstance(theObject, Mesh)):
3633             theObject = theObject.GetMesh()
3634         if ( isinstance( theObject, list )):
3635             theObject = self.GetIDSource(theObject,SMESH.ALL)
3636
3637         self.mesh.SetParameters(thePoint.parameters)
3638         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
3639                                          MakeGroups, NewMeshName)
3640         return Mesh( self.smeshpyD, self.geompyD, mesh )
3641
3642
3643
3644     ## Rotates the elements
3645     #  @param IDsOfElements list of elements ids
3646     #  @param Axis the axis of rotation (AxisStruct or geom line)
3647     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3648     #  @param Copy allows copying the rotated elements
3649     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3650     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3651     #  @ingroup l2_modif_trsf
3652     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
3653         if IDsOfElements == []:
3654             IDsOfElements = self.GetElementsId()
3655         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
3656             Axis = self.smeshpyD.GetAxisStruct(Axis)
3657         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3658         Parameters = Axis.parameters + var_separator + Parameters
3659         self.mesh.SetParameters(Parameters)
3660         if Copy and MakeGroups:
3661             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
3662         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
3663         return []
3664
3665     ## Creates a new mesh of rotated elements
3666     #  @param IDsOfElements list of element ids
3667     #  @param Axis the axis of rotation (AxisStruct or geom line)
3668     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3669     #  @param MakeGroups forces the generation of new groups from existing ones
3670     #  @param NewMeshName the name of the newly created mesh
3671     #  @return instance of Mesh class
3672     #  @ingroup l2_modif_trsf
3673     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
3674         if IDsOfElements == []:
3675             IDsOfElements = self.GetElementsId()
3676         if ( isinstance( Axis, geompyDC.GEOM._objref_GEOM_Object)):
3677             Axis = self.smeshpyD.GetAxisStruct(Axis)
3678         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3679         Parameters = Axis.parameters + var_separator + Parameters
3680         self.mesh.SetParameters(Parameters)
3681         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
3682                                           MakeGroups, NewMeshName)
3683         return Mesh( self.smeshpyD, self.geompyD, mesh )
3684
3685     ## Rotates the object
3686     #  @param theObject the object to rotate( mesh, submesh, or group)
3687     #  @param Axis the axis of rotation (AxisStruct or geom line)
3688     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3689     #  @param Copy allows copying the rotated elements
3690     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3691     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3692     #  @ingroup l2_modif_trsf
3693     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
3694         if (isinstance(theObject, Mesh)):
3695             theObject = theObject.GetMesh()
3696         if (isinstance(Axis, geompyDC.GEOM._objref_GEOM_Object)):
3697             Axis = self.smeshpyD.GetAxisStruct(Axis)
3698         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3699         Parameters = Axis.parameters + ":" + Parameters
3700         self.mesh.SetParameters(Parameters)
3701         if Copy and MakeGroups:
3702             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
3703         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
3704         return []
3705
3706     ## Creates a new mesh from the rotated object
3707     #  @param theObject the object to rotate (mesh, submesh, or group)
3708     #  @param Axis the axis of rotation (AxisStruct or geom line)
3709     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
3710     #  @param MakeGroups forces the generation of new groups from existing ones
3711     #  @param NewMeshName the name of the newly created mesh
3712     #  @return instance of Mesh class
3713     #  @ingroup l2_modif_trsf
3714     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
3715         if (isinstance( theObject, Mesh )):
3716             theObject = theObject.GetMesh()
3717         if (isinstance(Axis, geompyDC.GEOM._objref_GEOM_Object)):
3718             Axis = self.smeshpyD.GetAxisStruct(Axis)
3719         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3720         Parameters = Axis.parameters + ":" + Parameters
3721         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
3722                                                        MakeGroups, NewMeshName)
3723         self.mesh.SetParameters(Parameters)
3724         return Mesh( self.smeshpyD, self.geompyD, mesh )
3725
3726     ## Finds groups of ajacent nodes within Tolerance.
3727     #  @param Tolerance the value of tolerance
3728     #  @return the list of groups of nodes
3729     #  @ingroup l2_modif_trsf
3730     def FindCoincidentNodes (self, Tolerance):
3731         return self.editor.FindCoincidentNodes(Tolerance)
3732
3733     ## Finds groups of ajacent nodes within Tolerance.
3734     #  @param Tolerance the value of tolerance
3735     #  @param SubMeshOrGroup SubMesh or Group
3736     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
3737     #  @return the list of groups of nodes
3738     #  @ingroup l2_modif_trsf
3739     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
3740         if (isinstance( SubMeshOrGroup, Mesh )):
3741             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
3742         if not isinstance( exceptNodes, list):
3743             exceptNodes = [ exceptNodes ]
3744         if exceptNodes and isinstance( exceptNodes[0], int):
3745             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
3746         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
3747
3748     ## Merges nodes
3749     #  @param GroupsOfNodes the list of groups of nodes
3750     #  @ingroup l2_modif_trsf
3751     def MergeNodes (self, GroupsOfNodes):
3752         self.editor.MergeNodes(GroupsOfNodes)
3753
3754     ## Finds the elements built on the same nodes.
3755     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
3756     #  @return a list of groups of equal elements
3757     #  @ingroup l2_modif_trsf
3758     def FindEqualElements (self, MeshOrSubMeshOrGroup):
3759         if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
3760             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
3761         return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
3762
3763     ## Merges elements in each given group.
3764     #  @param GroupsOfElementsID groups of elements for merging
3765     #  @ingroup l2_modif_trsf
3766     def MergeElements(self, GroupsOfElementsID):
3767         self.editor.MergeElements(GroupsOfElementsID)
3768
3769     ## Leaves one element and removes all other elements built on the same nodes.
3770     #  @ingroup l2_modif_trsf
3771     def MergeEqualElements(self):
3772         self.editor.MergeEqualElements()
3773
3774     ## Sews free borders
3775     #  @return SMESH::Sew_Error
3776     #  @ingroup l2_modif_trsf
3777     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
3778                         FirstNodeID2, SecondNodeID2, LastNodeID2,
3779                         CreatePolygons, CreatePolyedrs):
3780         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
3781                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
3782                                           CreatePolygons, CreatePolyedrs)
3783
3784     ## Sews conform free borders
3785     #  @return SMESH::Sew_Error
3786     #  @ingroup l2_modif_trsf
3787     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
3788                                FirstNodeID2, SecondNodeID2):
3789         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
3790                                                  FirstNodeID2, SecondNodeID2)
3791
3792     ## Sews border to side
3793     #  @return SMESH::Sew_Error
3794     #  @ingroup l2_modif_trsf
3795     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
3796                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
3797         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
3798                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
3799
3800     ## Sews two sides of a mesh. The nodes belonging to Side1 are
3801     #  merged with the nodes of elements of Side2.
3802     #  The number of elements in theSide1 and in theSide2 must be
3803     #  equal and they should have similar nodal connectivity.
3804     #  The nodes to merge should belong to side borders and
3805     #  the first node should be linked to the second.
3806     #  @return SMESH::Sew_Error
3807     #  @ingroup l2_modif_trsf
3808     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
3809                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
3810                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
3811         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
3812                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
3813                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
3814
3815     ## Sets new nodes for the given element.
3816     #  @param ide the element id
3817     #  @param newIDs nodes ids
3818     #  @return If the number of nodes does not correspond to the type of element - returns false
3819     #  @ingroup l2_modif_edit
3820     def ChangeElemNodes(self, ide, newIDs):
3821         return self.editor.ChangeElemNodes(ide, newIDs)
3822
3823     ## If during the last operation of MeshEditor some nodes were
3824     #  created, this method returns the list of their IDs, \n
3825     #  if new nodes were not created - returns empty list
3826     #  @return the list of integer values (can be empty)
3827     #  @ingroup l1_auxiliary
3828     def GetLastCreatedNodes(self):
3829         return self.editor.GetLastCreatedNodes()
3830
3831     ## If during the last operation of MeshEditor some elements were
3832     #  created this method returns the list of their IDs, \n
3833     #  if new elements were not created - returns empty list
3834     #  @return the list of integer values (can be empty)
3835     #  @ingroup l1_auxiliary
3836     def GetLastCreatedElems(self):
3837         return self.editor.GetLastCreatedElems()
3838
3839      ## Creates a hole in a mesh by doubling the nodes of some particular elements
3840     #  @param theNodes identifiers of nodes to be doubled
3841     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
3842     #         nodes. If list of element identifiers is empty then nodes are doubled but
3843     #         they not assigned to elements
3844     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3845     #  @ingroup l2_modif_edit
3846     def DoubleNodes(self, theNodes, theModifiedElems):
3847         return self.editor.DoubleNodes(theNodes, theModifiedElems)
3848
3849     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3850     #  This method provided for convenience works as DoubleNodes() described above.
3851     #  @param theNodeId identifiers of node to be doubled
3852     #  @param theModifiedElems identifiers of elements to be updated
3853     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3854     #  @ingroup l2_modif_edit
3855     def DoubleNode(self, theNodeId, theModifiedElems):
3856         return self.editor.DoubleNode(theNodeId, theModifiedElems)
3857
3858     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3859     #  This method provided for convenience works as DoubleNodes() described above.
3860     #  @param theNodes group of nodes to be doubled
3861     #  @param theModifiedElems group of elements to be updated.
3862     #  @param theMakeGroup forces the generation of a group containing new nodes.
3863     #  @return TRUE or a created group if operation has been completed successfully,
3864     #          FALSE or None otherwise
3865     #  @ingroup l2_modif_edit
3866     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
3867         if theMakeGroup:
3868             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
3869         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
3870
3871     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3872     #  This method provided for convenience works as DoubleNodes() described above.
3873     #  @param theNodes list of groups of nodes to be doubled
3874     #  @param theModifiedElems list of groups of elements to be updated.
3875     #  @param theMakeGroup forces the generation of a group containing new nodes.
3876     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3877     #  @ingroup l2_modif_edit
3878     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
3879         if theMakeGroup:
3880             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
3881         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
3882
3883     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3884     #  @param theElems - the list of elements (edges or faces) to be replicated
3885     #         The nodes for duplication could be found from these elements
3886     #  @param theNodesNot - list of nodes to NOT replicate
3887     #  @param theAffectedElems - the list of elements (cells and edges) to which the
3888     #         replicated nodes should be associated to.
3889     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3890     #  @ingroup l2_modif_edit
3891     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
3892         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
3893
3894     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3895     #  @param theElems - the list of elements (edges or faces) to be replicated
3896     #         The nodes for duplication could be found from these elements
3897     #  @param theNodesNot - list of nodes to NOT replicate
3898     #  @param theShape - shape to detect affected elements (element which geometric center
3899     #         located on or inside shape).
3900     #         The replicated nodes should be associated to affected elements.
3901     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3902     #  @ingroup l2_modif_edit
3903     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
3904         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
3905
3906     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3907     #  This method provided for convenience works as DoubleNodes() described above.
3908     #  @param theElems - group of of elements (edges or faces) to be replicated
3909     #  @param theNodesNot - group of nodes not to replicated
3910     #  @param theAffectedElems - group of elements to which the replicated nodes
3911     #         should be associated to.
3912     #  @param theMakeGroup forces the generation of a group containing new elements.
3913     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
3914     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
3915     #          FALSE or None otherwise
3916     #  @ingroup l2_modif_edit
3917     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
3918                              theMakeGroup=False, theMakeNodeGroup=False):
3919         if theMakeGroup or theMakeNodeGroup:
3920             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
3921                                                             theAffectedElems,
3922                                                             theMakeGroup, theMakeNodeGroup)
3923             if theMakeGroup and theMakeNodeGroup:
3924                 return twoGroups
3925             else:
3926                 return twoGroups[ int(theMakeNodeGroup) ]
3927         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
3928
3929     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3930     #  This method provided for convenience works as DoubleNodes() described above.
3931     #  @param theElems - group of of elements (edges or faces) to be replicated
3932     #  @param theNodesNot - group of nodes not to replicated
3933     #  @param theShape - shape to detect affected elements (element which geometric center
3934     #         located on or inside shape).
3935     #         The replicated nodes should be associated to affected elements.
3936     #  @ingroup l2_modif_edit
3937     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
3938         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
3939
3940     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3941     #  This method provided for convenience works as DoubleNodes() described above.
3942     #  @param theElems - list of groups of elements (edges or faces) to be replicated
3943     #  @param theNodesNot - list of groups of nodes not to replicated
3944     #  @param theAffectedElems - group of elements to which the replicated nodes
3945     #         should be associated to.
3946     #  @param theMakeGroup forces the generation of a group containing new elements.
3947     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
3948     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
3949     #          FALSE or None otherwise
3950     #  @ingroup l2_modif_edit
3951     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
3952                              theMakeGroup=False, theMakeNodeGroup=False):
3953         if theMakeGroup or theMakeNodeGroup:
3954             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
3955                                                              theAffectedElems,
3956                                                              theMakeGroup, theMakeNodeGroup)
3957             if theMakeGroup and theMakeNodeGroup:
3958                 return twoGroups
3959             else:
3960                 return twoGroups[ int(theMakeNodeGroup) ]
3961         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
3962
3963     ## Creates a hole in a mesh by doubling the nodes of some particular elements
3964     #  This method provided for convenience works as DoubleNodes() described above.
3965     #  @param theElems - list of groups of elements (edges or faces) to be replicated
3966     #  @param theNodesNot - list of groups of nodes not to replicated
3967     #  @param theShape - shape to detect affected elements (element which geometric center
3968     #         located on or inside shape).
3969     #         The replicated nodes should be associated to affected elements.
3970     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3971     #  @ingroup l2_modif_edit
3972     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
3973         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
3974
3975     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
3976     # The list of groups must describe a partition of the mesh volumes.
3977     # The nodes of the internal faces at the boundaries of the groups are doubled.
3978     # In option, the internal faces are replaced by flat elements.
3979     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
3980     # @param theDomains - list of groups of volumes
3981     # @param createJointElems - if TRUE, create the elements
3982     # @return TRUE if operation has been completed successfully, FALSE otherwise
3983     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
3984        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
3985
3986     ## Double nodes on some external faces and create flat elements.
3987     # Flat elements are mainly used by some types of mechanic calculations.
3988     #
3989     # Each group of the list must be constituted of faces.
3990     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
3991     # @param theGroupsOfFaces - list of groups of faces
3992     # @return TRUE if operation has been completed successfully, FALSE otherwise
3993     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
3994         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
3995
3996     def _valueFromFunctor(self, funcType, elemId):
3997         fn = self.smeshpyD.GetFunctor(funcType)
3998         fn.SetMesh(self.mesh)
3999         if fn.GetElementType() == self.GetElementType(elemId, True):
4000             val = fn.GetValue(elemId)
4001         else:
4002             val = 0
4003         return val
4004
4005     ## Get length of 1D element.
4006     #  @param elemId mesh element ID
4007     #  @return element's length value
4008     #  @ingroup l1_measurements
4009     def GetLength(self, elemId):
4010         return self._valueFromFunctor(SMESH.FT_Length, elemId)
4011
4012     ## Get area of 2D element.
4013     #  @param elemId mesh element ID
4014     #  @return element's area value
4015     #  @ingroup l1_measurements
4016     def GetArea(self, elemId):
4017         return self._valueFromFunctor(SMESH.FT_Area, elemId)
4018
4019     ## Get volume of 3D element.
4020     #  @param elemId mesh element ID
4021     #  @return element's volume value
4022     #  @ingroup l1_measurements
4023     def GetVolume(self, elemId):
4024         return self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4025
4026     ## Get maximum element length.
4027     #  @param elemId mesh element ID
4028     #  @return element's maximum length value
4029     #  @ingroup l1_measurements
4030     def GetMaxElementLength(self, elemId):
4031         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4032             ftype = SMESH.FT_MaxElementLength3D
4033         else:
4034             ftype = SMESH.FT_MaxElementLength2D
4035         return self._valueFromFunctor(ftype, elemId)
4036
4037     ## Get aspect ratio of 2D or 3D element.
4038     #  @param elemId mesh element ID
4039     #  @return element's aspect ratio value
4040     #  @ingroup l1_measurements
4041     def GetAspectRatio(self, elemId):
4042         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4043             ftype = SMESH.FT_AspectRatio3D
4044         else:
4045             ftype = SMESH.FT_AspectRatio
4046         return self._valueFromFunctor(ftype, elemId)
4047
4048     ## Get warping angle of 2D element.
4049     #  @param elemId mesh element ID
4050     #  @return element's warping angle value
4051     #  @ingroup l1_measurements
4052     def GetWarping(self, elemId):
4053         return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4054
4055     ## Get minimum angle of 2D element.
4056     #  @param elemId mesh element ID
4057     #  @return element's minimum angle value
4058     #  @ingroup l1_measurements
4059     def GetMinimumAngle(self, elemId):
4060         return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4061
4062     ## Get taper of 2D element.
4063     #  @param elemId mesh element ID
4064     #  @return element's taper value
4065     #  @ingroup l1_measurements
4066     def GetTaper(self, elemId):
4067         return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4068
4069     ## Get skew of 2D element.
4070     #  @param elemId mesh element ID
4071     #  @return element's skew value
4072     #  @ingroup l1_measurements
4073     def GetSkew(self, elemId):
4074         return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4075
4076 ## The mother class to define algorithm, it is not recommended to use it directly.
4077 #
4078 #  For each meshing algorithm, a python class inheriting from class Mesh_Algorithm
4079 #  should be defined. This descendant class sould have two attributes defining the way
4080 # it is created by class Mesh (see e.g. class StdMeshersDC_Segment in StdMeshersDC.py).
4081 # - meshMethod attribute defines name of method of class Mesh by calling which the
4082 #   python class of algorithm is created. E.g. if in class MyPlugin_Algorithm
4083 #   meshMethod = "MyAlgorithm", then an instance of MyPlugin_Algorithm is created
4084 #   by the following code: my_algo = mesh.MyAlgorithm()
4085 # - algoType defines name of algorithm type and is used mostly to discriminate
4086 #   algorithms that are created by the same method of class Mesh. E.g. if
4087 #   MyPlugin_Algorithm.algoType = "MyPLUGIN" then it's creation code can be:
4088 #   my_algo = mesh.MyAlgorithm(algo="MyPLUGIN")
4089 #  @ingroup l2_algorithms
4090 class Mesh_Algorithm:
4091     #  @class Mesh_Algorithm
4092     #  @brief Class Mesh_Algorithm
4093
4094     #def __init__(self,smesh):
4095     #    self.smesh=smesh
4096     def __init__(self):
4097         self.mesh = None
4098         self.geom = None
4099         self.subm = None
4100         self.algo = None
4101
4102     ## Finds a hypothesis in the study by its type name and parameters.
4103     #  Finds only the hypotheses created in smeshpyD engine.
4104     #  @return SMESH.SMESH_Hypothesis
4105     def FindHypothesis (self, hypname, args, CompareMethod, smeshpyD):
4106         study = smeshpyD.GetCurrentStudy()
4107         #to do: find component by smeshpyD object, not by its data type
4108         scomp = study.FindComponent(smeshpyD.ComponentDataType())
4109         if scomp is not None:
4110             res,hypRoot = scomp.FindSubObject(SMESH.Tag_HypothesisRoot)
4111             # Check if the root label of the hypotheses exists
4112             if res and hypRoot is not None:
4113                 iter = study.NewChildIterator(hypRoot)
4114                 # Check all published hypotheses
4115                 while iter.More():
4116                     hypo_so_i = iter.Value()
4117                     attr = hypo_so_i.FindAttribute("AttributeIOR")[1]
4118                     if attr is not None:
4119                         anIOR = attr.Value()
4120                         hypo_o_i = salome.orb.string_to_object(anIOR)
4121                         if hypo_o_i is not None:
4122                             # Check if this is a hypothesis
4123                             hypo_i = hypo_o_i._narrow(SMESH.SMESH_Hypothesis)
4124                             if hypo_i is not None:
4125                                 # Check if the hypothesis belongs to current engine
4126                                 if smeshpyD.GetObjectId(hypo_i) > 0:
4127                                     # Check if this is the required hypothesis
4128                                     if hypo_i.GetName() == hypname:
4129                                         # Check arguments
4130                                         if CompareMethod(hypo_i, args):
4131                                             # found!!!
4132                                             return hypo_i
4133                                         pass
4134                                     pass
4135                                 pass
4136                             pass
4137                         pass
4138                     iter.Next()
4139                     pass
4140                 pass
4141             pass
4142         return None
4143
4144     ## Finds the algorithm in the study by its type name.
4145     #  Finds only the algorithms, which have been created in smeshpyD engine.
4146     #  @return SMESH.SMESH_Algo
4147     def FindAlgorithm (self, algoname, smeshpyD):
4148         study = smeshpyD.GetCurrentStudy()
4149         if not study: return None
4150         #to do: find component by smeshpyD object, not by its data type
4151         scomp = study.FindComponent(smeshpyD.ComponentDataType())
4152         if scomp is not None:
4153             res,hypRoot = scomp.FindSubObject(SMESH.Tag_AlgorithmsRoot)
4154             # Check if the root label of the algorithms exists
4155             if res and hypRoot is not None:
4156                 iter = study.NewChildIterator(hypRoot)
4157                 # Check all published algorithms
4158                 while iter.More():
4159                     algo_so_i = iter.Value()
4160                     attr = algo_so_i.FindAttribute("AttributeIOR")[1]
4161                     if attr is not None:
4162                         anIOR = attr.Value()
4163                         algo_o_i = salome.orb.string_to_object(anIOR)
4164                         if algo_o_i is not None:
4165                             # Check if this is an algorithm
4166                             algo_i = algo_o_i._narrow(SMESH.SMESH_Algo)
4167                             if algo_i is not None:
4168                                 # Checks if the algorithm belongs to the current engine
4169                                 if smeshpyD.GetObjectId(algo_i) > 0:
4170                                     # Check if this is the required algorithm
4171                                     if algo_i.GetName() == algoname:
4172                                         # found!!!
4173                                         return algo_i
4174                                     pass
4175                                 pass
4176                             pass
4177                         pass
4178                     iter.Next()
4179                     pass
4180                 pass
4181             pass
4182         return None
4183
4184     ## If the algorithm is global, returns 0; \n
4185     #  else returns the submesh associated to this algorithm.
4186     def GetSubMesh(self):
4187         return self.subm
4188
4189     ## Returns the wrapped mesher.
4190     def GetAlgorithm(self):
4191         return self.algo
4192
4193     ## Gets the list of hypothesis that can be used with this algorithm
4194     def GetCompatibleHypothesis(self):
4195         mylist = []
4196         if self.algo:
4197             mylist = self.algo.GetCompatibleHypothesis()
4198         return mylist
4199
4200     ## Gets the name of the algorithm
4201     def GetName(self):
4202         GetName(self.algo)
4203
4204     ## Sets the name to the algorithm
4205     def SetName(self, name):
4206         self.mesh.smeshpyD.SetName(self.algo, name)
4207
4208     ## Gets the id of the algorithm
4209     def GetId(self):
4210         return self.algo.GetId()
4211
4212     ## Private method.
4213     def Create(self, mesh, geom, hypo, so="libStdMeshersEngine.so"):
4214         if geom is None:
4215             raise RuntimeError, "Attemp to create " + hypo + " algoritm on None shape"
4216         algo = self.FindAlgorithm(hypo, mesh.smeshpyD)
4217         if algo is None:
4218             algo = mesh.smeshpyD.CreateHypothesis(hypo, so)
4219             pass
4220         self.Assign(algo, mesh, geom)
4221         return self.algo
4222
4223     ## Private method
4224     def Assign(self, algo, mesh, geom):
4225         if geom is None:
4226             raise RuntimeError, "Attemp to create " + algo + " algoritm on None shape"
4227         self.mesh = mesh
4228         name = ""
4229         if not geom:
4230             self.geom = mesh.geom
4231         else:
4232             self.geom = geom
4233             AssureGeomPublished( mesh, geom )
4234             try:
4235                 name = GetName(geom)
4236                 pass
4237             except:
4238                 pass
4239             self.subm = mesh.mesh.GetSubMesh(geom, algo.GetName())
4240         self.algo = algo
4241         status = mesh.mesh.AddHypothesis(self.geom, self.algo)
4242         TreatHypoStatus( status, algo.GetName(), name, True )
4243         return
4244
4245     def CompareHyp (self, hyp, args):
4246         print "CompareHyp is not implemented for ", self.__class__.__name__, ":", hyp.GetName()
4247         return False
4248
4249     def CompareEqualHyp (self, hyp, args):
4250         return True
4251
4252     ## Private method
4253     def Hypothesis (self, hyp, args=[], so="libStdMeshersEngine.so",
4254                     UseExisting=0, CompareMethod=""):
4255         hypo = None
4256         if UseExisting:
4257             if CompareMethod == "": CompareMethod = self.CompareHyp
4258             hypo = self.FindHypothesis(hyp, args, CompareMethod, self.mesh.smeshpyD)
4259             pass
4260         if hypo is None:
4261             hypo = self.mesh.smeshpyD.CreateHypothesis(hyp, so)
4262             a = ""
4263             s = "="
4264             for arg in args:
4265                 argStr = str(arg)
4266                 if isinstance( arg, geompyDC.GEOM._objref_GEOM_Object ):
4267                     argStr = arg.GetStudyEntry()
4268                     if not argStr: argStr = "GEOM_Obj_%s", arg.GetEntry()
4269                 if len( argStr ) > 10:
4270                     argStr = argStr[:7]+"..."
4271                     if argStr[0] == '[': argStr += ']'
4272                 a = a + s + argStr
4273                 s = ","
4274                 pass
4275             if len(a) > 50:
4276                 a = a[:47]+"..."
4277             self.mesh.smeshpyD.SetName(hypo, hyp + a)
4278             pass
4279         geomName=""
4280         if self.geom:
4281             geomName = GetName(self.geom)
4282         status = self.mesh.mesh.AddHypothesis(self.geom, hypo)
4283         TreatHypoStatus( status, GetName(hypo), geomName, 0 )
4284         return hypo
4285
4286     ## Returns entry of the shape to mesh in the study
4287     def MainShapeEntry(self):
4288         if not self.mesh or not self.mesh.GetMesh(): return ""
4289         if not self.mesh.GetMesh().HasShapeToMesh(): return ""
4290         shape = self.mesh.GetShape()
4291         return shape.GetStudyEntry()
4292
4293     ## Defines "ViscousLayers" hypothesis to give parameters of layers of prisms to build
4294     #  near mesh boundary. This hypothesis can be used by several 3D algorithms:
4295     #  NETGEN 3D, GHS3D, Hexahedron(i,j,k)
4296     #  @param thickness total thickness of layers of prisms
4297     #  @param numberOfLayers number of layers of prisms
4298     #  @param stretchFactor factor (>1.0) of growth of layer thickness towards inside of mesh
4299     #  @param ignoreFaces list of geometrical faces (or their ids) not to generate layers on
4300     #  @ingroup l3_hypos_additi
4301     def ViscousLayers(self, thickness, numberOfLayers, stretchFactor, ignoreFaces=[]):
4302         if not isinstance(self.algo, SMESH._objref_SMESH_3D_Algo):
4303             raise TypeError, "ViscousLayers are supported by 3D algorithms only"
4304         if not "ViscousLayers" in self.GetCompatibleHypothesis():
4305             raise TypeError, "ViscousLayers are not supported by %s"%self.algo.GetName()
4306         if ignoreFaces and isinstance( ignoreFaces[0], geompyDC.GEOM._objref_GEOM_Object ):
4307             ignoreFaces = [ self.mesh.geompyD.GetSubShapeID(self.mesh.geom, f) for f in ignoreFaces ]
4308         hyp = self.Hypothesis("ViscousLayers",
4309                               [thickness, numberOfLayers, stretchFactor, ignoreFaces])
4310         hyp.SetTotalThickness(thickness)
4311         hyp.SetNumberLayers(numberOfLayers)
4312         hyp.SetStretchFactor(stretchFactor)
4313         hyp.SetIgnoreFaces(ignoreFaces)
4314         return hyp
4315
4316     ## Transform a list of ether edges or tuples (edge, 1st_vertex_of_edge)
4317     #  into a list acceptable to SetReversedEdges() of some 1D hypotheses
4318     #  @ingroup l3_hypos_1dhyps
4319     def ReversedEdgeIndices(self, reverseList):
4320         resList = []
4321         geompy = self.mesh.geompyD
4322         for i in reverseList:
4323             if isinstance( i, int ):
4324                 s = geompy.SubShapes(self.mesh.geom, [i])[0]
4325                 if s.GetShapeType() != geompyDC.GEOM.EDGE:
4326                     raise TypeError, "Not EDGE index given"
4327                 resList.append( i )
4328             elif isinstance( i, geompyDC.GEOM._objref_GEOM_Object ):
4329                 if i.GetShapeType() != geompyDC.GEOM.EDGE:
4330                     raise TypeError, "Not an EDGE given"
4331                 resList.append( geompy.GetSubShapeID(self.mesh.geom, i ))
4332             elif len( i ) > 1:
4333                 e = i[0]
4334                 v = i[1]
4335                 if not isinstance( e, geompyDC.GEOM._objref_GEOM_Object ) or \
4336                    not isinstance( v, geompyDC.GEOM._objref_GEOM_Object ):
4337                     raise TypeError, "A list item must be a tuple (edge, 1st_vertex_of_edge)"
4338                 if v.GetShapeType() == geompyDC.GEOM.EDGE and \
4339                    e.GetShapeType() == geompyDC.GEOM.VERTEX:
4340                     v,e = e,v
4341                 if e.GetShapeType() != geompyDC.GEOM.EDGE or \
4342                    v.GetShapeType() != geompyDC.GEOM.VERTEX:
4343                     raise TypeError, "A list item must be a tuple (edge, 1st_vertex_of_edge)"
4344                 vFirst = FirstVertexOnCurve( e )
4345                 tol    = geompy.Tolerance( vFirst )[-1]
4346                 if geompy.MinDistance( v, vFirst ) > 1.5*tol:
4347                     resList.append( geompy.GetSubShapeID(self.mesh.geom, e ))
4348             else:
4349                 raise TypeError, "Item must be either an edge or tuple (edge, 1st_vertex_of_edge)"
4350         return resList
4351
4352
4353 class Pattern(SMESH._objref_SMESH_Pattern):
4354
4355     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4356         decrFun = lambda i: i-1
4357         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4358         theMesh.SetParameters(Parameters)
4359         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4360
4361     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4362         decrFun = lambda i: i-1
4363         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4364         theMesh.SetParameters(Parameters)
4365         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4366
4367 #Registering the new proxy for Pattern
4368 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4369
4370
4371
4372
4373
4374 ## Private class used to bind methods creating algorithms to the class Mesh
4375 #
4376 class algoCreator:
4377     def __init__(self):
4378         self.mesh = None
4379         self.defaultAlgoType = ""
4380         self.algoTypeToClass = {}
4381
4382     # Stores a python class of algorithm
4383     def add(self, algoClass):
4384         if type( algoClass ).__name__ == 'classobj' and \
4385            hasattr( algoClass, "algoType"):
4386             self.algoTypeToClass[ algoClass.algoType ] = algoClass
4387             if not self.defaultAlgoType and \
4388                hasattr( algoClass, "isDefault") and algoClass.isDefault:
4389                 self.defaultAlgoType = algoClass.algoType
4390             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4391
4392     # creates a copy of self and assign mesh to the copy
4393     def copy(self, mesh):
4394         other = algoCreator()
4395         other.defaultAlgoType = self.defaultAlgoType
4396         other.algoTypeToClass  = self.algoTypeToClass
4397         other.mesh = mesh
4398         return other
4399
4400     # creates an instance of algorithm
4401     def __call__(self,algo="",geom=0,*args):
4402         algoType = self.defaultAlgoType
4403         for arg in args + (algo,geom):
4404             if isinstance( arg, geompyDC.GEOM._objref_GEOM_Object ):
4405                 geom = arg
4406             if isinstance( arg, str ) and arg:
4407                 algoType = arg
4408         if not algoType and self.algoTypeToClass:
4409             algoType = self.algoTypeToClass.keys()[0]
4410         if self.algoTypeToClass.has_key( algoType ):
4411             #print "Create algo",algoType
4412             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4413         raise RuntimeError, "No class found for algo type %s" % algoType
4414         return None
4415
4416 # Private class used to substitute and store variable parameters of hypotheses.
4417 class hypMethodWrapper:
4418     def __init__(self, hyp, method):
4419         self.hyp    = hyp
4420         self.method = method
4421         #print "REBIND:", method.__name__
4422         return
4423
4424     # call a method of hypothesis with calling SetVarParameter() before
4425     def __call__(self,*args):
4426         if not args:
4427             return self.method( self.hyp, *args ) # hypothesis method with no args
4428
4429         #print "MethWrapper.__call__",self.method.__name__, args
4430         try:
4431             parsed = ParseParameters(*args)     # replace variables with their values
4432             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4433             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4434         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4435             # maybe there is a replaced string arg which is not variable
4436             result = self.method( self.hyp, *args )
4437         except ValueError, detail: # raised by ParseParameters()
4438             try:
4439                 result = self.method( self.hyp, *args )
4440             except omniORB.CORBA.BAD_PARAM:
4441                 raise ValueError, detail # wrong variable name
4442
4443         return result