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