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