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