1 # Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
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.
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.
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
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
30 ## @defgroup l2_construct Constructing meshes
31 ## @defgroup l2_algorithms Defining Algorithms
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
40 ## @defgroup l2_hypotheses Defining hypotheses
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
49 ## @defgroup l2_submeshes Constructing submeshes
50 ## @defgroup l2_compounds Building Compounds
51 ## @defgroup l2_editing Editing Meshes
54 ## @defgroup l1_meshinfo Mesh Information
55 ## @defgroup l1_controls Quality controls and Filtering
56 ## @defgroup l1_grouping Grouping elements
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
64 ## @defgroup l1_modifying Modifying meshes
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
83 ## @defgroup l1_measurements Measurements
86 from salome.geom import geomBuilder
88 import SMESH # This is necessary for back compatibility
90 from salome.smesh.smesh_algorithm import Mesh_Algorithm
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
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__)
106 ## @addtogroup l1_auxiliary
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
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):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
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)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
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)
159 SMESH.PointStruct.__init__ = __initPointStruct
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)
166 SMESH.AxisStruct.__init__ = __initAxisStruct
168 smeshPrecisionConfusion = 1.e-07
169 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
170 if abs(val1 - val2) < tol:
180 if isinstance(obj, SALOMEDS._objref_SObject):
184 ior = salome.orb.object_to_string(obj)
189 studies = salome.myStudyManager.GetOpenStudies()
190 for sname in studies:
191 s = salome.myStudyManager.GetStudyByName(sname)
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
200 # unknown CORBA object, no GetName() method
203 if hasattr(obj, "GetName"):
204 # unknown non-CORBA object, having GetName() method
207 raise RuntimeError, "Null or invalid object"
209 ## Prints error message if a hypothesis was not assigned.
210 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
212 hypType = "algorithm"
214 hypType = "hypothesis"
217 if hasattr( status, "__getitem__" ):
218 status,reason = status[0],status[1]
219 if status == HYP_UNKNOWN_FATAL :
220 reason = "for unknown reason"
221 elif status == HYP_INCOMPATIBLE :
222 reason = "this hypothesis mismatches the algorithm"
223 elif status == HYP_NOTCONFORM :
224 reason = "a non-conform mesh would be built"
225 elif status == HYP_ALREADY_EXIST :
226 if isAlgo: return # it does not influence anything
227 reason = hypType + " of the same dimension is already assigned to this shape"
228 elif status == HYP_BAD_DIM :
229 reason = hypType + " mismatches the shape"
230 elif status == HYP_CONCURENT :
231 reason = "there are concurrent hypotheses on sub-shapes"
232 elif status == HYP_BAD_SUBSHAPE :
233 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
234 elif status == HYP_BAD_GEOMETRY:
235 reason = "geometry mismatches the expectation of the algorithm"
236 elif status == HYP_HIDDEN_ALGO:
237 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
238 elif status == HYP_HIDING_ALGO:
239 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
240 elif status == HYP_NEED_SHAPE:
241 reason = "algorithm can't work without shape"
242 elif status == HYP_INCOMPAT_HYPS:
248 where = '"%s"' % geomName
250 meshName = GetName( mesh )
251 if meshName and meshName != NO_NAME:
252 where = '"%s" in "%s"' % ( geomName, meshName )
253 if status < HYP_UNKNOWN_FATAL and where:
254 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
256 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
258 print '"%s" was not assigned : %s' %( hypName, reason )
261 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
262 def AssureGeomPublished(mesh, geom, name=''):
263 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
265 if not geom.GetStudyEntry() and \
266 mesh.smeshpyD.GetCurrentStudy():
268 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
269 if studyID != mesh.geompyD.myStudyId:
270 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
272 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
273 # for all groups SubShapeName() returns "Compound_-1"
274 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
276 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
278 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
281 ## Return the first vertex of a geometrical edge by ignoring orientation
282 def FirstVertexOnCurve(mesh, edge):
283 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
285 raise TypeError, "Given object has no vertices"
286 if len( vv ) == 1: return vv[0]
287 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
288 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
289 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
290 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
293 dist1 += abs( xyz[i] - xyz1[i] )
294 dist2 += abs( xyz[i] - xyz2[i] )
300 # end of l1_auxiliary
304 # Warning: smeshInst is a singleton
310 ## This class allows to create, load or manipulate meshes
311 # It has a set of methods to create load or copy meshes, to combine several meshes.
312 # It also has methods to get infos on meshes.
313 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
315 # MirrorType enumeration
316 POINT = SMESH_MeshEditor.POINT
317 AXIS = SMESH_MeshEditor.AXIS
318 PLANE = SMESH_MeshEditor.PLANE
320 # Smooth_Method enumeration
321 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
322 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
324 PrecisionConfusion = smeshPrecisionConfusion
326 # TopAbs_State enumeration
327 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
329 # Methods of splitting a hexahedron into tetrahedra
330 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
336 #print "==== __new__", engine, smeshInst, doLcc
338 if smeshInst is None:
339 # smesh engine is either retrieved from engine, or created
341 # Following test avoids a recursive loop
343 if smeshInst is not None:
344 # smesh engine not created: existing engine found
348 # FindOrLoadComponent called:
349 # 1. CORBA resolution of server
350 # 2. the __new__ method is called again
351 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
352 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
354 # FindOrLoadComponent not called
355 if smeshInst is None:
356 # smeshBuilder instance is created from lcc.FindOrLoadComponent
357 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
358 smeshInst = super(smeshBuilder,cls).__new__(cls)
360 # smesh engine not created: existing engine found
361 #print "==== existing ", engine, smeshInst, doLcc
363 #print "====1 ", smeshInst
366 #print "====2 ", smeshInst
371 #print "--------------- smeshbuilder __init__ ---", created
374 SMESH._objref_SMESH_Gen.__init__(self)
376 ## Dump component to the Python script
377 # This method overrides IDL function to allow default values for the parameters.
378 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
379 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
381 ## Set mode of DumpPython(), \a historical or \a snapshot.
382 # In the \a historical mode, the Python Dump script includes all commands
383 # performed by SMESH engine. In the \a snapshot mode, commands
384 # relating to objects removed from the Study are excluded from the script
385 # as well as commands not influencing the current state of meshes
386 def SetDumpPythonHistorical(self, isHistorical):
387 if isHistorical: val = "true"
389 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
391 ## Sets the current study and Geometry component
392 # @ingroup l1_auxiliary
393 def init_smesh(self,theStudy,geompyD = None):
395 self.SetCurrentStudy(theStudy,geompyD)
398 notebook.myStudy = theStudy
400 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
401 # or a mesh wrapping a CORBA mesh given as a parameter.
402 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
403 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
404 # (2) a Geometrical object for meshing or
406 # @param name the name for the new mesh.
407 # @return an instance of Mesh class.
408 # @ingroup l2_construct
409 def Mesh(self, obj=0, name=0):
410 if isinstance(obj,str):
412 return Mesh(self,self.geompyD,obj,name)
414 ## Returns a long value from enumeration
415 # @ingroup l1_controls
416 def EnumToLong(self,theItem):
419 ## Returns a string representation of the color.
420 # To be used with filters.
421 # @param c color value (SALOMEDS.Color)
422 # @ingroup l1_controls
423 def ColorToString(self,c):
425 if isinstance(c, SALOMEDS.Color):
426 val = "%s;%s;%s" % (c.R, c.G, c.B)
427 elif isinstance(c, str):
430 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
433 ## Gets PointStruct from vertex
434 # @param theVertex a GEOM object(vertex)
435 # @return SMESH.PointStruct
436 # @ingroup l1_auxiliary
437 def GetPointStruct(self,theVertex):
438 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
439 return PointStruct(x,y,z)
441 ## Gets DirStruct from vector
442 # @param theVector a GEOM object(vector)
443 # @return SMESH.DirStruct
444 # @ingroup l1_auxiliary
445 def GetDirStruct(self,theVector):
446 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
447 if(len(vertices) != 2):
448 print "Error: vector object is incorrect."
450 p1 = self.geompyD.PointCoordinates(vertices[0])
451 p2 = self.geompyD.PointCoordinates(vertices[1])
452 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
453 dirst = DirStruct(pnt)
456 ## Makes DirStruct from a triplet
457 # @param x,y,z vector components
458 # @return SMESH.DirStruct
459 # @ingroup l1_auxiliary
460 def MakeDirStruct(self,x,y,z):
461 pnt = PointStruct(x,y,z)
462 return DirStruct(pnt)
464 ## Get AxisStruct from object
465 # @param theObj a GEOM object (line or plane)
466 # @return SMESH.AxisStruct
467 # @ingroup l1_auxiliary
468 def GetAxisStruct(self,theObj):
470 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
473 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
474 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
475 vertex1 = self.geompyD.PointCoordinates(vertex1)
476 vertex2 = self.geompyD.PointCoordinates(vertex2)
477 vertex3 = self.geompyD.PointCoordinates(vertex3)
478 vertex4 = self.geompyD.PointCoordinates(vertex4)
479 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
480 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
481 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] ]
482 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
483 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
484 elif len(edges) == 1:
485 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
486 p1 = self.geompyD.PointCoordinates( vertex1 )
487 p2 = self.geompyD.PointCoordinates( vertex2 )
488 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
489 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
490 elif theObj.GetShapeType() == GEOM.VERTEX:
491 x,y,z = self.geompyD.PointCoordinates( theObj )
492 axis = AxisStruct( x,y,z, 1,0,0,)
493 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
496 # From SMESH_Gen interface:
497 # ------------------------
499 ## Sets the given name to the object
500 # @param obj the object to rename
501 # @param name a new object name
502 # @ingroup l1_auxiliary
503 def SetName(self, obj, name):
504 if isinstance( obj, Mesh ):
506 elif isinstance( obj, Mesh_Algorithm ):
507 obj = obj.GetAlgorithm()
508 ior = salome.orb.object_to_string(obj)
509 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
511 ## Sets the current mode
512 # @ingroup l1_auxiliary
513 def SetEmbeddedMode( self,theMode ):
514 #self.SetEmbeddedMode(theMode)
515 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
517 ## Gets the current mode
518 # @ingroup l1_auxiliary
519 def IsEmbeddedMode(self):
520 #return self.IsEmbeddedMode()
521 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
523 ## Sets the current study. Calling SetCurrentStudy( None ) allows to
524 # switch OFF automatic pubilishing in the Study of mesh objects.
525 # @ingroup l1_auxiliary
526 def SetCurrentStudy( self, theStudy, geompyD = None ):
527 #self.SetCurrentStudy(theStudy)
529 from salome.geom import geomBuilder
530 geompyD = geomBuilder.geom
533 self.SetGeomEngine(geompyD)
534 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
537 notebook = salome_notebook.NoteBook( theStudy )
539 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
541 sb = theStudy.NewBuilder()
542 sc = theStudy.FindComponent("SMESH")
543 if sc: sb.LoadWith(sc, self)
547 ## Gets the current study
548 # @ingroup l1_auxiliary
549 def GetCurrentStudy(self):
550 #return self.GetCurrentStudy()
551 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
553 ## Creates a Mesh object importing data from the given UNV file
554 # @return an instance of Mesh class
556 def CreateMeshesFromUNV( self,theFileName ):
557 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
558 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
561 ## Creates a Mesh object(s) importing data from the given MED file
562 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
564 def CreateMeshesFromMED( self,theFileName ):
565 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
566 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
567 return aMeshes, aStatus
569 ## Creates a Mesh object(s) importing data from the given SAUV file
570 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
572 def CreateMeshesFromSAUV( self,theFileName ):
573 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
574 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
575 return aMeshes, aStatus
577 ## Creates a Mesh object importing data from the given STL file
578 # @return an instance of Mesh class
580 def CreateMeshesFromSTL( self, theFileName ):
581 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
582 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
585 ## Creates Mesh objects importing data from the given CGNS file
586 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
588 def CreateMeshesFromCGNS( self, theFileName ):
589 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
590 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
591 return aMeshes, aStatus
593 ## Creates a Mesh object importing data from the given GMF file.
594 # GMF files must have .mesh extension for the ASCII format and .meshb for
596 # @return [ an instance of Mesh class, SMESH.ComputeError ]
598 def CreateMeshesFromGMF( self, theFileName ):
599 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
602 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
603 return Mesh(self, self.geompyD, aSmeshMesh), error
605 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
606 # present in the new mesh.
607 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
608 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
609 # @param mergeNodesAndElements if true, equal nodes and elements are merged
610 # @param mergeTolerance tolerance for merging nodes
611 # @param allGroups forces creation of groups corresponding to every input mesh
612 # @param name name of a new mesh
613 # @return an instance of Mesh class
614 def Concatenate( self, meshes, uniteIdenticalGroups,
615 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
617 if not meshes: return None
618 for i,m in enumerate(meshes):
619 if isinstance(m, Mesh):
620 meshes[i] = m.GetMesh()
621 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
622 meshes[0].SetParameters(Parameters)
624 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
625 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
629 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
632 ## Create a mesh by copying a part of another mesh.
633 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
634 # to copy nodes or elements not contained in any mesh object,
635 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
636 # @param meshName a name of the new mesh
637 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
638 # @param toKeepIDs to preserve order of the copied elements or not
639 # @return an instance of Mesh class
640 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
641 if (isinstance( meshPart, Mesh )):
642 meshPart = meshPart.GetMesh()
643 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
644 return Mesh(self, self.geompyD, mesh)
646 ## From SMESH_Gen interface
647 # @return the list of integer values
648 # @ingroup l1_auxiliary
649 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
650 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
652 ## From SMESH_Gen interface. Creates a pattern
653 # @return an instance of SMESH_Pattern
655 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
656 # @ingroup l2_modif_patterns
657 def GetPattern(self):
658 return SMESH._objref_SMESH_Gen.GetPattern(self)
660 ## Sets number of segments per diagonal of boundary box of geometry by which
661 # default segment length of appropriate 1D hypotheses is defined.
662 # Default value is 10
663 # @ingroup l1_auxiliary
664 def SetBoundaryBoxSegmentation(self, nbSegments):
665 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
667 # Filtering. Auxiliary functions:
668 # ------------------------------
670 ## Creates an empty criterion
671 # @return SMESH.Filter.Criterion
672 # @ingroup l1_controls
673 def GetEmptyCriterion(self):
674 Type = self.EnumToLong(FT_Undefined)
675 Compare = self.EnumToLong(FT_Undefined)
679 UnaryOp = self.EnumToLong(FT_Undefined)
680 BinaryOp = self.EnumToLong(FT_Undefined)
683 Precision = -1 ##@1e-07
684 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
685 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
687 ## Creates a criterion by the given parameters
688 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
689 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
690 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
691 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
692 # @param Threshold the threshold value (range of ids as string, shape, numeric)
693 # @param UnaryOp FT_LogicalNOT or FT_Undefined
694 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
695 # FT_Undefined (must be for the last criterion of all criteria)
696 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
697 # FT_LyingOnGeom, FT_CoplanarFaces criteria
698 # @return SMESH.Filter.Criterion
700 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
701 # @ingroup l1_controls
702 def GetCriterion(self,elementType,
704 Compare = FT_EqualTo,
706 UnaryOp=FT_Undefined,
707 BinaryOp=FT_Undefined,
709 if not CritType in SMESH.FunctorType._items:
710 raise TypeError, "CritType should be of SMESH.FunctorType"
711 aCriterion = self.GetEmptyCriterion()
712 aCriterion.TypeOfElement = elementType
713 aCriterion.Type = self.EnumToLong(CritType)
714 aCriterion.Tolerance = Tolerance
716 aThreshold = Threshold
718 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
719 aCriterion.Compare = self.EnumToLong(Compare)
720 elif Compare == "=" or Compare == "==":
721 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
723 aCriterion.Compare = self.EnumToLong(FT_LessThan)
725 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
726 elif Compare != FT_Undefined:
727 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
730 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
731 FT_BelongToCylinder, FT_LyingOnGeom]:
732 # Checks that Threshold is GEOM object
733 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
734 aCriterion.ThresholdStr = GetName(aThreshold)
735 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
736 if not aCriterion.ThresholdID:
737 name = aCriterion.ThresholdStr
739 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
740 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
741 # or a name of GEOM object
742 elif isinstance( aThreshold, str ):
743 aCriterion.ThresholdStr = aThreshold
745 print "Error: The Threshold should be a shape."
747 if isinstance(UnaryOp,float):
748 aCriterion.Tolerance = UnaryOp
749 UnaryOp = FT_Undefined
751 elif CritType == FT_RangeOfIds:
752 # Checks that Threshold is string
753 if isinstance(aThreshold, str):
754 aCriterion.ThresholdStr = aThreshold
756 print "Error: The Threshold should be a string."
758 elif CritType == FT_CoplanarFaces:
759 # Checks the Threshold
760 if isinstance(aThreshold, int):
761 aCriterion.ThresholdID = str(aThreshold)
762 elif isinstance(aThreshold, str):
765 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
766 aCriterion.ThresholdID = aThreshold
769 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
770 elif CritType == FT_ConnectedElements:
771 # Checks the Threshold
772 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
773 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
774 if not aCriterion.ThresholdID:
775 name = aThreshold.GetName()
777 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
778 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
779 elif isinstance(aThreshold, int): # node id
780 aCriterion.Threshold = aThreshold
781 elif isinstance(aThreshold, list): # 3 point coordinates
782 if len( aThreshold ) < 3:
783 raise ValueError, "too few point coordinates, must be 3"
784 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
785 elif isinstance(aThreshold, str):
786 if aThreshold.isdigit():
787 aCriterion.Threshold = aThreshold # node id
789 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
792 "The Threshold should either a VERTEX, or a node ID, "\
793 "or a list of point coordinates and not '%s'"%aThreshold
794 elif CritType == FT_ElemGeomType:
795 # Checks the Threshold
797 aCriterion.Threshold = self.EnumToLong(aThreshold)
798 assert( aThreshold in SMESH.GeometryType._items )
800 if isinstance(aThreshold, int):
801 aCriterion.Threshold = aThreshold
803 print "Error: The Threshold should be an integer or SMESH.GeometryType."
807 elif CritType == FT_EntityType:
808 # Checks the Threshold
810 aCriterion.Threshold = self.EnumToLong(aThreshold)
811 assert( aThreshold in SMESH.EntityType._items )
813 if isinstance(aThreshold, int):
814 aCriterion.Threshold = aThreshold
816 print "Error: The Threshold should be an integer or SMESH.EntityType."
821 elif CritType == FT_GroupColor:
822 # Checks the Threshold
824 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
826 print "Error: The threshold value should be of SALOMEDS.Color type"
829 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
830 FT_LinearOrQuadratic, FT_BadOrientedVolume,
831 FT_BareBorderFace, FT_BareBorderVolume,
832 FT_OverConstrainedFace, FT_OverConstrainedVolume,
833 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
834 # At this point the Threshold is unnecessary
835 if aThreshold == FT_LogicalNOT:
836 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
837 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
838 aCriterion.BinaryOp = aThreshold
842 aThreshold = float(aThreshold)
843 aCriterion.Threshold = aThreshold
845 print "Error: The Threshold should be a number."
848 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
849 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
851 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
852 aCriterion.BinaryOp = self.EnumToLong(Threshold)
854 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
855 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
857 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
858 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
862 ## Creates a filter with the given parameters
863 # @param elementType the type of elements in the group
864 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
865 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
866 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
867 # @param UnaryOp FT_LogicalNOT or FT_Undefined
868 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
869 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
870 # @param mesh the mesh to initialize the filter with
871 # @return SMESH_Filter
873 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
874 # @ingroup l1_controls
875 def GetFilter(self,elementType,
876 CritType=FT_Undefined,
879 UnaryOp=FT_Undefined,
882 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
883 aFilterMgr = self.CreateFilterManager()
884 aFilter = aFilterMgr.CreateFilter()
886 aCriteria.append(aCriterion)
887 aFilter.SetCriteria(aCriteria)
889 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
890 else : aFilter.SetMesh( mesh )
891 aFilterMgr.UnRegister()
894 ## Creates a filter from criteria
895 # @param criteria a list of criteria
896 # @param binOp binary operator used when binary operator of criteria is undefined
897 # @return SMESH_Filter
899 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
900 # @ingroup l1_controls
901 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
902 for i in range( len( criteria ) - 1 ):
903 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
904 criteria[i].BinaryOp = self.EnumToLong( binOp )
905 aFilterMgr = self.CreateFilterManager()
906 aFilter = aFilterMgr.CreateFilter()
907 aFilter.SetCriteria(criteria)
908 aFilterMgr.UnRegister()
911 ## Creates a numerical functor by its type
912 # @param theCriterion FT_...; functor type
913 # @return SMESH_NumericalFunctor
914 # @ingroup l1_controls
915 def GetFunctor(self,theCriterion):
916 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
918 aFilterMgr = self.CreateFilterManager()
920 if theCriterion == FT_AspectRatio:
921 functor = aFilterMgr.CreateAspectRatio()
922 elif theCriterion == FT_AspectRatio3D:
923 functor = aFilterMgr.CreateAspectRatio3D()
924 elif theCriterion == FT_Warping:
925 functor = aFilterMgr.CreateWarping()
926 elif theCriterion == FT_MinimumAngle:
927 functor = aFilterMgr.CreateMinimumAngle()
928 elif theCriterion == FT_Taper:
929 functor = aFilterMgr.CreateTaper()
930 elif theCriterion == FT_Skew:
931 functor = aFilterMgr.CreateSkew()
932 elif theCriterion == FT_Area:
933 functor = aFilterMgr.CreateArea()
934 elif theCriterion == FT_Volume3D:
935 functor = aFilterMgr.CreateVolume3D()
936 elif theCriterion == FT_MaxElementLength2D:
937 functor = aFilterMgr.CreateMaxElementLength2D()
938 elif theCriterion == FT_MaxElementLength3D:
939 functor = aFilterMgr.CreateMaxElementLength3D()
940 elif theCriterion == FT_MultiConnection:
941 functor = aFilterMgr.CreateMultiConnection()
942 elif theCriterion == FT_MultiConnection2D:
943 functor = aFilterMgr.CreateMultiConnection2D()
944 elif theCriterion == FT_Length:
945 functor = aFilterMgr.CreateLength()
946 elif theCriterion == FT_Length2D:
947 functor = aFilterMgr.CreateLength2D()
949 print "Error: given parameter is not numerical functor type."
950 aFilterMgr.UnRegister()
953 ## Creates hypothesis
954 # @param theHType mesh hypothesis type (string)
955 # @param theLibName mesh plug-in library name
956 # @return created hypothesis instance
957 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
958 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
960 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
963 # wrap hypothesis methods
964 #print "HYPOTHESIS", theHType
965 for meth_name in dir( hyp.__class__ ):
966 if not meth_name.startswith("Get") and \
967 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
968 method = getattr ( hyp.__class__, meth_name )
970 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
974 ## Gets the mesh statistic
975 # @return dictionary "element type" - "count of elements"
976 # @ingroup l1_meshinfo
977 def GetMeshInfo(self, obj):
978 if isinstance( obj, Mesh ):
981 if hasattr(obj, "GetMeshInfo"):
982 values = obj.GetMeshInfo()
983 for i in range(SMESH.Entity_Last._v):
984 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
988 ## Get minimum distance between two objects
990 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
991 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
993 # @param src1 first source object
994 # @param src2 second source object
995 # @param id1 node/element id from the first source
996 # @param id2 node/element id from the second (or first) source
997 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
998 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
999 # @return minimum distance value
1000 # @sa GetMinDistance()
1001 # @ingroup l1_measurements
1002 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1003 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1007 result = result.value
1010 ## Get measure structure specifying minimum distance data between two objects
1012 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1013 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1015 # @param src1 first source object
1016 # @param src2 second source object
1017 # @param id1 node/element id from the first source
1018 # @param id2 node/element id from the second (or first) source
1019 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1020 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1021 # @return Measure structure or None if input data is invalid
1023 # @ingroup l1_measurements
1024 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1025 if isinstance(src1, Mesh): src1 = src1.mesh
1026 if isinstance(src2, Mesh): src2 = src2.mesh
1027 if src2 is None and id2 != 0: src2 = src1
1028 if not hasattr(src1, "_narrow"): return None
1029 src1 = src1._narrow(SMESH.SMESH_IDSource)
1030 if not src1: return None
1031 unRegister = genObjUnRegister()
1034 e = m.GetMeshEditor()
1036 src1 = e.MakeIDSource([id1], SMESH.FACE)
1038 src1 = e.MakeIDSource([id1], SMESH.NODE)
1039 unRegister.set( src1 )
1041 if hasattr(src2, "_narrow"):
1042 src2 = src2._narrow(SMESH.SMESH_IDSource)
1043 if src2 and id2 != 0:
1045 e = m.GetMeshEditor()
1047 src2 = e.MakeIDSource([id2], SMESH.FACE)
1049 src2 = e.MakeIDSource([id2], SMESH.NODE)
1050 unRegister.set( src2 )
1053 aMeasurements = self.CreateMeasurements()
1054 unRegister.set( aMeasurements )
1055 result = aMeasurements.MinDistance(src1, src2)
1058 ## Get bounding box of the specified object(s)
1059 # @param objects single source object or list of source objects
1060 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1061 # @sa GetBoundingBox()
1062 # @ingroup l1_measurements
1063 def BoundingBox(self, objects):
1064 result = self.GetBoundingBox(objects)
1068 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1071 ## Get measure structure specifying bounding box data of the specified object(s)
1072 # @param objects single source object or list of source objects
1073 # @return Measure structure
1075 # @ingroup l1_measurements
1076 def GetBoundingBox(self, objects):
1077 if isinstance(objects, tuple):
1078 objects = list(objects)
1079 if not isinstance(objects, list):
1083 if isinstance(o, Mesh):
1084 srclist.append(o.mesh)
1085 elif hasattr(o, "_narrow"):
1086 src = o._narrow(SMESH.SMESH_IDSource)
1087 if src: srclist.append(src)
1090 aMeasurements = self.CreateMeasurements()
1091 result = aMeasurements.BoundingBox(srclist)
1092 aMeasurements.UnRegister()
1095 ## Get sum of lengths of all 1D elements in the mesh object.
1096 # @param obj mesh, submesh or group
1097 # @return sum of lengths of all 1D elements
1098 # @ingroup l1_measurements
1099 def GetLength(self, obj):
1100 if isinstance(obj, Mesh): obj = obj.mesh
1101 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1102 aMeasurements = self.CreateMeasurements()
1103 value = aMeasurements.Length(obj)
1104 aMeasurements.UnRegister()
1107 ## Get sum of areas of all 2D elements in the mesh object.
1108 # @param obj mesh, submesh or group
1109 # @return sum of areas of all 2D elements
1110 # @ingroup l1_measurements
1111 def GetArea(self, obj):
1112 if isinstance(obj, Mesh): obj = obj.mesh
1113 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1114 aMeasurements = self.CreateMeasurements()
1115 value = aMeasurements.Area(obj)
1116 aMeasurements.UnRegister()
1119 ## Get sum of volumes of all 3D elements in the mesh object.
1120 # @param obj mesh, submesh or group
1121 # @return sum of volumes of all 3D elements
1122 # @ingroup l1_measurements
1123 def GetVolume(self, obj):
1124 if isinstance(obj, Mesh): obj = obj.mesh
1125 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1126 aMeasurements = self.CreateMeasurements()
1127 value = aMeasurements.Volume(obj)
1128 aMeasurements.UnRegister()
1131 pass # end of class smeshBuilder
1134 #Registering the new proxy for SMESH_Gen
1135 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1137 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1138 # interface to create or load meshes.
1143 # salome.salome_init()
1144 # from salome.smesh import smeshBuilder
1145 # smesh = smeshBuilder.New(theStudy)
1147 # @param study SALOME study, generally obtained by salome.myStudy.
1148 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1149 # @return smeshBuilder instance
1151 def New( study, instance=None):
1153 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1154 interface to create or load meshes.
1158 salome.salome_init()
1159 from salome.smesh import smeshBuilder
1160 smesh = smeshBuilder.New(theStudy)
1163 study SALOME study, generally obtained by salome.myStudy.
1164 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1166 smeshBuilder instance
1174 smeshInst = smeshBuilder()
1175 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1176 smeshInst.init_smesh(study)
1180 # Public class: Mesh
1181 # ==================
1183 ## This class allows defining and managing a mesh.
1184 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1185 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1186 # new nodes and elements and by changing the existing entities), to get information
1187 # about a mesh and to export a mesh into different formats.
1189 __metaclass__ = MeshMeta
1197 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1198 # sets the GUI name of this mesh to \a name.
1199 # @param smeshpyD an instance of smeshBuilder class
1200 # @param geompyD an instance of geomBuilder class
1201 # @param obj Shape to be meshed or SMESH_Mesh object
1202 # @param name Study name of the mesh
1203 # @ingroup l2_construct
1204 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1205 self.smeshpyD=smeshpyD
1206 self.geompyD=geompyD
1211 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1214 # publish geom of mesh (issue 0021122)
1215 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1217 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1218 if studyID != geompyD.myStudyId:
1219 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1222 geo_name = name + " shape"
1224 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1225 geompyD.addToStudy( self.geom, geo_name )
1226 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1228 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1231 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1233 self.smeshpyD.SetName(self.mesh, name)
1235 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1238 self.geom = self.mesh.GetShapeToMesh()
1240 self.editor = self.mesh.GetMeshEditor()
1241 self.functors = [None] * SMESH.FT_Undefined._v
1243 # set self to algoCreator's
1244 for attrName in dir(self):
1245 attr = getattr( self, attrName )
1246 if isinstance( attr, algoCreator ):
1247 #print "algoCreator ", attrName
1248 setattr( self, attrName, attr.copy( self ))
1253 ## Destructor. Clean-up resources
1256 #self.mesh.UnRegister()
1260 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1261 # @param theMesh a SMESH_Mesh object
1262 # @ingroup l2_construct
1263 def SetMesh(self, theMesh):
1264 # do not call Register() as this prevents mesh servant deletion at closing study
1265 #if self.mesh: self.mesh.UnRegister()
1268 #self.mesh.Register()
1269 self.geom = self.mesh.GetShapeToMesh()
1272 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1273 # @return a SMESH_Mesh object
1274 # @ingroup l2_construct
1278 ## Gets the name of the mesh
1279 # @return the name of the mesh as a string
1280 # @ingroup l2_construct
1282 name = GetName(self.GetMesh())
1285 ## Sets a name to the mesh
1286 # @param name a new name of the mesh
1287 # @ingroup l2_construct
1288 def SetName(self, name):
1289 self.smeshpyD.SetName(self.GetMesh(), name)
1291 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1292 # The subMesh object gives access to the IDs of nodes and elements.
1293 # @param geom a geometrical object (shape)
1294 # @param name a name for the submesh
1295 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1296 # @ingroup l2_submeshes
1297 def GetSubMesh(self, geom, name):
1298 AssureGeomPublished( self, geom, name )
1299 submesh = self.mesh.GetSubMesh( geom, name )
1302 ## Returns the shape associated to the mesh
1303 # @return a GEOM_Object
1304 # @ingroup l2_construct
1308 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1309 # @param geom the shape to be meshed (GEOM_Object)
1310 # @ingroup l2_construct
1311 def SetShape(self, geom):
1312 self.mesh = self.smeshpyD.CreateMesh(geom)
1314 ## Loads mesh from the study after opening the study
1318 ## Returns true if the hypotheses are defined well
1319 # @param theSubObject a sub-shape of a mesh shape
1320 # @return True or False
1321 # @ingroup l2_construct
1322 def IsReadyToCompute(self, theSubObject):
1323 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1325 ## Returns errors of hypotheses definition.
1326 # The list of errors is empty if everything is OK.
1327 # @param theSubObject a sub-shape of a mesh shape
1328 # @return a list of errors
1329 # @ingroup l2_construct
1330 def GetAlgoState(self, theSubObject):
1331 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1333 ## Returns a geometrical object on which the given element was built.
1334 # The returned geometrical object, if not nil, is either found in the
1335 # study or published by this method with the given name
1336 # @param theElementID the id of the mesh element
1337 # @param theGeomName the user-defined name of the geometrical object
1338 # @return GEOM::GEOM_Object instance
1339 # @ingroup l2_construct
1340 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1341 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1343 ## Returns the mesh dimension depending on the dimension of the underlying shape
1344 # or, if the mesh is not based on any shape, basing on deimension of elements
1345 # @return mesh dimension as an integer value [0,3]
1346 # @ingroup l1_auxiliary
1347 def MeshDimension(self):
1348 if self.mesh.HasShapeToMesh():
1349 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1350 if len( shells ) > 0 :
1352 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1354 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1359 if self.NbVolumes() > 0: return 3
1360 if self.NbFaces() > 0: return 2
1361 if self.NbEdges() > 0: return 1
1364 ## Evaluates size of prospective mesh on a shape
1365 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1366 # To know predicted number of e.g. edges, inquire it this way
1367 # Evaluate()[ EnumToLong( Entity_Edge )]
1368 def Evaluate(self, geom=0):
1369 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1371 geom = self.mesh.GetShapeToMesh()
1374 return self.smeshpyD.Evaluate(self.mesh, geom)
1377 ## Computes the mesh and returns the status of the computation
1378 # @param geom geomtrical shape on which mesh data should be computed
1379 # @param discardModifs if True and the mesh has been edited since
1380 # a last total re-compute and that may prevent successful partial re-compute,
1381 # then the mesh is cleaned before Compute()
1382 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1383 # @return True or False
1384 # @ingroup l2_construct
1385 def Compute(self, geom=0, discardModifs=False, refresh=False):
1386 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1388 geom = self.mesh.GetShapeToMesh()
1393 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1395 ok = self.smeshpyD.Compute(self.mesh, geom)
1396 except SALOME.SALOME_Exception, ex:
1397 print "Mesh computation failed, exception caught:"
1398 print " ", ex.details.text
1401 print "Mesh computation failed, exception caught:"
1402 traceback.print_exc()
1406 # Treat compute errors
1407 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1408 for err in computeErrors:
1410 if self.mesh.HasShapeToMesh():
1412 mainIOR = salome.orb.object_to_string(geom)
1413 for sname in salome.myStudyManager.GetOpenStudies():
1414 s = salome.myStudyManager.GetStudyByName(sname)
1416 mainSO = s.FindObjectIOR(mainIOR)
1417 if not mainSO: continue
1418 if err.subShapeID == 1:
1419 shapeText = ' on "%s"' % mainSO.GetName()
1420 subIt = s.NewChildIterator(mainSO)
1422 subSO = subIt.Value()
1424 obj = subSO.GetObject()
1425 if not obj: continue
1426 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1428 ids = go.GetSubShapeIndices()
1429 if len(ids) == 1 and ids[0] == err.subShapeID:
1430 shapeText = ' on "%s"' % subSO.GetName()
1433 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1435 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1437 shapeText = " on subshape #%s" % (err.subShapeID)
1439 shapeText = " on subshape #%s" % (err.subShapeID)
1441 stdErrors = ["OK", #COMPERR_OK
1442 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1443 "std::exception", #COMPERR_STD_EXCEPTION
1444 "OCC exception", #COMPERR_OCC_EXCEPTION
1445 "..", #COMPERR_SLM_EXCEPTION
1446 "Unknown exception", #COMPERR_EXCEPTION
1447 "Memory allocation problem", #COMPERR_MEMORY_PB
1448 "Algorithm failed", #COMPERR_ALGO_FAILED
1449 "Unexpected geometry", #COMPERR_BAD_SHAPE
1450 "Warning", #COMPERR_WARNING
1451 "Computation cancelled",#COMPERR_CANCELED
1452 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1454 if err.code < len(stdErrors): errText = stdErrors[err.code]
1456 errText = "code %s" % -err.code
1457 if errText: errText += ". "
1458 errText += err.comment
1459 if allReasons != "":allReasons += "\n"
1461 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1463 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1467 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1469 if err.isGlobalAlgo:
1477 reason = '%s %sD algorithm is missing' % (glob, dim)
1478 elif err.state == HYP_MISSING:
1479 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1480 % (glob, dim, name, dim))
1481 elif err.state == HYP_NOTCONFORM:
1482 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1483 elif err.state == HYP_BAD_PARAMETER:
1484 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1485 % ( glob, dim, name ))
1486 elif err.state == HYP_BAD_GEOMETRY:
1487 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1488 'geometry' % ( glob, dim, name ))
1489 elif err.state == HYP_HIDDEN_ALGO:
1490 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1491 'algorithm of upper dimension generating %sD mesh'
1492 % ( glob, dim, name, glob, dim ))
1494 reason = ("For unknown reason. "
1495 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1497 if allReasons != "":allReasons += "\n"
1498 allReasons += "- " + reason
1500 if not ok or allReasons != "":
1501 msg = '"' + GetName(self.mesh) + '"'
1502 if ok: msg += " has been computed with warnings"
1503 else: msg += " has not been computed"
1504 if allReasons != "": msg += ":"
1509 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1510 smeshgui = salome.ImportComponentGUI("SMESH")
1511 smeshgui.Init(self.mesh.GetStudyId())
1512 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1513 if refresh: salome.sg.updateObjBrowser(1)
1517 ## Return submesh objects list in meshing order
1518 # @return list of list of submesh objects
1519 # @ingroup l2_construct
1520 def GetMeshOrder(self):
1521 return self.mesh.GetMeshOrder()
1523 ## Return submesh objects list in meshing order
1524 # @return list of list of submesh objects
1525 # @ingroup l2_construct
1526 def SetMeshOrder(self, submeshes):
1527 return self.mesh.SetMeshOrder(submeshes)
1529 ## Removes all nodes and elements
1530 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1531 # @ingroup l2_construct
1532 def Clear(self, refresh=False):
1534 if ( salome.sg.hasDesktop() and
1535 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1536 smeshgui = salome.ImportComponentGUI("SMESH")
1537 smeshgui.Init(self.mesh.GetStudyId())
1538 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1539 if refresh: salome.sg.updateObjBrowser(1)
1541 ## Removes all nodes and elements of indicated shape
1542 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1543 # @param geomId the ID of a sub-shape to remove elements on
1544 # @ingroup l2_construct
1545 def ClearSubMesh(self, geomId, refresh=False):
1546 self.mesh.ClearSubMesh(geomId)
1547 if salome.sg.hasDesktop():
1548 smeshgui = salome.ImportComponentGUI("SMESH")
1549 smeshgui.Init(self.mesh.GetStudyId())
1550 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1551 if refresh: salome.sg.updateObjBrowser(1)
1553 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1554 # @param fineness [0.0,1.0] defines mesh fineness
1555 # @return True or False
1556 # @ingroup l3_algos_basic
1557 def AutomaticTetrahedralization(self, fineness=0):
1558 dim = self.MeshDimension()
1560 self.RemoveGlobalHypotheses()
1561 self.Segment().AutomaticLength(fineness)
1563 self.Triangle().LengthFromEdges()
1568 return self.Compute()
1570 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1571 # @param fineness [0.0, 1.0] defines mesh fineness
1572 # @return True or False
1573 # @ingroup l3_algos_basic
1574 def AutomaticHexahedralization(self, fineness=0):
1575 dim = self.MeshDimension()
1576 # assign the hypotheses
1577 self.RemoveGlobalHypotheses()
1578 self.Segment().AutomaticLength(fineness)
1585 return self.Compute()
1587 ## Assigns a hypothesis
1588 # @param hyp a hypothesis to assign
1589 # @param geom a subhape of mesh geometry
1590 # @return SMESH.Hypothesis_Status
1591 # @ingroup l2_hypotheses
1592 def AddHypothesis(self, hyp, geom=0):
1593 if isinstance( hyp, Mesh_Algorithm ):
1594 hyp = hyp.GetAlgorithm()
1599 geom = self.mesh.GetShapeToMesh()
1602 if self.mesh.HasShapeToMesh():
1603 hyp_type = hyp.GetName()
1604 lib_name = hyp.GetLibName()
1605 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1606 if checkAll and geom:
1607 checkAll = geom.GetType() == 37
1608 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1610 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1611 status = self.mesh.AddHypothesis(geom, hyp)
1613 status = HYP_BAD_GEOMETRY,""
1614 hyp_name = GetName( hyp )
1617 geom_name = geom.GetName()
1618 isAlgo = hyp._narrow( SMESH_Algo )
1619 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1622 ## Return True if an algorithm of hypothesis is assigned to a given shape
1623 # @param hyp a hypothesis to check
1624 # @param geom a subhape of mesh geometry
1625 # @return True of False
1626 # @ingroup l2_hypotheses
1627 def IsUsedHypothesis(self, hyp, geom):
1628 if not hyp: # or not geom
1630 if isinstance( hyp, Mesh_Algorithm ):
1631 hyp = hyp.GetAlgorithm()
1633 hyps = self.GetHypothesisList(geom)
1635 if h.GetId() == hyp.GetId():
1639 ## Unassigns a hypothesis
1640 # @param hyp a hypothesis to unassign
1641 # @param geom a sub-shape of mesh geometry
1642 # @return SMESH.Hypothesis_Status
1643 # @ingroup l2_hypotheses
1644 def RemoveHypothesis(self, hyp, geom=0):
1647 if isinstance( hyp, Mesh_Algorithm ):
1648 hyp = hyp.GetAlgorithm()
1654 if self.IsUsedHypothesis( hyp, shape ):
1655 return self.mesh.RemoveHypothesis( shape, hyp )
1656 hypName = GetName( hyp )
1657 geoName = GetName( shape )
1658 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1661 ## Gets the list of hypotheses added on a geometry
1662 # @param geom a sub-shape of mesh geometry
1663 # @return the sequence of SMESH_Hypothesis
1664 # @ingroup l2_hypotheses
1665 def GetHypothesisList(self, geom):
1666 return self.mesh.GetHypothesisList( geom )
1668 ## Removes all global hypotheses
1669 # @ingroup l2_hypotheses
1670 def RemoveGlobalHypotheses(self):
1671 current_hyps = self.mesh.GetHypothesisList( self.geom )
1672 for hyp in current_hyps:
1673 self.mesh.RemoveHypothesis( self.geom, hyp )
1677 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1678 ## allowing to overwrite the file if it exists or add the exported data to its contents
1679 # @param f is the file name
1680 # @param auto_groups boolean parameter for creating/not creating
1681 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1682 # the typical use is auto_groups=false.
1683 # @param version MED format version(MED_V2_1 or MED_V2_2)
1684 # @param overwrite boolean parameter for overwriting/not overwriting the file
1685 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1686 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1687 # - 1D if all mesh nodes lie on OX coordinate axis, or
1688 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1689 # - 3D in the rest cases.
1690 # If @a autoDimension is @c False, the space dimension is always 3.
1691 # @param fields : list of GEOM fields defined on the shape to mesh.
1692 # @param geomAssocFields : each character of this string means a need to export a
1693 # corresponding field; correspondence between fields and characters is following:
1694 # - 'v' stands for _vertices_ field;
1695 # - 'e' stands for _edges_ field;
1696 # - 'f' stands for _faces_ field;
1697 # - 's' stands for _solids_ field.
1698 # @ingroup l2_impexp
1699 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1700 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1701 if meshPart or fields or geomAssocFields:
1702 unRegister = genObjUnRegister()
1703 if isinstance( meshPart, list ):
1704 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1705 unRegister.set( meshPart )
1706 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1707 fields, geomAssocFields)
1709 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1711 ## Exports the mesh in a file in SAUV format
1712 # @param f is the file name
1713 # @param auto_groups boolean parameter for creating/not creating
1714 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1715 # the typical use is auto_groups=false.
1716 # @ingroup l2_impexp
1717 def ExportSAUV(self, f, auto_groups=0):
1718 self.mesh.ExportSAUV(f, auto_groups)
1720 ## Exports the mesh in a file in DAT format
1721 # @param f the file name
1722 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1723 # @ingroup l2_impexp
1724 def ExportDAT(self, f, meshPart=None):
1726 unRegister = genObjUnRegister()
1727 if isinstance( meshPart, list ):
1728 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1729 unRegister.set( meshPart )
1730 self.mesh.ExportPartToDAT( meshPart, f )
1732 self.mesh.ExportDAT(f)
1734 ## Exports the mesh in a file in UNV format
1735 # @param f the file name
1736 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1737 # @ingroup l2_impexp
1738 def ExportUNV(self, f, meshPart=None):
1740 unRegister = genObjUnRegister()
1741 if isinstance( meshPart, list ):
1742 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1743 unRegister.set( meshPart )
1744 self.mesh.ExportPartToUNV( meshPart, f )
1746 self.mesh.ExportUNV(f)
1748 ## Export the mesh in a file in STL format
1749 # @param f the file name
1750 # @param ascii defines the file encoding
1751 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1752 # @ingroup l2_impexp
1753 def ExportSTL(self, f, ascii=1, meshPart=None):
1755 unRegister = genObjUnRegister()
1756 if isinstance( meshPart, list ):
1757 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1758 unRegister.set( meshPart )
1759 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1761 self.mesh.ExportSTL(f, ascii)
1763 ## Exports the mesh in a file in CGNS format
1764 # @param f is the file name
1765 # @param overwrite boolean parameter for overwriting/not overwriting the file
1766 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1767 # @ingroup l2_impexp
1768 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1769 unRegister = genObjUnRegister()
1770 if isinstance( meshPart, list ):
1771 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1772 unRegister.set( meshPart )
1773 if isinstance( meshPart, Mesh ):
1774 meshPart = meshPart.mesh
1776 meshPart = self.mesh
1777 self.mesh.ExportCGNS(meshPart, f, overwrite)
1779 ## Exports the mesh in a file in GMF format.
1780 # GMF files must have .mesh extension for the ASCII format and .meshb for
1781 # the bynary format. Other extensions are not allowed.
1782 # @param f is the file name
1783 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1784 # @ingroup l2_impexp
1785 def ExportGMF(self, f, meshPart=None):
1786 unRegister = genObjUnRegister()
1787 if isinstance( meshPart, list ):
1788 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1789 unRegister.set( meshPart )
1790 if isinstance( meshPart, Mesh ):
1791 meshPart = meshPart.mesh
1793 meshPart = self.mesh
1794 self.mesh.ExportGMF(meshPart, f, True)
1796 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1797 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1798 ## allowing to overwrite the file if it exists or add the exported data to its contents
1799 # @param f the file name
1800 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1801 # @param opt boolean parameter for creating/not creating
1802 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1803 # @param overwrite boolean parameter for overwriting/not overwriting the file
1804 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1805 # - 1D if all mesh nodes lie on OX coordinate axis, or
1806 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1807 # - 3D in the rest cases.
1809 # If @a autoDimension is @c False, the space dimension is always 3.
1810 # @ingroup l2_impexp
1811 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1812 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1814 # Operations with groups:
1815 # ----------------------
1817 ## Creates an empty mesh group
1818 # @param elementType the type of elements in the group
1819 # @param name the name of the mesh group
1820 # @return SMESH_Group
1821 # @ingroup l2_grps_create
1822 def CreateEmptyGroup(self, elementType, name):
1823 return self.mesh.CreateGroup(elementType, name)
1825 ## Creates a mesh group based on the geometric object \a grp
1826 # and gives a \a name, \n if this parameter is not defined
1827 # the name is the same as the geometric group name \n
1828 # Note: Works like GroupOnGeom().
1829 # @param grp a geometric group, a vertex, an edge, a face or a solid
1830 # @param name the name of the mesh group
1831 # @return SMESH_GroupOnGeom
1832 # @ingroup l2_grps_create
1833 def Group(self, grp, name=""):
1834 return self.GroupOnGeom(grp, name)
1836 ## Creates a mesh group based on the geometrical object \a grp
1837 # and gives a \a name, \n if this parameter is not defined
1838 # the name is the same as the geometrical group name
1839 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1840 # @param name the name of the mesh group
1841 # @param typ the type of elements in the group. If not set, it is
1842 # automatically detected by the type of the geometry
1843 # @return SMESH_GroupOnGeom
1844 # @ingroup l2_grps_create
1845 def GroupOnGeom(self, grp, name="", typ=None):
1846 AssureGeomPublished( self, grp, name )
1848 name = grp.GetName()
1850 typ = self._groupTypeFromShape( grp )
1851 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1853 ## Pivate method to get a type of group on geometry
1854 def _groupTypeFromShape( self, shape ):
1855 tgeo = str(shape.GetShapeType())
1856 if tgeo == "VERTEX":
1858 elif tgeo == "EDGE":
1860 elif tgeo == "FACE" or tgeo == "SHELL":
1862 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1864 elif tgeo == "COMPOUND":
1865 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1867 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1868 return self._groupTypeFromShape( sub[0] )
1871 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1874 ## Creates a mesh group with given \a name based on the \a filter which
1875 ## is a special type of group dynamically updating it's contents during
1876 ## mesh modification
1877 # @param typ the type of elements in the group
1878 # @param name the name of the mesh group
1879 # @param filter the filter defining group contents
1880 # @return SMESH_GroupOnFilter
1881 # @ingroup l2_grps_create
1882 def GroupOnFilter(self, typ, name, filter):
1883 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1885 ## Creates a mesh group by the given ids of elements
1886 # @param groupName the name of the mesh group
1887 # @param elementType the type of elements in the group
1888 # @param elemIDs the list of ids
1889 # @return SMESH_Group
1890 # @ingroup l2_grps_create
1891 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1892 group = self.mesh.CreateGroup(elementType, groupName)
1893 if hasattr( elemIDs, "GetIDs" ):
1894 if hasattr( elemIDs, "SetMesh" ):
1895 elemIDs.SetMesh( self.GetMesh() )
1896 group.AddFrom( elemIDs )
1901 ## Creates a mesh group by the given conditions
1902 # @param groupName the name of the mesh group
1903 # @param elementType the type of elements in the group
1904 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1905 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1906 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1907 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1908 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1909 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1910 # @return SMESH_GroupOnFilter
1911 # @ingroup l2_grps_create
1915 CritType=FT_Undefined,
1918 UnaryOp=FT_Undefined,
1920 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1921 group = self.MakeGroupByCriterion(groupName, aCriterion)
1924 ## Creates a mesh group by the given criterion
1925 # @param groupName the name of the mesh group
1926 # @param Criterion the instance of Criterion class
1927 # @return SMESH_GroupOnFilter
1928 # @ingroup l2_grps_create
1929 def MakeGroupByCriterion(self, groupName, Criterion):
1930 return self.MakeGroupByCriteria( groupName, [Criterion] )
1932 ## Creates a mesh group by the given criteria (list of criteria)
1933 # @param groupName the name of the mesh group
1934 # @param theCriteria the list of criteria
1935 # @param binOp binary operator used when binary operator of criteria is undefined
1936 # @return SMESH_GroupOnFilter
1937 # @ingroup l2_grps_create
1938 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1939 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1940 group = self.MakeGroupByFilter(groupName, aFilter)
1943 ## Creates a mesh group by the given filter
1944 # @param groupName the name of the mesh group
1945 # @param theFilter the instance of Filter class
1946 # @return SMESH_GroupOnFilter
1947 # @ingroup l2_grps_create
1948 def MakeGroupByFilter(self, groupName, theFilter):
1949 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1950 #theFilter.SetMesh( self.mesh )
1951 #group.AddFrom( theFilter )
1952 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1956 # @ingroup l2_grps_delete
1957 def RemoveGroup(self, group):
1958 self.mesh.RemoveGroup(group)
1960 ## Removes a group with its contents
1961 # @ingroup l2_grps_delete
1962 def RemoveGroupWithContents(self, group):
1963 self.mesh.RemoveGroupWithContents(group)
1965 ## Gets the list of groups existing in the mesh in the order
1966 # of creation (starting from the oldest one)
1967 # @return a sequence of SMESH_GroupBase
1968 # @ingroup l2_grps_create
1969 def GetGroups(self):
1970 return self.mesh.GetGroups()
1972 ## Gets the number of groups existing in the mesh
1973 # @return the quantity of groups as an integer value
1974 # @ingroup l2_grps_create
1976 return self.mesh.NbGroups()
1978 ## Gets the list of names of groups existing in the mesh
1979 # @return list of strings
1980 # @ingroup l2_grps_create
1981 def GetGroupNames(self):
1982 groups = self.GetGroups()
1984 for group in groups:
1985 names.append(group.GetName())
1988 ## Produces a union of two groups.
1989 # A new group is created. All mesh elements that are
1990 # present in the initial groups are added to the new one
1991 # @return an instance of SMESH_Group
1992 # @ingroup l2_grps_operon
1993 def UnionGroups(self, group1, group2, name):
1994 return self.mesh.UnionGroups(group1, group2, name)
1996 ## Produces a union list of groups.
1997 # New group is created. All mesh elements that are present in
1998 # initial groups are added to the new one
1999 # @return an instance of SMESH_Group
2000 # @ingroup l2_grps_operon
2001 def UnionListOfGroups(self, groups, name):
2002 return self.mesh.UnionListOfGroups(groups, name)
2004 ## Prodices an intersection of two groups.
2005 # A new group is created. All mesh elements that are common
2006 # for the two initial groups are added to the new one.
2007 # @return an instance of SMESH_Group
2008 # @ingroup l2_grps_operon
2009 def IntersectGroups(self, group1, group2, name):
2010 return self.mesh.IntersectGroups(group1, group2, name)
2012 ## Produces an intersection of groups.
2013 # New group is created. All mesh elements that are present in all
2014 # initial groups simultaneously are added to the new one
2015 # @return an instance of SMESH_Group
2016 # @ingroup l2_grps_operon
2017 def IntersectListOfGroups(self, groups, name):
2018 return self.mesh.IntersectListOfGroups(groups, name)
2020 ## Produces a cut of two groups.
2021 # A new group is created. All mesh elements that are present in
2022 # the main group but are not present in the tool group are added to the new one
2023 # @return an instance of SMESH_Group
2024 # @ingroup l2_grps_operon
2025 def CutGroups(self, main_group, tool_group, name):
2026 return self.mesh.CutGroups(main_group, tool_group, name)
2028 ## Produces a cut of groups.
2029 # A new group is created. All mesh elements that are present in main groups
2030 # but do not present in tool groups are added to the new one
2031 # @return an instance of SMESH_Group
2032 # @ingroup l2_grps_operon
2033 def CutListOfGroups(self, main_groups, tool_groups, name):
2034 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2037 # Create a standalone group of entities basing on nodes of other groups.
2038 # \param groups - list of groups, sub-meshes or filters, of any type.
2039 # \param elemType - a type of elements to include to the new group.
2040 # \param name - a name of the new group.
2041 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2042 # basing on number of element nodes common with reference \a groups.
2043 # Meaning of possible values are:
2044 # - SMESH.ALL_NODES - include if all nodes are common,
2045 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2046 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2047 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2048 # \param underlyingOnly - if \c True (default), an element is included to the
2049 # new group provided that it is based on nodes of one element of \a groups.
2050 # @return an instance of SMESH_Group
2051 # @ingroup l2_grps_operon
2052 def CreateDimGroup(self, groups, elemType, name,
2053 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2054 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2056 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2059 ## Convert group on geom into standalone group
2060 # @ingroup l2_grps_delete
2061 def ConvertToStandalone(self, group):
2062 return self.mesh.ConvertToStandalone(group)
2064 # Get some info about mesh:
2065 # ------------------------
2067 ## Returns the log of nodes and elements added or removed
2068 # since the previous clear of the log.
2069 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2070 # @return list of log_block structures:
2075 # @ingroup l1_auxiliary
2076 def GetLog(self, clearAfterGet):
2077 return self.mesh.GetLog(clearAfterGet)
2079 ## Clears the log of nodes and elements added or removed since the previous
2080 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2081 # @ingroup l1_auxiliary
2083 self.mesh.ClearLog()
2085 ## Toggles auto color mode on the object.
2086 # @param theAutoColor the flag which toggles auto color mode.
2087 # @ingroup l1_auxiliary
2088 def SetAutoColor(self, theAutoColor):
2089 self.mesh.SetAutoColor(theAutoColor)
2091 ## Gets flag of object auto color mode.
2092 # @return True or False
2093 # @ingroup l1_auxiliary
2094 def GetAutoColor(self):
2095 return self.mesh.GetAutoColor()
2097 ## Gets the internal ID
2098 # @return integer value, which is the internal Id of the mesh
2099 # @ingroup l1_auxiliary
2101 return self.mesh.GetId()
2104 # @return integer value, which is the study Id of the mesh
2105 # @ingroup l1_auxiliary
2106 def GetStudyId(self):
2107 return self.mesh.GetStudyId()
2109 ## Checks the group names for duplications.
2110 # Consider the maximum group name length stored in MED file.
2111 # @return True or False
2112 # @ingroup l1_auxiliary
2113 def HasDuplicatedGroupNamesMED(self):
2114 return self.mesh.HasDuplicatedGroupNamesMED()
2116 ## Obtains the mesh editor tool
2117 # @return an instance of SMESH_MeshEditor
2118 # @ingroup l1_modifying
2119 def GetMeshEditor(self):
2122 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2123 # can be passed as argument to a method accepting mesh, group or sub-mesh
2124 # @return an instance of SMESH_IDSource
2125 # @ingroup l1_auxiliary
2126 def GetIDSource(self, ids, elemType):
2127 return self.editor.MakeIDSource(ids, elemType)
2130 # Get informations about mesh contents:
2131 # ------------------------------------
2133 ## Gets the mesh stattistic
2134 # @return dictionary type element - count of elements
2135 # @ingroup l1_meshinfo
2136 def GetMeshInfo(self, obj = None):
2137 if not obj: obj = self.mesh
2138 return self.smeshpyD.GetMeshInfo(obj)
2140 ## Returns the number of nodes in the mesh
2141 # @return an integer value
2142 # @ingroup l1_meshinfo
2144 return self.mesh.NbNodes()
2146 ## Returns the number of elements in the mesh
2147 # @return an integer value
2148 # @ingroup l1_meshinfo
2149 def NbElements(self):
2150 return self.mesh.NbElements()
2152 ## Returns the number of 0d elements in the mesh
2153 # @return an integer value
2154 # @ingroup l1_meshinfo
2155 def Nb0DElements(self):
2156 return self.mesh.Nb0DElements()
2158 ## Returns the number of ball discrete elements in the mesh
2159 # @return an integer value
2160 # @ingroup l1_meshinfo
2162 return self.mesh.NbBalls()
2164 ## Returns the number of edges in the mesh
2165 # @return an integer value
2166 # @ingroup l1_meshinfo
2168 return self.mesh.NbEdges()
2170 ## Returns the number of edges with the given order in the mesh
2171 # @param elementOrder the order of elements:
2172 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2173 # @return an integer value
2174 # @ingroup l1_meshinfo
2175 def NbEdgesOfOrder(self, elementOrder):
2176 return self.mesh.NbEdgesOfOrder(elementOrder)
2178 ## Returns the number of faces in the mesh
2179 # @return an integer value
2180 # @ingroup l1_meshinfo
2182 return self.mesh.NbFaces()
2184 ## Returns the number of faces with the given order in the mesh
2185 # @param elementOrder the order of elements:
2186 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2187 # @return an integer value
2188 # @ingroup l1_meshinfo
2189 def NbFacesOfOrder(self, elementOrder):
2190 return self.mesh.NbFacesOfOrder(elementOrder)
2192 ## Returns the number of triangles in the mesh
2193 # @return an integer value
2194 # @ingroup l1_meshinfo
2195 def NbTriangles(self):
2196 return self.mesh.NbTriangles()
2198 ## Returns the number of triangles with the given order in the mesh
2199 # @param elementOrder is the order of elements:
2200 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2201 # @return an integer value
2202 # @ingroup l1_meshinfo
2203 def NbTrianglesOfOrder(self, elementOrder):
2204 return self.mesh.NbTrianglesOfOrder(elementOrder)
2206 ## Returns the number of biquadratic triangles in the mesh
2207 # @return an integer value
2208 # @ingroup l1_meshinfo
2209 def NbBiQuadTriangles(self):
2210 return self.mesh.NbBiQuadTriangles()
2212 ## Returns the number of quadrangles in the mesh
2213 # @return an integer value
2214 # @ingroup l1_meshinfo
2215 def NbQuadrangles(self):
2216 return self.mesh.NbQuadrangles()
2218 ## Returns the number of quadrangles 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 NbQuadranglesOfOrder(self, elementOrder):
2224 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2226 ## Returns the number of biquadratic quadrangles in the mesh
2227 # @return an integer value
2228 # @ingroup l1_meshinfo
2229 def NbBiQuadQuadrangles(self):
2230 return self.mesh.NbBiQuadQuadrangles()
2232 ## Returns the number of polygons in the mesh
2233 # @return an integer value
2234 # @ingroup l1_meshinfo
2235 def NbPolygons(self):
2236 return self.mesh.NbPolygons()
2238 ## Returns the number of volumes in the mesh
2239 # @return an integer value
2240 # @ingroup l1_meshinfo
2241 def NbVolumes(self):
2242 return self.mesh.NbVolumes()
2244 ## Returns the number of volumes with the given order in the mesh
2245 # @param elementOrder the order of elements:
2246 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2247 # @return an integer value
2248 # @ingroup l1_meshinfo
2249 def NbVolumesOfOrder(self, elementOrder):
2250 return self.mesh.NbVolumesOfOrder(elementOrder)
2252 ## Returns the number of tetrahedrons in the mesh
2253 # @return an integer value
2254 # @ingroup l1_meshinfo
2256 return self.mesh.NbTetras()
2258 ## Returns the number of tetrahedrons with the given order in the mesh
2259 # @param elementOrder the order of elements:
2260 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2261 # @return an integer value
2262 # @ingroup l1_meshinfo
2263 def NbTetrasOfOrder(self, elementOrder):
2264 return self.mesh.NbTetrasOfOrder(elementOrder)
2266 ## Returns the number of hexahedrons in the mesh
2267 # @return an integer value
2268 # @ingroup l1_meshinfo
2270 return self.mesh.NbHexas()
2272 ## Returns the number of hexahedrons with the given order in the mesh
2273 # @param elementOrder the order of elements:
2274 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2275 # @return an integer value
2276 # @ingroup l1_meshinfo
2277 def NbHexasOfOrder(self, elementOrder):
2278 return self.mesh.NbHexasOfOrder(elementOrder)
2280 ## Returns the number of triquadratic hexahedrons in the mesh
2281 # @return an integer value
2282 # @ingroup l1_meshinfo
2283 def NbTriQuadraticHexas(self):
2284 return self.mesh.NbTriQuadraticHexas()
2286 ## Returns the number of pyramids in the mesh
2287 # @return an integer value
2288 # @ingroup l1_meshinfo
2289 def NbPyramids(self):
2290 return self.mesh.NbPyramids()
2292 ## Returns the number of pyramids with the given order in the mesh
2293 # @param elementOrder the order of elements:
2294 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2295 # @return an integer value
2296 # @ingroup l1_meshinfo
2297 def NbPyramidsOfOrder(self, elementOrder):
2298 return self.mesh.NbPyramidsOfOrder(elementOrder)
2300 ## Returns the number of prisms in the mesh
2301 # @return an integer value
2302 # @ingroup l1_meshinfo
2304 return self.mesh.NbPrisms()
2306 ## Returns the number of prisms with the given order in the mesh
2307 # @param elementOrder the order of elements:
2308 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2309 # @return an integer value
2310 # @ingroup l1_meshinfo
2311 def NbPrismsOfOrder(self, elementOrder):
2312 return self.mesh.NbPrismsOfOrder(elementOrder)
2314 ## Returns the number of hexagonal prisms in the mesh
2315 # @return an integer value
2316 # @ingroup l1_meshinfo
2317 def NbHexagonalPrisms(self):
2318 return self.mesh.NbHexagonalPrisms()
2320 ## Returns the number of polyhedrons in the mesh
2321 # @return an integer value
2322 # @ingroup l1_meshinfo
2323 def NbPolyhedrons(self):
2324 return self.mesh.NbPolyhedrons()
2326 ## Returns the number of submeshes in the mesh
2327 # @return an integer value
2328 # @ingroup l1_meshinfo
2329 def NbSubMesh(self):
2330 return self.mesh.NbSubMesh()
2332 ## Returns the list of mesh elements IDs
2333 # @return the list of integer values
2334 # @ingroup l1_meshinfo
2335 def GetElementsId(self):
2336 return self.mesh.GetElementsId()
2338 ## Returns the list of IDs of mesh elements with the given type
2339 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2340 # @return list of integer values
2341 # @ingroup l1_meshinfo
2342 def GetElementsByType(self, elementType):
2343 return self.mesh.GetElementsByType(elementType)
2345 ## Returns the list of mesh nodes IDs
2346 # @return the list of integer values
2347 # @ingroup l1_meshinfo
2348 def GetNodesId(self):
2349 return self.mesh.GetNodesId()
2351 # Get the information about mesh elements:
2352 # ------------------------------------
2354 ## Returns the type of mesh element
2355 # @return the value from SMESH::ElementType enumeration
2356 # @ingroup l1_meshinfo
2357 def GetElementType(self, id, iselem):
2358 return self.mesh.GetElementType(id, iselem)
2360 ## Returns the geometric type of mesh element
2361 # @return the value from SMESH::EntityType enumeration
2362 # @ingroup l1_meshinfo
2363 def GetElementGeomType(self, id):
2364 return self.mesh.GetElementGeomType(id)
2366 ## Returns the shape type of mesh element
2367 # @return the value from SMESH::GeometryType enumeration
2368 # @ingroup l1_meshinfo
2369 def GetElementShape(self, id):
2370 return self.mesh.GetElementShape(id)
2372 ## Returns the list of submesh elements IDs
2373 # @param Shape a geom object(sub-shape) IOR
2374 # Shape must be the sub-shape of a ShapeToMesh()
2375 # @return the list of integer values
2376 # @ingroup l1_meshinfo
2377 def GetSubMeshElementsId(self, Shape):
2378 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2379 ShapeID = Shape.GetSubShapeIndices()[0]
2382 return self.mesh.GetSubMeshElementsId(ShapeID)
2384 ## Returns the list of submesh nodes IDs
2385 # @param Shape a geom object(sub-shape) IOR
2386 # Shape must be the sub-shape of a ShapeToMesh()
2387 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2388 # @return the list of integer values
2389 # @ingroup l1_meshinfo
2390 def GetSubMeshNodesId(self, Shape, all):
2391 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2392 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2395 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2397 ## Returns type of elements on given shape
2398 # @param Shape a geom object(sub-shape) IOR
2399 # Shape must be a sub-shape of a ShapeToMesh()
2400 # @return element type
2401 # @ingroup l1_meshinfo
2402 def GetSubMeshElementType(self, Shape):
2403 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2404 ShapeID = Shape.GetSubShapeIndices()[0]
2407 return self.mesh.GetSubMeshElementType(ShapeID)
2409 ## Gets the mesh description
2410 # @return string value
2411 # @ingroup l1_meshinfo
2413 return self.mesh.Dump()
2416 # Get the information about nodes and elements of a mesh by its IDs:
2417 # -----------------------------------------------------------
2419 ## Gets XYZ coordinates of a node
2420 # \n If there is no nodes for the given ID - returns an empty list
2421 # @return a list of double precision values
2422 # @ingroup l1_meshinfo
2423 def GetNodeXYZ(self, id):
2424 return self.mesh.GetNodeXYZ(id)
2426 ## Returns list of IDs of inverse elements for the given node
2427 # \n If there is no node for the given ID - returns an empty list
2428 # @return a list of integer values
2429 # @ingroup l1_meshinfo
2430 def GetNodeInverseElements(self, id):
2431 return self.mesh.GetNodeInverseElements(id)
2433 ## @brief Returns the position of a node on the shape
2434 # @return SMESH::NodePosition
2435 # @ingroup l1_meshinfo
2436 def GetNodePosition(self,NodeID):
2437 return self.mesh.GetNodePosition(NodeID)
2439 ## @brief Returns the position of an element on the shape
2440 # @return SMESH::ElementPosition
2441 # @ingroup l1_meshinfo
2442 def GetElementPosition(self,ElemID):
2443 return self.mesh.GetElementPosition(ElemID)
2445 ## If the given element is a node, returns the ID of shape
2446 # \n If there is no node for the given ID - returns -1
2447 # @return an integer value
2448 # @ingroup l1_meshinfo
2449 def GetShapeID(self, id):
2450 return self.mesh.GetShapeID(id)
2452 ## Returns the ID of the result shape after
2453 # FindShape() from SMESH_MeshEditor for the given element
2454 # \n If there is no element for the given ID - returns -1
2455 # @return an integer value
2456 # @ingroup l1_meshinfo
2457 def GetShapeIDForElem(self,id):
2458 return self.mesh.GetShapeIDForElem(id)
2460 ## Returns the number of nodes for the given element
2461 # \n If there is no element for the given ID - returns -1
2462 # @return an integer value
2463 # @ingroup l1_meshinfo
2464 def GetElemNbNodes(self, id):
2465 return self.mesh.GetElemNbNodes(id)
2467 ## Returns the node ID the given (zero based) index for the given element
2468 # \n If there is no element for the given ID - returns -1
2469 # \n If there is no node for the given index - returns -2
2470 # @return an integer value
2471 # @ingroup l1_meshinfo
2472 def GetElemNode(self, id, index):
2473 return self.mesh.GetElemNode(id, index)
2475 ## Returns the IDs of nodes of the given element
2476 # @return a list of integer values
2477 # @ingroup l1_meshinfo
2478 def GetElemNodes(self, id):
2479 return self.mesh.GetElemNodes(id)
2481 ## Returns true if the given node is the medium node in the given quadratic element
2482 # @ingroup l1_meshinfo
2483 def IsMediumNode(self, elementID, nodeID):
2484 return self.mesh.IsMediumNode(elementID, nodeID)
2486 ## Returns true if the given node is the medium node in one of quadratic elements
2487 # @ingroup l1_meshinfo
2488 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2489 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2491 ## Returns the number of edges for the given element
2492 # @ingroup l1_meshinfo
2493 def ElemNbEdges(self, id):
2494 return self.mesh.ElemNbEdges(id)
2496 ## Returns the number of faces for the given element
2497 # @ingroup l1_meshinfo
2498 def ElemNbFaces(self, id):
2499 return self.mesh.ElemNbFaces(id)
2501 ## Returns nodes of given face (counted from zero) for given volumic element.
2502 # @ingroup l1_meshinfo
2503 def GetElemFaceNodes(self,elemId, faceIndex):
2504 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2506 ## Returns three components of normal of given mesh face
2507 # (or an empty array in KO case)
2508 # @ingroup l1_meshinfo
2509 def GetFaceNormal(self, faceId, normalized=False):
2510 return self.mesh.GetFaceNormal(faceId,normalized)
2512 ## Returns an element based on all given nodes.
2513 # @ingroup l1_meshinfo
2514 def FindElementByNodes(self,nodes):
2515 return self.mesh.FindElementByNodes(nodes)
2517 ## Returns true if the given element is a polygon
2518 # @ingroup l1_meshinfo
2519 def IsPoly(self, id):
2520 return self.mesh.IsPoly(id)
2522 ## Returns true if the given element is quadratic
2523 # @ingroup l1_meshinfo
2524 def IsQuadratic(self, id):
2525 return self.mesh.IsQuadratic(id)
2527 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2528 # @ingroup l1_meshinfo
2529 def GetBallDiameter(self, id):
2530 return self.mesh.GetBallDiameter(id)
2532 ## Returns XYZ coordinates of the barycenter of the given element
2533 # \n If there is no element for the given ID - returns an empty list
2534 # @return a list of three double values
2535 # @ingroup l1_meshinfo
2536 def BaryCenter(self, id):
2537 return self.mesh.BaryCenter(id)
2539 ## Passes mesh elements through the given filter and return IDs of fitting elements
2540 # @param theFilter SMESH_Filter
2541 # @return a list of ids
2542 # @ingroup l1_controls
2543 def GetIdsFromFilter(self, theFilter):
2544 theFilter.SetMesh( self.mesh )
2545 return theFilter.GetIDs()
2547 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2548 # Returns a list of special structures (borders).
2549 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2550 # @ingroup l1_controls
2551 def GetFreeBorders(self):
2552 aFilterMgr = self.smeshpyD.CreateFilterManager()
2553 aPredicate = aFilterMgr.CreateFreeEdges()
2554 aPredicate.SetMesh(self.mesh)
2555 aBorders = aPredicate.GetBorders()
2556 aFilterMgr.UnRegister()
2560 # Get mesh measurements information:
2561 # ------------------------------------
2563 ## Get minimum distance between two nodes, elements or distance to the origin
2564 # @param id1 first node/element id
2565 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2566 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2567 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2568 # @return minimum distance value
2569 # @sa GetMinDistance()
2570 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2571 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2572 return aMeasure.value
2574 ## Get measure structure specifying minimum distance data between two objects
2575 # @param id1 first node/element id
2576 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2577 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2578 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2579 # @return Measure structure
2581 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2583 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2585 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2588 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2590 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2595 aMeasurements = self.smeshpyD.CreateMeasurements()
2596 aMeasure = aMeasurements.MinDistance(id1, id2)
2597 genObjUnRegister([aMeasurements,id1, id2])
2600 ## Get bounding box of the specified object(s)
2601 # @param objects single source object or list of source objects or list of nodes/elements IDs
2602 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2603 # @c False specifies that @a objects are nodes
2604 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2605 # @sa GetBoundingBox()
2606 def BoundingBox(self, objects=None, isElem=False):
2607 result = self.GetBoundingBox(objects, isElem)
2611 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2614 ## Get measure structure specifying bounding box data of the specified object(s)
2615 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2616 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2617 # @c False specifies that @a objects are nodes
2618 # @return Measure structure
2620 def GetBoundingBox(self, IDs=None, isElem=False):
2623 elif isinstance(IDs, tuple):
2625 if not isinstance(IDs, list):
2627 if len(IDs) > 0 and isinstance(IDs[0], int):
2630 unRegister = genObjUnRegister()
2632 if isinstance(o, Mesh):
2633 srclist.append(o.mesh)
2634 elif hasattr(o, "_narrow"):
2635 src = o._narrow(SMESH.SMESH_IDSource)
2636 if src: srclist.append(src)
2638 elif isinstance(o, list):
2640 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2642 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2643 unRegister.set( srclist[-1] )
2646 aMeasurements = self.smeshpyD.CreateMeasurements()
2647 unRegister.set( aMeasurements )
2648 aMeasure = aMeasurements.BoundingBox(srclist)
2651 # Mesh edition (SMESH_MeshEditor functionality):
2652 # ---------------------------------------------
2654 ## Removes the elements from the mesh by ids
2655 # @param IDsOfElements is a list of ids of elements to remove
2656 # @return True or False
2657 # @ingroup l2_modif_del
2658 def RemoveElements(self, IDsOfElements):
2659 return self.editor.RemoveElements(IDsOfElements)
2661 ## Removes nodes from mesh by ids
2662 # @param IDsOfNodes is a list of ids of nodes to remove
2663 # @return True or False
2664 # @ingroup l2_modif_del
2665 def RemoveNodes(self, IDsOfNodes):
2666 return self.editor.RemoveNodes(IDsOfNodes)
2668 ## Removes all orphan (free) nodes from mesh
2669 # @return number of the removed nodes
2670 # @ingroup l2_modif_del
2671 def RemoveOrphanNodes(self):
2672 return self.editor.RemoveOrphanNodes()
2674 ## Add a node to the mesh by coordinates
2675 # @return Id of the new node
2676 # @ingroup l2_modif_add
2677 def AddNode(self, x, y, z):
2678 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2679 if hasVars: self.mesh.SetParameters(Parameters)
2680 return self.editor.AddNode( x, y, z)
2682 ## Creates a 0D element on a node with given number.
2683 # @param IDOfNode the ID of node for creation of the element.
2684 # @return the Id of the new 0D element
2685 # @ingroup l2_modif_add
2686 def Add0DElement(self, IDOfNode):
2687 return self.editor.Add0DElement(IDOfNode)
2689 ## Create 0D elements on all nodes of the given elements except those
2690 # nodes on which a 0D element already exists.
2691 # @param theObject an object on whose nodes 0D elements will be created.
2692 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2693 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2694 # @param theGroupName optional name of a group to add 0D elements created
2695 # and/or found on nodes of \a theObject.
2696 # @return an object (a new group or a temporary SMESH_IDSource) holding
2697 # IDs of new and/or found 0D elements. IDs of 0D elements
2698 # can be retrieved from the returned object by calling GetIDs()
2699 # @ingroup l2_modif_add
2700 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2701 unRegister = genObjUnRegister()
2702 if isinstance( theObject, Mesh ):
2703 theObject = theObject.GetMesh()
2704 if isinstance( theObject, list ):
2705 theObject = self.GetIDSource( theObject, SMESH.ALL )
2706 unRegister.set( theObject )
2707 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2709 ## Creates a ball element on a node with given ID.
2710 # @param IDOfNode the ID of node for creation of the element.
2711 # @param diameter the bal diameter.
2712 # @return the Id of the new ball element
2713 # @ingroup l2_modif_add
2714 def AddBall(self, IDOfNode, diameter):
2715 return self.editor.AddBall( IDOfNode, diameter )
2717 ## Creates a linear or quadratic edge (this is determined
2718 # by the number of given nodes).
2719 # @param IDsOfNodes the list of node IDs for creation of the element.
2720 # The order of nodes in this list should correspond to the description
2721 # of MED. \n This description is located by the following link:
2722 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2723 # @return the Id of the new edge
2724 # @ingroup l2_modif_add
2725 def AddEdge(self, IDsOfNodes):
2726 return self.editor.AddEdge(IDsOfNodes)
2728 ## Creates a linear or quadratic face (this is determined
2729 # by the number of given nodes).
2730 # @param IDsOfNodes the list of node IDs for creation of the element.
2731 # The order of nodes in this list should correspond to the description
2732 # of MED. \n This description is located by the following link:
2733 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2734 # @return the Id of the new face
2735 # @ingroup l2_modif_add
2736 def AddFace(self, IDsOfNodes):
2737 return self.editor.AddFace(IDsOfNodes)
2739 ## Adds a polygonal face to the mesh by the list of node IDs
2740 # @param IdsOfNodes the list of node IDs for creation of the element.
2741 # @return the Id of the new face
2742 # @ingroup l2_modif_add
2743 def AddPolygonalFace(self, IdsOfNodes):
2744 return self.editor.AddPolygonalFace(IdsOfNodes)
2746 ## Creates both simple and quadratic volume (this is determined
2747 # by the number of given nodes).
2748 # @param IDsOfNodes the list of node IDs for creation of the element.
2749 # The order of nodes in this list should correspond to the description
2750 # of MED. \n This description is located by the following link:
2751 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2752 # @return the Id of the new volumic element
2753 # @ingroup l2_modif_add
2754 def AddVolume(self, IDsOfNodes):
2755 return self.editor.AddVolume(IDsOfNodes)
2757 ## Creates a volume of many faces, giving nodes for each face.
2758 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2759 # @param Quantities the list of integer values, Quantities[i]
2760 # gives the quantity of nodes in face number i.
2761 # @return the Id of the new volumic element
2762 # @ingroup l2_modif_add
2763 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2764 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2766 ## Creates a volume of many faces, giving the IDs of the existing faces.
2767 # @param IdsOfFaces the list of face IDs for volume creation.
2769 # Note: The created volume will refer only to the nodes
2770 # of the given faces, not to the faces themselves.
2771 # @return the Id of the new volumic element
2772 # @ingroup l2_modif_add
2773 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2774 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2777 ## @brief Binds a node to a vertex
2778 # @param NodeID a node ID
2779 # @param Vertex a vertex or vertex ID
2780 # @return True if succeed else raises an exception
2781 # @ingroup l2_modif_add
2782 def SetNodeOnVertex(self, NodeID, Vertex):
2783 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2784 VertexID = Vertex.GetSubShapeIndices()[0]
2788 self.editor.SetNodeOnVertex(NodeID, VertexID)
2789 except SALOME.SALOME_Exception, inst:
2790 raise ValueError, inst.details.text
2794 ## @brief Stores the node position on an edge
2795 # @param NodeID a node ID
2796 # @param Edge an edge or edge ID
2797 # @param paramOnEdge a parameter on the edge where the node is located
2798 # @return True if succeed else raises an exception
2799 # @ingroup l2_modif_add
2800 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2801 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2802 EdgeID = Edge.GetSubShapeIndices()[0]
2806 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2807 except SALOME.SALOME_Exception, inst:
2808 raise ValueError, inst.details.text
2811 ## @brief Stores node position on a face
2812 # @param NodeID a node ID
2813 # @param Face a face or face ID
2814 # @param u U parameter on the face where the node is located
2815 # @param v V parameter on the face where the node is located
2816 # @return True if succeed else raises an exception
2817 # @ingroup l2_modif_add
2818 def SetNodeOnFace(self, NodeID, Face, u, v):
2819 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2820 FaceID = Face.GetSubShapeIndices()[0]
2824 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2825 except SALOME.SALOME_Exception, inst:
2826 raise ValueError, inst.details.text
2829 ## @brief Binds a node to a solid
2830 # @param NodeID a node ID
2831 # @param Solid a solid or solid ID
2832 # @return True if succeed else raises an exception
2833 # @ingroup l2_modif_add
2834 def SetNodeInVolume(self, NodeID, Solid):
2835 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2836 SolidID = Solid.GetSubShapeIndices()[0]
2840 self.editor.SetNodeInVolume(NodeID, SolidID)
2841 except SALOME.SALOME_Exception, inst:
2842 raise ValueError, inst.details.text
2845 ## @brief Bind an element to a shape
2846 # @param ElementID an element ID
2847 # @param Shape a shape or shape ID
2848 # @return True if succeed else raises an exception
2849 # @ingroup l2_modif_add
2850 def SetMeshElementOnShape(self, ElementID, Shape):
2851 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2852 ShapeID = Shape.GetSubShapeIndices()[0]
2856 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2857 except SALOME.SALOME_Exception, inst:
2858 raise ValueError, inst.details.text
2862 ## Moves the node with the given id
2863 # @param NodeID the id of the node
2864 # @param x a new X coordinate
2865 # @param y a new Y coordinate
2866 # @param z a new Z coordinate
2867 # @return True if succeed else False
2868 # @ingroup l2_modif_movenode
2869 def MoveNode(self, NodeID, x, y, z):
2870 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2871 if hasVars: self.mesh.SetParameters(Parameters)
2872 return self.editor.MoveNode(NodeID, x, y, z)
2874 ## Finds the node closest to a point and moves it to a point location
2875 # @param x the X coordinate of a point
2876 # @param y the Y coordinate of a point
2877 # @param z the Z coordinate of a point
2878 # @param NodeID if specified (>0), the node with this ID is moved,
2879 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2880 # @return the ID of a node
2881 # @ingroup l2_modif_throughp
2882 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2883 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2884 if hasVars: self.mesh.SetParameters(Parameters)
2885 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2887 ## Finds the node closest to a point
2888 # @param x the X coordinate of a point
2889 # @param y the Y coordinate of a point
2890 # @param z the Z coordinate of a point
2891 # @return the ID of a node
2892 # @ingroup l2_modif_throughp
2893 def FindNodeClosestTo(self, x, y, z):
2894 #preview = self.mesh.GetMeshEditPreviewer()
2895 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2896 return self.editor.FindNodeClosestTo(x, y, z)
2898 ## Finds the elements where a point lays IN or ON
2899 # @param x the X coordinate of a point
2900 # @param y the Y coordinate of a point
2901 # @param z the Z coordinate of a point
2902 # @param elementType type of elements to find (SMESH.ALL type
2903 # means elements of any type excluding nodes, discrete and 0D elements)
2904 # @param meshPart a part of mesh (group, sub-mesh) to search within
2905 # @return list of IDs of found elements