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