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