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):
166 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
167 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
169 SMESH.AxisStruct.__init__ = __initAxisStruct
171 smeshPrecisionConfusion = 1.e-07
172 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
173 if abs(val1 - val2) < tol:
183 if isinstance(obj, SALOMEDS._objref_SObject):
187 ior = salome.orb.object_to_string(obj)
192 studies = salome.myStudyManager.GetOpenStudies()
193 for sname in studies:
194 s = salome.myStudyManager.GetStudyByName(sname)
196 sobj = s.FindObjectIOR(ior)
197 if not sobj: continue
198 return sobj.GetName()
199 if hasattr(obj, "GetName"):
200 # unknown CORBA object, having GetName() method
203 # unknown CORBA object, no GetName() method
206 if hasattr(obj, "GetName"):
207 # unknown non-CORBA object, having GetName() method
210 raise RuntimeError, "Null or invalid object"
212 ## Prints error message if a hypothesis was not assigned.
213 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
215 hypType = "algorithm"
217 hypType = "hypothesis"
220 if hasattr( status, "__getitem__" ):
221 status,reason = status[0],status[1]
222 if status == HYP_UNKNOWN_FATAL :
223 reason = "for unknown reason"
224 elif status == HYP_INCOMPATIBLE :
225 reason = "this hypothesis mismatches the algorithm"
226 elif status == HYP_NOTCONFORM :
227 reason = "a non-conform mesh would be built"
228 elif status == HYP_ALREADY_EXIST :
229 if isAlgo: return # it does not influence anything
230 reason = hypType + " of the same dimension is already assigned to this shape"
231 elif status == HYP_BAD_DIM :
232 reason = hypType + " mismatches the shape"
233 elif status == HYP_CONCURENT :
234 reason = "there are concurrent hypotheses on sub-shapes"
235 elif status == HYP_BAD_SUBSHAPE :
236 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
237 elif status == HYP_BAD_GEOMETRY:
238 reason = "geometry mismatches the expectation of the algorithm"
239 elif status == HYP_HIDDEN_ALGO:
240 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
241 elif status == HYP_HIDING_ALGO:
242 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
243 elif status == HYP_NEED_SHAPE:
244 reason = "algorithm can't work without shape"
245 elif status == HYP_INCOMPAT_HYPS:
251 where = '"%s"' % geomName
253 meshName = GetName( mesh )
254 if meshName and meshName != NO_NAME:
255 where = '"%s" in "%s"' % ( geomName, meshName )
256 if status < HYP_UNKNOWN_FATAL and where:
257 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
259 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
261 print '"%s" was not assigned : %s' %( hypName, reason )
264 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
265 def AssureGeomPublished(mesh, geom, name=''):
266 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
268 if not geom.GetStudyEntry() and \
269 mesh.smeshpyD.GetCurrentStudy():
271 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
272 if studyID != mesh.geompyD.myStudyId:
273 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
275 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
276 # for all groups SubShapeName() returns "Compound_-1"
277 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
279 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
281 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
284 ## Return the first vertex of a geometrical edge by ignoring orientation
285 def FirstVertexOnCurve(mesh, edge):
286 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
288 raise TypeError, "Given object has no vertices"
289 if len( vv ) == 1: return vv[0]
290 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
291 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
292 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
293 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
296 dist1 += abs( xyz[i] - xyz1[i] )
297 dist2 += abs( xyz[i] - xyz2[i] )
303 # end of l1_auxiliary
307 # Warning: smeshInst is a singleton
313 ## This class allows to create, load or manipulate meshes
314 # It has a set of methods to create load or copy meshes, to combine several meshes.
315 # It also has methods to get infos on meshes.
316 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
318 # MirrorType enumeration
319 POINT = SMESH_MeshEditor.POINT
320 AXIS = SMESH_MeshEditor.AXIS
321 PLANE = SMESH_MeshEditor.PLANE
323 # Smooth_Method enumeration
324 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
325 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
327 PrecisionConfusion = smeshPrecisionConfusion
329 # TopAbs_State enumeration
330 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
332 # Methods of splitting a hexahedron into tetrahedra
333 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
339 #print "==== __new__", engine, smeshInst, doLcc
341 if smeshInst is None:
342 # smesh engine is either retrieved from engine, or created
344 # Following test avoids a recursive loop
346 if smeshInst is not None:
347 # smesh engine not created: existing engine found
351 # FindOrLoadComponent called:
352 # 1. CORBA resolution of server
353 # 2. the __new__ method is called again
354 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
355 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
357 # FindOrLoadComponent not called
358 if smeshInst is None:
359 # smeshBuilder instance is created from lcc.FindOrLoadComponent
360 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
361 smeshInst = super(smeshBuilder,cls).__new__(cls)
363 # smesh engine not created: existing engine found
364 #print "==== existing ", engine, smeshInst, doLcc
366 #print "====1 ", smeshInst
369 #print "====2 ", smeshInst
374 #print "--------------- smeshbuilder __init__ ---", created
377 SMESH._objref_SMESH_Gen.__init__(self)
379 ## Dump component to the Python script
380 # This method overrides IDL function to allow default values for the parameters.
381 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
382 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
384 ## Set mode of DumpPython(), \a historical or \a snapshot.
385 # In the \a historical mode, the Python Dump script includes all commands
386 # performed by SMESH engine. In the \a snapshot mode, commands
387 # relating to objects removed from the Study are excluded from the script
388 # as well as commands not influencing the current state of meshes
389 def SetDumpPythonHistorical(self, isHistorical):
390 if isHistorical: val = "true"
392 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
394 ## Sets the current study and Geometry component
395 # @ingroup l1_auxiliary
396 def init_smesh(self,theStudy,geompyD = None):
398 self.SetCurrentStudy(theStudy,geompyD)
401 notebook.myStudy = theStudy
403 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
404 # or a mesh wrapping a CORBA mesh given as a parameter.
405 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
406 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
407 # (2) a Geometrical object for meshing or
409 # @param name the name for the new mesh.
410 # @return an instance of Mesh class.
411 # @ingroup l2_construct
412 def Mesh(self, obj=0, name=0):
413 if isinstance(obj,str):
415 return Mesh(self,self.geompyD,obj,name)
417 ## Returns a long value from enumeration
418 # @ingroup l1_controls
419 def EnumToLong(self,theItem):
422 ## Returns a string representation of the color.
423 # To be used with filters.
424 # @param c color value (SALOMEDS.Color)
425 # @ingroup l1_controls
426 def ColorToString(self,c):
428 if isinstance(c, SALOMEDS.Color):
429 val = "%s;%s;%s" % (c.R, c.G, c.B)
430 elif isinstance(c, str):
433 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
436 ## Gets PointStruct from vertex
437 # @param theVertex a GEOM object(vertex)
438 # @return SMESH.PointStruct
439 # @ingroup l1_auxiliary
440 def GetPointStruct(self,theVertex):
441 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
442 return PointStruct(x,y,z)
444 ## Gets DirStruct from vector
445 # @param theVector a GEOM object(vector)
446 # @return SMESH.DirStruct
447 # @ingroup l1_auxiliary
448 def GetDirStruct(self,theVector):
449 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
450 if(len(vertices) != 2):
451 print "Error: vector object is incorrect."
453 p1 = self.geompyD.PointCoordinates(vertices[0])
454 p2 = self.geompyD.PointCoordinates(vertices[1])
455 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
456 dirst = DirStruct(pnt)
459 ## Makes DirStruct from a triplet
460 # @param x,y,z vector components
461 # @return SMESH.DirStruct
462 # @ingroup l1_auxiliary
463 def MakeDirStruct(self,x,y,z):
464 pnt = PointStruct(x,y,z)
465 return DirStruct(pnt)
467 ## Get AxisStruct from object
468 # @param theObj a GEOM object (line or plane)
469 # @return SMESH.AxisStruct
470 # @ingroup l1_auxiliary
471 def GetAxisStruct(self,theObj):
473 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
476 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
477 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
478 vertex1 = self.geompyD.PointCoordinates(vertex1)
479 vertex2 = self.geompyD.PointCoordinates(vertex2)
480 vertex3 = self.geompyD.PointCoordinates(vertex3)
481 vertex4 = self.geompyD.PointCoordinates(vertex4)
482 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
483 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
484 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] ]
485 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
486 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
487 elif len(edges) == 1:
488 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
489 p1 = self.geompyD.PointCoordinates( vertex1 )
490 p2 = self.geompyD.PointCoordinates( vertex2 )
491 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
492 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
493 elif theObj.GetShapeType() == GEOM.VERTEX:
494 x,y,z = self.geompyD.PointCoordinates( theObj )
495 axis = AxisStruct( x,y,z, 1,0,0,)
496 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
499 # From SMESH_Gen interface:
500 # ------------------------
502 ## Sets the given name to the object
503 # @param obj the object to rename
504 # @param name a new object name
505 # @ingroup l1_auxiliary
506 def SetName(self, obj, name):
507 if isinstance( obj, Mesh ):
509 elif isinstance( obj, Mesh_Algorithm ):
510 obj = obj.GetAlgorithm()
511 ior = salome.orb.object_to_string(obj)
512 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
514 ## Sets the current mode
515 # @ingroup l1_auxiliary
516 def SetEmbeddedMode( self,theMode ):
517 #self.SetEmbeddedMode(theMode)
518 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
520 ## Gets the current mode
521 # @ingroup l1_auxiliary
522 def IsEmbeddedMode(self):
523 #return self.IsEmbeddedMode()
524 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
526 ## Sets the current study. Calling SetCurrentStudy( None ) allows to
527 # switch OFF automatic pubilishing in the Study of mesh objects.
528 # @ingroup l1_auxiliary
529 def SetCurrentStudy( self, theStudy, geompyD = None ):
530 #self.SetCurrentStudy(theStudy)
532 from salome.geom import geomBuilder
533 geompyD = geomBuilder.geom
536 self.SetGeomEngine(geompyD)
537 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
540 notebook = salome_notebook.NoteBook( theStudy )
542 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
544 sb = theStudy.NewBuilder()
545 sc = theStudy.FindComponent("SMESH")
546 if sc: sb.LoadWith(sc, self)
550 ## Gets the current study
551 # @ingroup l1_auxiliary
552 def GetCurrentStudy(self):
553 #return self.GetCurrentStudy()
554 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
556 ## Creates a Mesh object importing data from the given UNV file
557 # @return an instance of Mesh class
559 def CreateMeshesFromUNV( self,theFileName ):
560 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
561 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
564 ## Creates a Mesh object(s) importing data from the given MED file
565 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
567 def CreateMeshesFromMED( self,theFileName ):
568 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
569 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
570 return aMeshes, aStatus
572 ## Creates a Mesh object(s) importing data from the given SAUV file
573 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
575 def CreateMeshesFromSAUV( self,theFileName ):
576 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
577 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
578 return aMeshes, aStatus
580 ## Creates a Mesh object importing data from the given STL file
581 # @return an instance of Mesh class
583 def CreateMeshesFromSTL( self, theFileName ):
584 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
585 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
588 ## Creates Mesh objects importing data from the given CGNS file
589 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
591 def CreateMeshesFromCGNS( self, theFileName ):
592 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
593 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
594 return aMeshes, aStatus
596 ## Creates a Mesh object importing data from the given GMF file.
597 # GMF files must have .mesh extension for the ASCII format and .meshb for
599 # @return [ an instance of Mesh class, SMESH.ComputeError ]
601 def CreateMeshesFromGMF( self, theFileName ):
602 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
605 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
606 return Mesh(self, self.geompyD, aSmeshMesh), error
608 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
609 # present in the new mesh.
610 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
611 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
612 # @param mergeNodesAndElements if true, equal nodes and elements are merged
613 # @param mergeTolerance tolerance for merging nodes
614 # @param allGroups forces creation of groups corresponding to every input mesh
615 # @param name name of a new mesh
616 # @return an instance of Mesh class
617 def Concatenate( self, meshes, uniteIdenticalGroups,
618 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
620 if not meshes: return None
621 for i,m in enumerate(meshes):
622 if isinstance(m, Mesh):
623 meshes[i] = m.GetMesh()
624 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
625 meshes[0].SetParameters(Parameters)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
630 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
635 ## Create a mesh by copying a part of another mesh.
636 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
637 # to copy nodes or elements not contained in any mesh object,
638 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
639 # @param meshName a name of the new mesh
640 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
641 # @param toKeepIDs to preserve order of the copied elements or not
642 # @return an instance of Mesh class
643 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
644 if (isinstance( meshPart, Mesh )):
645 meshPart = meshPart.GetMesh()
646 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
647 return Mesh(self, self.geompyD, mesh)
649 ## From SMESH_Gen interface
650 # @return the list of integer values
651 # @ingroup l1_auxiliary
652 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
653 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
655 ## From SMESH_Gen interface. Creates a pattern
656 # @return an instance of SMESH_Pattern
658 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
659 # @ingroup l2_modif_patterns
660 def GetPattern(self):
661 return SMESH._objref_SMESH_Gen.GetPattern(self)
663 ## Sets number of segments per diagonal of boundary box of geometry by which
664 # default segment length of appropriate 1D hypotheses is defined.
665 # Default value is 10
666 # @ingroup l1_auxiliary
667 def SetBoundaryBoxSegmentation(self, nbSegments):
668 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
670 # Filtering. Auxiliary functions:
671 # ------------------------------
673 ## Creates an empty criterion
674 # @return SMESH.Filter.Criterion
675 # @ingroup l1_controls
676 def GetEmptyCriterion(self):
677 Type = self.EnumToLong(FT_Undefined)
678 Compare = self.EnumToLong(FT_Undefined)
682 UnaryOp = self.EnumToLong(FT_Undefined)
683 BinaryOp = self.EnumToLong(FT_Undefined)
686 Precision = -1 ##@1e-07
687 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
688 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
690 ## Creates a criterion by the given parameters
691 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
692 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
693 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
694 # Type SMESH.FunctorType._items in the Python Console to see all values.
695 # Note that the items starting from FT_LessThan are not suitable for CritType.
696 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
697 # @param Threshold the threshold value (range of ids as string, shape, numeric)
698 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
699 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
701 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
702 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
703 # @return SMESH.Filter.Criterion
705 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
706 # @ingroup l1_controls
707 def GetCriterion(self,elementType,
709 Compare = FT_EqualTo,
711 UnaryOp=FT_Undefined,
712 BinaryOp=FT_Undefined,
714 if not CritType in SMESH.FunctorType._items:
715 raise TypeError, "CritType should be of SMESH.FunctorType"
716 aCriterion = self.GetEmptyCriterion()
717 aCriterion.TypeOfElement = elementType
718 aCriterion.Type = self.EnumToLong(CritType)
719 aCriterion.Tolerance = Tolerance
721 aThreshold = Threshold
723 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
724 aCriterion.Compare = self.EnumToLong(Compare)
725 elif Compare == "=" or Compare == "==":
726 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
728 aCriterion.Compare = self.EnumToLong(FT_LessThan)
730 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
731 elif Compare != FT_Undefined:
732 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
735 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
736 FT_BelongToCylinder, FT_LyingOnGeom]:
737 # Check that Threshold is GEOM object
738 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
739 aCriterion.ThresholdStr = GetName(aThreshold)
740 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
741 if not aCriterion.ThresholdID:
742 name = aCriterion.ThresholdStr
744 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
745 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
746 # or a name of GEOM object
747 elif isinstance( aThreshold, str ):
748 aCriterion.ThresholdStr = aThreshold
750 raise TypeError, "The Threshold should be a shape."
751 if isinstance(UnaryOp,float):
752 aCriterion.Tolerance = UnaryOp
753 UnaryOp = FT_Undefined
755 elif CritType == FT_BelongToMeshGroup:
756 # Check that Threshold is a group
757 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
758 if aThreshold.GetType() != elementType:
759 raise ValueError, "Group type mismatches Element type"
760 aCriterion.ThresholdStr = aThreshold.GetName()
761 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
762 study = self.GetCurrentStudy()
764 so = study.FindObjectIOR( aCriterion.ThresholdID )
768 aCriterion.ThresholdID = entry
770 raise TypeError, "The Threshold should be a Mesh Group"
771 elif CritType == FT_RangeOfIds:
772 # Check that Threshold is string
773 if isinstance(aThreshold, str):
774 aCriterion.ThresholdStr = aThreshold
776 raise TypeError, "The Threshold should be a string."
777 elif CritType == FT_CoplanarFaces:
778 # Check the Threshold
779 if isinstance(aThreshold, int):
780 aCriterion.ThresholdID = str(aThreshold)
781 elif isinstance(aThreshold, str):
784 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
785 aCriterion.ThresholdID = aThreshold
788 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
789 elif CritType == FT_ConnectedElements:
790 # Check the Threshold
791 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
792 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
793 if not aCriterion.ThresholdID:
794 name = aThreshold.GetName()
796 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
797 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
798 elif isinstance(aThreshold, int): # node id
799 aCriterion.Threshold = aThreshold
800 elif isinstance(aThreshold, list): # 3 point coordinates
801 if len( aThreshold ) < 3:
802 raise ValueError, "too few point coordinates, must be 3"
803 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
804 elif isinstance(aThreshold, str):
805 if aThreshold.isdigit():
806 aCriterion.Threshold = aThreshold # node id
808 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
811 "The Threshold should either a VERTEX, or a node ID, "\
812 "or a list of point coordinates and not '%s'"%aThreshold
813 elif CritType == FT_ElemGeomType:
814 # Check the Threshold
816 aCriterion.Threshold = self.EnumToLong(aThreshold)
817 assert( aThreshold in SMESH.GeometryType._items )
819 if isinstance(aThreshold, int):
820 aCriterion.Threshold = aThreshold
822 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
825 elif CritType == FT_EntityType:
826 # Check the Threshold
828 aCriterion.Threshold = self.EnumToLong(aThreshold)
829 assert( aThreshold in SMESH.EntityType._items )
831 if isinstance(aThreshold, int):
832 aCriterion.Threshold = aThreshold
834 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
838 elif CritType == FT_GroupColor:
839 # Check the Threshold
841 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
843 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
845 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
846 FT_LinearOrQuadratic, FT_BadOrientedVolume,
847 FT_BareBorderFace, FT_BareBorderVolume,
848 FT_OverConstrainedFace, FT_OverConstrainedVolume,
849 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
850 # At this point the Threshold is unnecessary
851 if aThreshold == FT_LogicalNOT:
852 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
853 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
854 aCriterion.BinaryOp = aThreshold
858 aThreshold = float(aThreshold)
859 aCriterion.Threshold = aThreshold
861 raise TypeError, "The Threshold should be a number."
864 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
865 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
867 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
868 aCriterion.BinaryOp = self.EnumToLong(Threshold)
870 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
871 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
873 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
874 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
878 ## Creates a filter with the given parameters
879 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
880 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
881 # Type SMESH.FunctorType._items in the Python Console to see all values.
882 # Note that the items starting from FT_LessThan are not suitable for CritType.
883 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
884 # @param Threshold the threshold value (range of ids as string, shape, numeric)
885 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
886 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
887 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
888 # @param mesh the mesh to initialize the filter with
889 # @return SMESH_Filter
891 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
892 # @ingroup l1_controls
893 def GetFilter(self,elementType,
894 CritType=FT_Undefined,
897 UnaryOp=FT_Undefined,
900 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
901 aFilterMgr = self.CreateFilterManager()
902 aFilter = aFilterMgr.CreateFilter()
904 aCriteria.append(aCriterion)
905 aFilter.SetCriteria(aCriteria)
907 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
908 else : aFilter.SetMesh( mesh )
909 aFilterMgr.UnRegister()
912 ## Creates a filter from criteria
913 # @param criteria a list of criteria
914 # @param binOp binary operator used when binary operator of criteria is undefined
915 # @return SMESH_Filter
917 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
918 # @ingroup l1_controls
919 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
920 for i in range( len( criteria ) - 1 ):
921 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
922 criteria[i].BinaryOp = self.EnumToLong( binOp )
923 aFilterMgr = self.CreateFilterManager()
924 aFilter = aFilterMgr.CreateFilter()
925 aFilter.SetCriteria(criteria)
926 aFilterMgr.UnRegister()
929 ## Creates a numerical functor by its type
930 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
931 # Type SMESH.FunctorType._items in the Python Console to see all items.
932 # Note that not all items corresponds to numerical functors.
933 # @return SMESH_NumericalFunctor
934 # @ingroup l1_controls
935 def GetFunctor(self,theCriterion):
936 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
938 aFilterMgr = self.CreateFilterManager()
940 if theCriterion == FT_AspectRatio:
941 functor = aFilterMgr.CreateAspectRatio()
942 elif theCriterion == FT_AspectRatio3D:
943 functor = aFilterMgr.CreateAspectRatio3D()
944 elif theCriterion == FT_Warping:
945 functor = aFilterMgr.CreateWarping()
946 elif theCriterion == FT_MinimumAngle:
947 functor = aFilterMgr.CreateMinimumAngle()
948 elif theCriterion == FT_Taper:
949 functor = aFilterMgr.CreateTaper()
950 elif theCriterion == FT_Skew:
951 functor = aFilterMgr.CreateSkew()
952 elif theCriterion == FT_Area:
953 functor = aFilterMgr.CreateArea()
954 elif theCriterion == FT_Volume3D:
955 functor = aFilterMgr.CreateVolume3D()
956 elif theCriterion == FT_MaxElementLength2D:
957 functor = aFilterMgr.CreateMaxElementLength2D()
958 elif theCriterion == FT_MaxElementLength3D:
959 functor = aFilterMgr.CreateMaxElementLength3D()
960 elif theCriterion == FT_MultiConnection:
961 functor = aFilterMgr.CreateMultiConnection()
962 elif theCriterion == FT_MultiConnection2D:
963 functor = aFilterMgr.CreateMultiConnection2D()
964 elif theCriterion == FT_Length:
965 functor = aFilterMgr.CreateLength()
966 elif theCriterion == FT_Length2D:
967 functor = aFilterMgr.CreateLength2D()
969 print "Error: given parameter is not numerical functor type."
970 aFilterMgr.UnRegister()
973 ## Creates hypothesis
974 # @param theHType mesh hypothesis type (string)
975 # @param theLibName mesh plug-in library name
976 # @return created hypothesis instance
977 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
978 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
980 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
983 # wrap hypothesis methods
984 #print "HYPOTHESIS", theHType
985 for meth_name in dir( hyp.__class__ ):
986 if not meth_name.startswith("Get") and \
987 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
988 method = getattr ( hyp.__class__, meth_name )
990 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
994 ## Gets the mesh statistic
995 # @return dictionary "element type" - "count of elements"
996 # @ingroup l1_meshinfo
997 def GetMeshInfo(self, obj):
998 if isinstance( obj, Mesh ):
1001 if hasattr(obj, "GetMeshInfo"):
1002 values = obj.GetMeshInfo()
1003 for i in range(SMESH.Entity_Last._v):
1004 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1008 ## Get minimum distance between two objects
1010 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1011 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1013 # @param src1 first source object
1014 # @param src2 second source object
1015 # @param id1 node/element id from the first source
1016 # @param id2 node/element id from the second (or first) source
1017 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1018 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1019 # @return minimum distance value
1020 # @sa GetMinDistance()
1021 # @ingroup l1_measurements
1022 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1023 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1027 result = result.value
1030 ## Get measure structure specifying minimum distance data between two objects
1032 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1033 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1035 # @param src1 first source object
1036 # @param src2 second source object
1037 # @param id1 node/element id from the first source
1038 # @param id2 node/element id from the second (or first) source
1039 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1040 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1041 # @return Measure structure or None if input data is invalid
1043 # @ingroup l1_measurements
1044 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1045 if isinstance(src1, Mesh): src1 = src1.mesh
1046 if isinstance(src2, Mesh): src2 = src2.mesh
1047 if src2 is None and id2 != 0: src2 = src1
1048 if not hasattr(src1, "_narrow"): return None
1049 src1 = src1._narrow(SMESH.SMESH_IDSource)
1050 if not src1: return None
1051 unRegister = genObjUnRegister()
1054 e = m.GetMeshEditor()
1056 src1 = e.MakeIDSource([id1], SMESH.FACE)
1058 src1 = e.MakeIDSource([id1], SMESH.NODE)
1059 unRegister.set( src1 )
1061 if hasattr(src2, "_narrow"):
1062 src2 = src2._narrow(SMESH.SMESH_IDSource)
1063 if src2 and id2 != 0:
1065 e = m.GetMeshEditor()
1067 src2 = e.MakeIDSource([id2], SMESH.FACE)
1069 src2 = e.MakeIDSource([id2], SMESH.NODE)
1070 unRegister.set( src2 )
1073 aMeasurements = self.CreateMeasurements()
1074 unRegister.set( aMeasurements )
1075 result = aMeasurements.MinDistance(src1, src2)
1078 ## Get bounding box of the specified object(s)
1079 # @param objects single source object or list of source objects
1080 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1081 # @sa GetBoundingBox()
1082 # @ingroup l1_measurements
1083 def BoundingBox(self, objects):
1084 result = self.GetBoundingBox(objects)
1088 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1091 ## Get measure structure specifying bounding box data of the specified object(s)
1092 # @param objects single source object or list of source objects
1093 # @return Measure structure
1095 # @ingroup l1_measurements
1096 def GetBoundingBox(self, objects):
1097 if isinstance(objects, tuple):
1098 objects = list(objects)
1099 if not isinstance(objects, list):
1103 if isinstance(o, Mesh):
1104 srclist.append(o.mesh)
1105 elif hasattr(o, "_narrow"):
1106 src = o._narrow(SMESH.SMESH_IDSource)
1107 if src: srclist.append(src)
1110 aMeasurements = self.CreateMeasurements()
1111 result = aMeasurements.BoundingBox(srclist)
1112 aMeasurements.UnRegister()
1115 ## Get sum of lengths of all 1D elements in the mesh object.
1116 # @param obj mesh, submesh or group
1117 # @return sum of lengths of all 1D elements
1118 # @ingroup l1_measurements
1119 def GetLength(self, obj):
1120 if isinstance(obj, Mesh): obj = obj.mesh
1121 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1122 aMeasurements = self.CreateMeasurements()
1123 value = aMeasurements.Length(obj)
1124 aMeasurements.UnRegister()
1127 ## Get sum of areas of all 2D elements in the mesh object.
1128 # @param obj mesh, submesh or group
1129 # @return sum of areas of all 2D elements
1130 # @ingroup l1_measurements
1131 def GetArea(self, obj):
1132 if isinstance(obj, Mesh): obj = obj.mesh
1133 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1134 aMeasurements = self.CreateMeasurements()
1135 value = aMeasurements.Area(obj)
1136 aMeasurements.UnRegister()
1139 ## Get sum of volumes of all 3D elements in the mesh object.
1140 # @param obj mesh, submesh or group
1141 # @return sum of volumes of all 3D elements
1142 # @ingroup l1_measurements
1143 def GetVolume(self, obj):
1144 if isinstance(obj, Mesh): obj = obj.mesh
1145 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1146 aMeasurements = self.CreateMeasurements()
1147 value = aMeasurements.Volume(obj)
1148 aMeasurements.UnRegister()
1151 pass # end of class smeshBuilder
1154 #Registering the new proxy for SMESH_Gen
1155 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1157 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1158 # interface to create or load meshes.
1163 # salome.salome_init()
1164 # from salome.smesh import smeshBuilder
1165 # smesh = smeshBuilder.New(theStudy)
1167 # @param study SALOME study, generally obtained by salome.myStudy.
1168 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1169 # @return smeshBuilder instance
1171 def New( study, instance=None):
1173 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1174 interface to create or load meshes.
1178 salome.salome_init()
1179 from salome.smesh import smeshBuilder
1180 smesh = smeshBuilder.New(theStudy)
1183 study SALOME study, generally obtained by salome.myStudy.
1184 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1186 smeshBuilder instance
1194 smeshInst = smeshBuilder()
1195 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1196 smeshInst.init_smesh(study)
1200 # Public class: Mesh
1201 # ==================
1203 ## This class allows defining and managing a mesh.
1204 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1205 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1206 # new nodes and elements and by changing the existing entities), to get information
1207 # about a mesh and to export a mesh into different formats.
1209 __metaclass__ = MeshMeta
1217 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1218 # sets the GUI name of this mesh to \a name.
1219 # @param smeshpyD an instance of smeshBuilder class
1220 # @param geompyD an instance of geomBuilder class
1221 # @param obj Shape to be meshed or SMESH_Mesh object
1222 # @param name Study name of the mesh
1223 # @ingroup l2_construct
1224 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1225 self.smeshpyD=smeshpyD
1226 self.geompyD=geompyD
1231 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1234 # publish geom of mesh (issue 0021122)
1235 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1237 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1238 if studyID != geompyD.myStudyId:
1239 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1242 geo_name = name + " shape"
1244 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1245 geompyD.addToStudy( self.geom, geo_name )
1246 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1248 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1251 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1253 self.smeshpyD.SetName(self.mesh, name)
1255 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1258 self.geom = self.mesh.GetShapeToMesh()
1260 self.editor = self.mesh.GetMeshEditor()
1261 self.functors = [None] * SMESH.FT_Undefined._v
1263 # set self to algoCreator's
1264 for attrName in dir(self):
1265 attr = getattr( self, attrName )
1266 if isinstance( attr, algoCreator ):
1267 setattr( self, attrName, attr.copy( self ))
1272 ## Destructor. Clean-up resources
1275 #self.mesh.UnRegister()
1279 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1280 # @param theMesh a SMESH_Mesh object
1281 # @ingroup l2_construct
1282 def SetMesh(self, theMesh):
1283 # do not call Register() as this prevents mesh servant deletion at closing study
1284 #if self.mesh: self.mesh.UnRegister()
1287 #self.mesh.Register()
1288 self.geom = self.mesh.GetShapeToMesh()
1291 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1292 # @return a SMESH_Mesh object
1293 # @ingroup l2_construct
1297 ## Gets the name of the mesh
1298 # @return the name of the mesh as a string
1299 # @ingroup l2_construct
1301 name = GetName(self.GetMesh())
1304 ## Sets a name to the mesh
1305 # @param name a new name of the mesh
1306 # @ingroup l2_construct
1307 def SetName(self, name):
1308 self.smeshpyD.SetName(self.GetMesh(), name)
1310 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1311 # The subMesh object gives access to the IDs of nodes and elements.
1312 # @param geom a geometrical object (shape)
1313 # @param name a name for the submesh
1314 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1315 # @ingroup l2_submeshes
1316 def GetSubMesh(self, geom, name):
1317 AssureGeomPublished( self, geom, name )
1318 submesh = self.mesh.GetSubMesh( geom, name )
1321 ## Returns the shape associated to the mesh
1322 # @return a GEOM_Object
1323 # @ingroup l2_construct
1327 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1328 # @param geom the shape to be meshed (GEOM_Object)
1329 # @ingroup l2_construct
1330 def SetShape(self, geom):
1331 self.mesh = self.smeshpyD.CreateMesh(geom)
1333 ## Loads mesh from the study after opening the study
1337 ## Returns true if the hypotheses are defined well
1338 # @param theSubObject a sub-shape of a mesh shape
1339 # @return True or False
1340 # @ingroup l2_construct
1341 def IsReadyToCompute(self, theSubObject):
1342 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1344 ## Returns errors of hypotheses definition.
1345 # The list of errors is empty if everything is OK.
1346 # @param theSubObject a sub-shape of a mesh shape
1347 # @return a list of errors
1348 # @ingroup l2_construct
1349 def GetAlgoState(self, theSubObject):
1350 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1352 ## Returns a geometrical object on which the given element was built.
1353 # The returned geometrical object, if not nil, is either found in the
1354 # study or published by this method with the given name
1355 # @param theElementID the id of the mesh element
1356 # @param theGeomName the user-defined name of the geometrical object
1357 # @return GEOM::GEOM_Object instance
1358 # @ingroup l2_construct
1359 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1360 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1362 ## Returns the mesh dimension depending on the dimension of the underlying shape
1363 # or, if the mesh is not based on any shape, basing on deimension of elements
1364 # @return mesh dimension as an integer value [0,3]
1365 # @ingroup l1_auxiliary
1366 def MeshDimension(self):
1367 if self.mesh.HasShapeToMesh():
1368 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1369 if len( shells ) > 0 :
1371 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1373 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1378 if self.NbVolumes() > 0: return 3
1379 if self.NbFaces() > 0: return 2
1380 if self.NbEdges() > 0: return 1
1383 ## Evaluates size of prospective mesh on a shape
1384 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1385 # To know predicted number of e.g. edges, inquire it this way
1386 # Evaluate()[ EnumToLong( Entity_Edge )]
1387 def Evaluate(self, geom=0):
1388 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1390 geom = self.mesh.GetShapeToMesh()
1393 return self.smeshpyD.Evaluate(self.mesh, geom)
1396 ## Computes the mesh and returns the status of the computation
1397 # @param geom geomtrical shape on which mesh data should be computed
1398 # @param discardModifs if True and the mesh has been edited since
1399 # a last total re-compute and that may prevent successful partial re-compute,
1400 # then the mesh is cleaned before Compute()
1401 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1402 # @return True or False
1403 # @ingroup l2_construct
1404 def Compute(self, geom=0, discardModifs=False, refresh=False):
1405 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1407 geom = self.mesh.GetShapeToMesh()
1412 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1414 ok = self.smeshpyD.Compute(self.mesh, geom)
1415 except SALOME.SALOME_Exception, ex:
1416 print "Mesh computation failed, exception caught:"
1417 print " ", ex.details.text
1420 print "Mesh computation failed, exception caught:"
1421 traceback.print_exc()
1425 # Treat compute errors
1426 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1427 for err in computeErrors:
1428 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1430 stdErrors = ["OK", #COMPERR_OK
1431 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1432 "std::exception", #COMPERR_STD_EXCEPTION
1433 "OCC exception", #COMPERR_OCC_EXCEPTION
1434 "..", #COMPERR_SLM_EXCEPTION
1435 "Unknown exception", #COMPERR_EXCEPTION
1436 "Memory allocation problem", #COMPERR_MEMORY_PB
1437 "Algorithm failed", #COMPERR_ALGO_FAILED
1438 "Unexpected geometry", #COMPERR_BAD_SHAPE
1439 "Warning", #COMPERR_WARNING
1440 "Computation cancelled",#COMPERR_CANCELED
1441 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1443 if err.code < len(stdErrors): errText = stdErrors[err.code]
1445 errText = "code %s" % -err.code
1446 if errText: errText += ". "
1447 errText += err.comment
1448 if allReasons != "":allReasons += "\n"
1450 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1452 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1456 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1458 if err.isGlobalAlgo:
1466 reason = '%s %sD algorithm is missing' % (glob, dim)
1467 elif err.state == HYP_MISSING:
1468 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1469 % (glob, dim, name, dim))
1470 elif err.state == HYP_NOTCONFORM:
1471 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1472 elif err.state == HYP_BAD_PARAMETER:
1473 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1474 % ( glob, dim, name ))
1475 elif err.state == HYP_BAD_GEOMETRY:
1476 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1477 'geometry' % ( glob, dim, name ))
1478 elif err.state == HYP_HIDDEN_ALGO:
1479 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1480 'algorithm of upper dimension generating %sD mesh'
1481 % ( glob, dim, name, glob, dim ))
1483 reason = ("For unknown reason. "
1484 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1486 if allReasons != "":allReasons += "\n"
1487 allReasons += "- " + reason
1489 if not ok or allReasons != "":
1490 msg = '"' + GetName(self.mesh) + '"'
1491 if ok: msg += " has been computed with warnings"
1492 else: msg += " has not been computed"
1493 if allReasons != "": msg += ":"
1498 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1499 smeshgui = salome.ImportComponentGUI("SMESH")
1500 smeshgui.Init(self.mesh.GetStudyId())
1501 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1502 if refresh: salome.sg.updateObjBrowser(1)
1506 ## Return a name of a sub-shape by its ID
1507 # @param subShapeID a unique ID of a sub-shape
1508 # @return a string describing the sub-shape; possible variants:
1509 # - "Face_12" (published sub-shape)
1510 # - FACE #3 (not published sub-shape)
1511 # - sub-shape #3 (invalid sub-shape ID)
1512 # - #3 (error in this function)
1513 def GetSubShapeName(self, subShapeID ):
1514 if not self.mesh.HasShapeToMesh():
1518 mainIOR = salome.orb.object_to_string( self.GetShape() )
1519 for sname in salome.myStudyManager.GetOpenStudies():
1520 s = salome.myStudyManager.GetStudyByName(sname)
1522 mainSO = s.FindObjectIOR(mainIOR)
1523 if not mainSO: continue
1525 shapeText = '"%s"' % mainSO.GetName()
1526 subIt = s.NewChildIterator(mainSO)
1528 subSO = subIt.Value()
1530 obj = subSO.GetObject()
1531 if not obj: continue
1532 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1535 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1538 if ids == subShapeID:
1539 shapeText = '"%s"' % subSO.GetName()
1542 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1544 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1546 shapeText = 'sub-shape #%s' % (subShapeID)
1548 shapeText = "#%s" % (subShapeID)
1551 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1552 # error of an algorithm
1553 # @param publish if @c True, the returned groups will be published in the study
1554 # @return a list of GEOM groups each named after a failed algorithm
1555 def GetFailedShapes(self, publish=False):
1558 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1559 for err in computeErrors:
1560 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1561 if not shape: continue
1562 if err.algoName in algo2shapes:
1563 algo2shapes[ err.algoName ].append( shape )
1565 algo2shapes[ err.algoName ] = [ shape ]
1569 for algoName, shapes in algo2shapes.items():
1571 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1572 otherTypeShapes = []
1574 group = self.geompyD.CreateGroup( self.geom, groupType )
1575 for shape in shapes:
1576 if shape.GetShapeType() == shapes[0].GetShapeType():
1577 sameTypeShapes.append( shape )
1579 otherTypeShapes.append( shape )
1580 self.geompyD.UnionList( group, sameTypeShapes )
1582 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1584 group.SetName( algoName )
1585 groups.append( group )
1586 shapes = otherTypeShapes
1589 for group in groups:
1590 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1593 ## Return sub-mesh objects list in meshing order
1594 # @return list of list of submesh objects
1595 # @ingroup l2_construct
1596 def GetMeshOrder(self):
1597 return self.mesh.GetMeshOrder()
1599 ## Set order in which concurrent sub-meshes sould be meshed
1600 # @param list of sub-meshes
1601 # @ingroup l2_construct
1602 def SetMeshOrder(self, submeshes):
1603 return self.mesh.SetMeshOrder(submeshes)
1605 ## Removes all nodes and elements
1606 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1607 # @ingroup l2_construct
1608 def Clear(self, refresh=False):
1610 if ( salome.sg.hasDesktop() and
1611 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1612 smeshgui = salome.ImportComponentGUI("SMESH")
1613 smeshgui.Init(self.mesh.GetStudyId())
1614 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1615 if refresh: salome.sg.updateObjBrowser(1)
1617 ## Removes all nodes and elements of indicated shape
1618 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1619 # @param geomId the ID of a sub-shape to remove elements on
1620 # @ingroup l2_construct
1621 def ClearSubMesh(self, geomId, refresh=False):
1622 self.mesh.ClearSubMesh(geomId)
1623 if salome.sg.hasDesktop():
1624 smeshgui = salome.ImportComponentGUI("SMESH")
1625 smeshgui.Init(self.mesh.GetStudyId())
1626 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1627 if refresh: salome.sg.updateObjBrowser(1)
1629 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1630 # @param fineness [0.0,1.0] defines mesh fineness
1631 # @return True or False
1632 # @ingroup l3_algos_basic
1633 def AutomaticTetrahedralization(self, fineness=0):
1634 dim = self.MeshDimension()
1636 self.RemoveGlobalHypotheses()
1637 self.Segment().AutomaticLength(fineness)
1639 self.Triangle().LengthFromEdges()
1644 return self.Compute()
1646 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1647 # @param fineness [0.0, 1.0] defines mesh fineness
1648 # @return True or False
1649 # @ingroup l3_algos_basic
1650 def AutomaticHexahedralization(self, fineness=0):
1651 dim = self.MeshDimension()
1652 # assign the hypotheses
1653 self.RemoveGlobalHypotheses()
1654 self.Segment().AutomaticLength(fineness)
1661 return self.Compute()
1663 ## Assigns a hypothesis
1664 # @param hyp a hypothesis to assign
1665 # @param geom a subhape of mesh geometry
1666 # @return SMESH.Hypothesis_Status
1667 # @ingroup l2_hypotheses
1668 def AddHypothesis(self, hyp, geom=0):
1669 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1670 hyp, geom = geom, hyp
1671 if isinstance( hyp, Mesh_Algorithm ):
1672 hyp = hyp.GetAlgorithm()
1677 geom = self.mesh.GetShapeToMesh()
1680 if self.mesh.HasShapeToMesh():
1681 hyp_type = hyp.GetName()
1682 lib_name = hyp.GetLibName()
1683 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1684 if checkAll and geom:
1685 checkAll = geom.GetType() == 37
1686 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1688 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1689 status = self.mesh.AddHypothesis(geom, hyp)
1691 status = HYP_BAD_GEOMETRY,""
1692 hyp_name = GetName( hyp )
1695 geom_name = geom.GetName()
1696 isAlgo = hyp._narrow( SMESH_Algo )
1697 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1700 ## Return True if an algorithm of hypothesis is assigned to a given shape
1701 # @param hyp a hypothesis to check
1702 # @param geom a subhape of mesh geometry
1703 # @return True of False
1704 # @ingroup l2_hypotheses
1705 def IsUsedHypothesis(self, hyp, geom):
1706 if not hyp: # or not geom
1708 if isinstance( hyp, Mesh_Algorithm ):
1709 hyp = hyp.GetAlgorithm()
1711 hyps = self.GetHypothesisList(geom)
1713 if h.GetId() == hyp.GetId():
1717 ## Unassigns a hypothesis
1718 # @param hyp a hypothesis to unassign
1719 # @param geom a sub-shape of mesh geometry
1720 # @return SMESH.Hypothesis_Status
1721 # @ingroup l2_hypotheses
1722 def RemoveHypothesis(self, hyp, geom=0):
1725 if isinstance( hyp, Mesh_Algorithm ):
1726 hyp = hyp.GetAlgorithm()
1732 if self.IsUsedHypothesis( hyp, shape ):
1733 return self.mesh.RemoveHypothesis( shape, hyp )
1734 hypName = GetName( hyp )
1735 geoName = GetName( shape )
1736 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1739 ## Gets the list of hypotheses added on a geometry
1740 # @param geom a sub-shape of mesh geometry
1741 # @return the sequence of SMESH_Hypothesis
1742 # @ingroup l2_hypotheses
1743 def GetHypothesisList(self, geom):
1744 return self.mesh.GetHypothesisList( geom )
1746 ## Removes all global hypotheses
1747 # @ingroup l2_hypotheses
1748 def RemoveGlobalHypotheses(self):
1749 current_hyps = self.mesh.GetHypothesisList( self.geom )
1750 for hyp in current_hyps:
1751 self.mesh.RemoveHypothesis( self.geom, hyp )
1755 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1756 ## allowing to overwrite the file if it exists or add the exported data to its contents
1757 # @param f is the file name
1758 # @param auto_groups boolean parameter for creating/not creating
1759 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1760 # the typical use is auto_groups=false.
1761 # @param version MED format version(MED_V2_1 or MED_V2_2)
1762 # @param overwrite boolean parameter for overwriting/not overwriting the file
1763 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1764 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1765 # - 1D if all mesh nodes lie on OX coordinate axis, or
1766 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1767 # - 3D in the rest cases.
1768 # If @a autoDimension is @c False, the space dimension is always 3.
1769 # @param fields : list of GEOM fields defined on the shape to mesh.
1770 # @param geomAssocFields : each character of this string means a need to export a
1771 # corresponding field; correspondence between fields and characters is following:
1772 # - 'v' stands for _vertices_ field;
1773 # - 'e' stands for _edges_ field;
1774 # - 'f' stands for _faces_ field;
1775 # - 's' stands for _solids_ field.
1776 # @ingroup l2_impexp
1777 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1778 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1779 if meshPart or fields or geomAssocFields:
1780 unRegister = genObjUnRegister()
1781 if isinstance( meshPart, list ):
1782 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1783 unRegister.set( meshPart )
1784 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1785 fields, geomAssocFields)
1787 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1789 ## Exports the mesh in a file in SAUV format
1790 # @param f is the file name
1791 # @param auto_groups boolean parameter for creating/not creating
1792 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1793 # the typical use is auto_groups=false.
1794 # @ingroup l2_impexp
1795 def ExportSAUV(self, f, auto_groups=0):
1796 self.mesh.ExportSAUV(f, auto_groups)
1798 ## Exports the mesh in a file in DAT format
1799 # @param f the file name
1800 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1801 # @ingroup l2_impexp
1802 def ExportDAT(self, f, meshPart=None):
1804 unRegister = genObjUnRegister()
1805 if isinstance( meshPart, list ):
1806 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1807 unRegister.set( meshPart )
1808 self.mesh.ExportPartToDAT( meshPart, f )
1810 self.mesh.ExportDAT(f)
1812 ## Exports the mesh in a file in UNV format
1813 # @param f the file name
1814 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1815 # @ingroup l2_impexp
1816 def ExportUNV(self, f, meshPart=None):
1818 unRegister = genObjUnRegister()
1819 if isinstance( meshPart, list ):
1820 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1821 unRegister.set( meshPart )
1822 self.mesh.ExportPartToUNV( meshPart, f )
1824 self.mesh.ExportUNV(f)
1826 ## Export the mesh in a file in STL format
1827 # @param f the file name
1828 # @param ascii defines the file encoding
1829 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1830 # @ingroup l2_impexp
1831 def ExportSTL(self, f, ascii=1, meshPart=None):
1833 unRegister = genObjUnRegister()
1834 if isinstance( meshPart, list ):
1835 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1836 unRegister.set( meshPart )
1837 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1839 self.mesh.ExportSTL(f, ascii)
1841 ## Exports the mesh in a file in CGNS format
1842 # @param f is the file name
1843 # @param overwrite boolean parameter for overwriting/not overwriting the file
1844 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1845 # @ingroup l2_impexp
1846 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1847 unRegister = genObjUnRegister()
1848 if isinstance( meshPart, list ):
1849 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1850 unRegister.set( meshPart )
1851 if isinstance( meshPart, Mesh ):
1852 meshPart = meshPart.mesh
1854 meshPart = self.mesh
1855 self.mesh.ExportCGNS(meshPart, f, overwrite)
1857 ## Exports the mesh in a file in GMF format.
1858 # GMF files must have .mesh extension for the ASCII format and .meshb for
1859 # the bynary format. Other extensions are not allowed.
1860 # @param f is the file name
1861 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1862 # @ingroup l2_impexp
1863 def ExportGMF(self, f, meshPart=None):
1864 unRegister = genObjUnRegister()
1865 if isinstance( meshPart, list ):
1866 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1867 unRegister.set( meshPart )
1868 if isinstance( meshPart, Mesh ):
1869 meshPart = meshPart.mesh
1871 meshPart = self.mesh
1872 self.mesh.ExportGMF(meshPart, f, True)
1874 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1875 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1876 ## allowing to overwrite the file if it exists or add the exported data to its contents
1877 # @param f the file name
1878 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1879 # @param opt boolean parameter for creating/not creating
1880 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1881 # @param overwrite boolean parameter for overwriting/not overwriting the file
1882 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1883 # - 1D if all mesh nodes lie on OX coordinate axis, or
1884 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1885 # - 3D in the rest cases.
1887 # If @a autoDimension is @c False, the space dimension is always 3.
1888 # @ingroup l2_impexp
1889 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1890 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1892 # Operations with groups:
1893 # ----------------------
1895 ## Creates an empty mesh group
1896 # @param elementType the type of elements in the group; either of
1897 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1898 # @param name the name of the mesh group
1899 # @return SMESH_Group
1900 # @ingroup l2_grps_create
1901 def CreateEmptyGroup(self, elementType, name):
1902 return self.mesh.CreateGroup(elementType, name)
1904 ## Creates a mesh group based on the geometric object \a grp
1905 # and gives a \a name, \n if this parameter is not defined
1906 # the name is the same as the geometric group name \n
1907 # Note: Works like GroupOnGeom().
1908 # @param grp a geometric group, a vertex, an edge, a face or a solid
1909 # @param name the name of the mesh group
1910 # @return SMESH_GroupOnGeom
1911 # @ingroup l2_grps_create
1912 def Group(self, grp, name=""):
1913 return self.GroupOnGeom(grp, name)
1915 ## Creates a mesh group based on the geometrical object \a grp
1916 # and gives a \a name, \n if this parameter is not defined
1917 # the name is the same as the geometrical group name
1918 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1919 # @param name the name of the mesh group
1920 # @param typ the type of elements in the group; either of
1921 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1922 # automatically detected by the type of the geometry
1923 # @return SMESH_GroupOnGeom
1924 # @ingroup l2_grps_create
1925 def GroupOnGeom(self, grp, name="", typ=None):
1926 AssureGeomPublished( self, grp, name )
1928 name = grp.GetName()
1930 typ = self._groupTypeFromShape( grp )
1931 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1933 ## Pivate method to get a type of group on geometry
1934 def _groupTypeFromShape( self, shape ):
1935 tgeo = str(shape.GetShapeType())
1936 if tgeo == "VERTEX":
1938 elif tgeo == "EDGE":
1940 elif tgeo == "FACE" or tgeo == "SHELL":
1942 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1944 elif tgeo == "COMPOUND":
1945 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1947 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1948 return self._groupTypeFromShape( sub[0] )
1951 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1954 ## Creates a mesh group with given \a name based on the \a filter which
1955 ## is a special type of group dynamically updating it's contents during
1956 ## mesh modification
1957 # @param typ the type of elements in the group; either of
1958 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1959 # @param name the name of the mesh group
1960 # @param filter the filter defining group contents
1961 # @return SMESH_GroupOnFilter
1962 # @ingroup l2_grps_create
1963 def GroupOnFilter(self, typ, name, filter):
1964 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1966 ## Creates a mesh group by the given ids of elements
1967 # @param groupName the name of the mesh group
1968 # @param elementType the type of elements in the group; either of
1969 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1970 # @param elemIDs the list of ids
1971 # @return SMESH_Group
1972 # @ingroup l2_grps_create
1973 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1974 group = self.mesh.CreateGroup(elementType, groupName)
1975 if hasattr( elemIDs, "GetIDs" ):
1976 if hasattr( elemIDs, "SetMesh" ):
1977 elemIDs.SetMesh( self.GetMesh() )
1978 group.AddFrom( elemIDs )
1983 ## Creates a mesh group by the given conditions
1984 # @param groupName the name of the mesh group
1985 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1986 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
1987 # Type SMESH.FunctorType._items in the Python Console to see all values.
1988 # Note that the items starting from FT_LessThan are not suitable for CritType.
1989 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1990 # @param Threshold the threshold value (range of ids as string, shape, numeric)
1991 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
1992 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1993 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
1994 # @return SMESH_GroupOnFilter
1995 # @ingroup l2_grps_create
1999 CritType=FT_Undefined,
2002 UnaryOp=FT_Undefined,
2004 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2005 group = self.MakeGroupByCriterion(groupName, aCriterion)
2008 ## Creates a mesh group by the given criterion
2009 # @param groupName the name of the mesh group
2010 # @param Criterion the instance of Criterion class
2011 # @return SMESH_GroupOnFilter
2012 # @ingroup l2_grps_create
2013 def MakeGroupByCriterion(self, groupName, Criterion):
2014 return self.MakeGroupByCriteria( groupName, [Criterion] )
2016 ## Creates a mesh group by the given criteria (list of criteria)
2017 # @param groupName the name of the mesh group
2018 # @param theCriteria the list of criteria
2019 # @param binOp binary operator used when binary operator of criteria is undefined
2020 # @return SMESH_GroupOnFilter
2021 # @ingroup l2_grps_create
2022 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2023 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2024 group = self.MakeGroupByFilter(groupName, aFilter)
2027 ## Creates a mesh group by the given filter
2028 # @param groupName the name of the mesh group
2029 # @param theFilter the instance of Filter class
2030 # @return SMESH_GroupOnFilter
2031 # @ingroup l2_grps_create
2032 def MakeGroupByFilter(self, groupName, theFilter):
2033 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2034 #theFilter.SetMesh( self.mesh )
2035 #group.AddFrom( theFilter )
2036 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2040 # @ingroup l2_grps_delete
2041 def RemoveGroup(self, group):
2042 self.mesh.RemoveGroup(group)
2044 ## Removes a group with its contents
2045 # @ingroup l2_grps_delete
2046 def RemoveGroupWithContents(self, group):
2047 self.mesh.RemoveGroupWithContents(group)
2049 ## Gets the list of groups existing in the mesh in the order
2050 # of creation (starting from the oldest one)
2051 # @param elemType type of elements the groups contain; either of
2052 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2053 # by default groups of elements of all types are returned
2054 # @return a sequence of SMESH_GroupBase
2055 # @ingroup l2_grps_create
2056 def GetGroups(self, elemType = SMESH.ALL):
2057 groups = self.mesh.GetGroups()
2058 if elemType == SMESH.ALL:
2062 if g.GetType() == elemType:
2063 typedGroups.append( g )
2068 ## Gets the number of groups existing in the mesh
2069 # @return the quantity of groups as an integer value
2070 # @ingroup l2_grps_create
2072 return self.mesh.NbGroups()
2074 ## Gets the list of names of groups existing in the mesh
2075 # @return list of strings
2076 # @ingroup l2_grps_create
2077 def GetGroupNames(self):
2078 groups = self.GetGroups()
2080 for group in groups:
2081 names.append(group.GetName())
2084 ## Finds groups by name and type
2085 # @param name name of the group of interest
2086 # @param elemType type of elements the groups contain; either of
2087 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2088 # by default one group of any type of elements is returned
2089 # if elemType == SMESH.ALL then all groups of any type are returned
2090 # @return a list of SMESH_GroupBase's
2091 # @ingroup l2_grps_create
2092 def GetGroupByName(self, name, elemType = None):
2094 for group in self.GetGroups():
2095 if group.GetName() == name:
2096 if elemType is None:
2098 if ( elemType == SMESH.ALL or
2099 group.GetType() == elemType ):
2100 groups.append( group )
2103 ## Produces a union of two groups.
2104 # A new group is created. All mesh elements that are
2105 # present in the initial groups are added to the new one
2106 # @return an instance of SMESH_Group
2107 # @ingroup l2_grps_operon
2108 def UnionGroups(self, group1, group2, name):
2109 return self.mesh.UnionGroups(group1, group2, name)
2111 ## Produces a union list of groups.
2112 # New group is created. All mesh elements that are present in
2113 # initial groups are added to the new one
2114 # @return an instance of SMESH_Group
2115 # @ingroup l2_grps_operon
2116 def UnionListOfGroups(self, groups, name):
2117 return self.mesh.UnionListOfGroups(groups, name)
2119 ## Prodices an intersection of two groups.
2120 # A new group is created. All mesh elements that are common
2121 # for the two initial groups are added to the new one.
2122 # @return an instance of SMESH_Group
2123 # @ingroup l2_grps_operon
2124 def IntersectGroups(self, group1, group2, name):
2125 return self.mesh.IntersectGroups(group1, group2, name)
2127 ## Produces an intersection of groups.
2128 # New group is created. All mesh elements that are present in all
2129 # initial groups simultaneously are added to the new one
2130 # @return an instance of SMESH_Group
2131 # @ingroup l2_grps_operon
2132 def IntersectListOfGroups(self, groups, name):
2133 return self.mesh.IntersectListOfGroups(groups, name)
2135 ## Produces a cut of two groups.
2136 # A new group is created. All mesh elements that are present in
2137 # the main group but are not present in the tool group are added to the new one
2138 # @return an instance of SMESH_Group
2139 # @ingroup l2_grps_operon
2140 def CutGroups(self, main_group, tool_group, name):
2141 return self.mesh.CutGroups(main_group, tool_group, name)
2143 ## Produces a cut of groups.
2144 # A new group is created. All mesh elements that are present in main groups
2145 # but do not present in tool groups are added to the new one
2146 # @return an instance of SMESH_Group
2147 # @ingroup l2_grps_operon
2148 def CutListOfGroups(self, main_groups, tool_groups, name):
2149 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2152 # Create a standalone group of entities basing on nodes of other groups.
2153 # \param groups - list of groups, sub-meshes or filters, of any type.
2154 # \param elemType - a type of elements to include to the new group; either of
2155 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2156 # \param name - a name of the new group.
2157 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2158 # basing on number of element nodes common with reference \a groups.
2159 # Meaning of possible values are:
2160 # - SMESH.ALL_NODES - include if all nodes are common,
2161 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2162 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2163 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2164 # \param underlyingOnly - if \c True (default), an element is included to the
2165 # new group provided that it is based on nodes of one element of \a groups.
2166 # @return an instance of SMESH_Group
2167 # @ingroup l2_grps_operon
2168 def CreateDimGroup(self, groups, elemType, name,
2169 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2170 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2172 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2175 ## Convert group on geom into standalone group
2176 # @ingroup l2_grps_delete
2177 def ConvertToStandalone(self, group):
2178 return self.mesh.ConvertToStandalone(group)
2180 # Get some info about mesh:
2181 # ------------------------
2183 ## Returns the log of nodes and elements added or removed
2184 # since the previous clear of the log.
2185 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2186 # @return list of log_block structures:
2191 # @ingroup l1_auxiliary
2192 def GetLog(self, clearAfterGet):
2193 return self.mesh.GetLog(clearAfterGet)
2195 ## Clears the log of nodes and elements added or removed since the previous
2196 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2197 # @ingroup l1_auxiliary
2199 self.mesh.ClearLog()
2201 ## Toggles auto color mode on the object.
2202 # @param theAutoColor the flag which toggles auto color mode.
2203 # @ingroup l1_auxiliary
2204 def SetAutoColor(self, theAutoColor):
2205 self.mesh.SetAutoColor(theAutoColor)
2207 ## Gets flag of object auto color mode.
2208 # @return True or False
2209 # @ingroup l1_auxiliary
2210 def GetAutoColor(self):
2211 return self.mesh.GetAutoColor()
2213 ## Gets the internal ID
2214 # @return integer value, which is the internal Id of the mesh
2215 # @ingroup l1_auxiliary
2217 return self.mesh.GetId()
2220 # @return integer value, which is the study Id of the mesh
2221 # @ingroup l1_auxiliary
2222 def GetStudyId(self):
2223 return self.mesh.GetStudyId()
2225 ## Checks the group names for duplications.
2226 # Consider the maximum group name length stored in MED file.
2227 # @return True or False
2228 # @ingroup l1_auxiliary
2229 def HasDuplicatedGroupNamesMED(self):
2230 return self.mesh.HasDuplicatedGroupNamesMED()
2232 ## Obtains the mesh editor tool
2233 # @return an instance of SMESH_MeshEditor
2234 # @ingroup l1_modifying
2235 def GetMeshEditor(self):
2238 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2239 # can be passed as argument to a method accepting mesh, group or sub-mesh
2240 # @param ids list of IDs
2241 # @param elemType type of elements; this parameter is used to distinguish
2242 # IDs of nodes from IDs of elements; by default ids are treated as
2243 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2244 # @return an instance of SMESH_IDSource
2245 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2246 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2247 # mesh.DoSomething( idSrc )
2248 # idSrc.UnRegister()
2249 # @ingroup l1_auxiliary
2250 def GetIDSource(self, ids, elemType = SMESH.ALL):
2251 return self.editor.MakeIDSource(ids, elemType)
2254 # Get informations about mesh contents:
2255 # ------------------------------------
2257 ## Gets the mesh stattistic
2258 # @return dictionary type element - count of elements
2259 # @ingroup l1_meshinfo
2260 def GetMeshInfo(self, obj = None):
2261 if not obj: obj = self.mesh
2262 return self.smeshpyD.GetMeshInfo(obj)
2264 ## Returns the number of nodes in the mesh
2265 # @return an integer value
2266 # @ingroup l1_meshinfo
2268 return self.mesh.NbNodes()
2270 ## Returns the number of elements in the mesh
2271 # @return an integer value
2272 # @ingroup l1_meshinfo
2273 def NbElements(self):
2274 return self.mesh.NbElements()
2276 ## Returns the number of 0d elements in the mesh
2277 # @return an integer value
2278 # @ingroup l1_meshinfo
2279 def Nb0DElements(self):
2280 return self.mesh.Nb0DElements()
2282 ## Returns the number of ball discrete elements in the mesh
2283 # @return an integer value
2284 # @ingroup l1_meshinfo
2286 return self.mesh.NbBalls()
2288 ## Returns the number of edges in the mesh
2289 # @return an integer value
2290 # @ingroup l1_meshinfo
2292 return self.mesh.NbEdges()
2294 ## Returns the number of edges with the given order in the mesh
2295 # @param elementOrder the order of elements:
2296 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2297 # @return an integer value
2298 # @ingroup l1_meshinfo
2299 def NbEdgesOfOrder(self, elementOrder):
2300 return self.mesh.NbEdgesOfOrder(elementOrder)
2302 ## Returns the number of faces in the mesh
2303 # @return an integer value
2304 # @ingroup l1_meshinfo
2306 return self.mesh.NbFaces()
2308 ## Returns the number of faces with the given order in the mesh
2309 # @param elementOrder the order of elements:
2310 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2311 # @return an integer value
2312 # @ingroup l1_meshinfo
2313 def NbFacesOfOrder(self, elementOrder):
2314 return self.mesh.NbFacesOfOrder(elementOrder)
2316 ## Returns the number of triangles in the mesh
2317 # @return an integer value
2318 # @ingroup l1_meshinfo
2319 def NbTriangles(self):
2320 return self.mesh.NbTriangles()
2322 ## Returns the number of triangles with the given order in the mesh
2323 # @param elementOrder is the order of elements:
2324 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2325 # @return an integer value
2326 # @ingroup l1_meshinfo
2327 def NbTrianglesOfOrder(self, elementOrder):
2328 return self.mesh.NbTrianglesOfOrder(elementOrder)
2330 ## Returns the number of biquadratic triangles in the mesh
2331 # @return an integer value
2332 # @ingroup l1_meshinfo
2333 def NbBiQuadTriangles(self):
2334 return self.mesh.NbBiQuadTriangles()
2336 ## Returns the number of quadrangles in the mesh
2337 # @return an integer value
2338 # @ingroup l1_meshinfo
2339 def NbQuadrangles(self):
2340 return self.mesh.NbQuadrangles()
2342 ## Returns the number of quadrangles with the given order in the mesh
2343 # @param elementOrder the order of elements:
2344 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2345 # @return an integer value
2346 # @ingroup l1_meshinfo
2347 def NbQuadranglesOfOrder(self, elementOrder):
2348 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2350 ## Returns the number of biquadratic quadrangles in the mesh
2351 # @return an integer value
2352 # @ingroup l1_meshinfo
2353 def NbBiQuadQuadrangles(self):
2354 return self.mesh.NbBiQuadQuadrangles()
2356 ## Returns the number of polygons of given order in the mesh
2357 # @param elementOrder the order of elements:
2358 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2359 # @return an integer value
2360 # @ingroup l1_meshinfo
2361 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2362 return self.mesh.NbPolygonsOfOrder(elementOrder)
2364 ## Returns the number of volumes in the mesh
2365 # @return an integer value
2366 # @ingroup l1_meshinfo
2367 def NbVolumes(self):
2368 return self.mesh.NbVolumes()
2370 ## Returns the number of volumes with the given order in the mesh
2371 # @param elementOrder the order of elements:
2372 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2373 # @return an integer value
2374 # @ingroup l1_meshinfo
2375 def NbVolumesOfOrder(self, elementOrder):
2376 return self.mesh.NbVolumesOfOrder(elementOrder)
2378 ## Returns the number of tetrahedrons in the mesh
2379 # @return an integer value
2380 # @ingroup l1_meshinfo
2382 return self.mesh.NbTetras()
2384 ## Returns the number of tetrahedrons with the given order in the mesh
2385 # @param elementOrder the order of elements:
2386 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2387 # @return an integer value
2388 # @ingroup l1_meshinfo
2389 def NbTetrasOfOrder(self, elementOrder):
2390 return self.mesh.NbTetrasOfOrder(elementOrder)
2392 ## Returns the number of hexahedrons in the mesh
2393 # @return an integer value
2394 # @ingroup l1_meshinfo
2396 return self.mesh.NbHexas()
2398 ## Returns the number of hexahedrons with the given order in the mesh
2399 # @param elementOrder the order of elements:
2400 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2401 # @return an integer value
2402 # @ingroup l1_meshinfo
2403 def NbHexasOfOrder(self, elementOrder):
2404 return self.mesh.NbHexasOfOrder(elementOrder)
2406 ## Returns the number of triquadratic hexahedrons in the mesh
2407 # @return an integer value
2408 # @ingroup l1_meshinfo
2409 def NbTriQuadraticHexas(self):
2410 return self.mesh.NbTriQuadraticHexas()
2412 ## Returns the number of pyramids in the mesh
2413 # @return an integer value
2414 # @ingroup l1_meshinfo
2415 def NbPyramids(self):
2416 return self.mesh.NbPyramids()
2418 ## Returns the number of pyramids with the given order in the mesh
2419 # @param elementOrder the order of elements:
2420 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2421 # @return an integer value
2422 # @ingroup l1_meshinfo
2423 def NbPyramidsOfOrder(self, elementOrder):
2424 return self.mesh.NbPyramidsOfOrder(elementOrder)
2426 ## Returns the number of prisms in the mesh
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2430 return self.mesh.NbPrisms()
2432 ## Returns the number of prisms with the given order in the mesh
2433 # @param elementOrder the order of elements:
2434 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2435 # @return an integer value
2436 # @ingroup l1_meshinfo
2437 def NbPrismsOfOrder(self, elementOrder):
2438 return self.mesh.NbPrismsOfOrder(elementOrder)
2440 ## Returns the number of hexagonal prisms in the mesh
2441 # @return an integer value
2442 # @ingroup l1_meshinfo
2443 def NbHexagonalPrisms(self):
2444 return self.mesh.NbHexagonalPrisms()
2446 ## Returns the number of polyhedrons in the mesh
2447 # @return an integer value
2448 # @ingroup l1_meshinfo
2449 def NbPolyhedrons(self):
2450 return self.mesh.NbPolyhedrons()
2452 ## Returns the number of submeshes in the mesh
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2455 def NbSubMesh(self):
2456 return self.mesh.NbSubMesh()
2458 ## Returns the list of mesh elements IDs
2459 # @return the list of integer values
2460 # @ingroup l1_meshinfo
2461 def GetElementsId(self):
2462 return self.mesh.GetElementsId()
2464 ## Returns the list of IDs of mesh elements with the given type
2465 # @param elementType the required type of elements, either of
2466 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2467 # @return list of integer values
2468 # @ingroup l1_meshinfo
2469 def GetElementsByType(self, elementType):
2470 return self.mesh.GetElementsByType(elementType)
2472 ## Returns the list of mesh nodes IDs
2473 # @return the list of integer values
2474 # @ingroup l1_meshinfo
2475 def GetNodesId(self):
2476 return self.mesh.GetNodesId()
2478 # Get the information about mesh elements:
2479 # ------------------------------------
2481 ## Returns the type of mesh element
2482 # @return the value from SMESH::ElementType enumeration
2483 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2484 # @ingroup l1_meshinfo
2485 def GetElementType(self, id, iselem=True):
2486 return self.mesh.GetElementType(id, iselem)
2488 ## Returns the geometric type of mesh element
2489 # @return the value from SMESH::EntityType enumeration
2490 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2491 # @ingroup l1_meshinfo
2492 def GetElementGeomType(self, id):
2493 return self.mesh.GetElementGeomType(id)
2495 ## Returns the shape type of mesh element
2496 # @return the value from SMESH::GeometryType enumeration.
2497 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2498 # @ingroup l1_meshinfo
2499 def GetElementShape(self, id):
2500 return self.mesh.GetElementShape(id)
2502 ## Returns the list of submesh elements IDs
2503 # @param Shape a geom object(sub-shape) IOR
2504 # Shape must be the sub-shape of a ShapeToMesh()
2505 # @return the list of integer values
2506 # @ingroup l1_meshinfo
2507 def GetSubMeshElementsId(self, Shape):
2508 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2509 ShapeID = Shape.GetSubShapeIndices()[0]
2512 return self.mesh.GetSubMeshElementsId(ShapeID)
2514 ## Returns the list of submesh nodes IDs
2515 # @param Shape a geom object(sub-shape) IOR
2516 # Shape must be the sub-shape of a ShapeToMesh()
2517 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2518 # @return the list of integer values
2519 # @ingroup l1_meshinfo
2520 def GetSubMeshNodesId(self, Shape, all):
2521 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2522 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2525 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2527 ## Returns type of elements on given shape
2528 # @param Shape a geom object(sub-shape) IOR
2529 # Shape must be a sub-shape of a ShapeToMesh()
2530 # @return element type
2531 # @ingroup l1_meshinfo
2532 def GetSubMeshElementType(self, Shape):
2533 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2534 ShapeID = Shape.GetSubShapeIndices()[0]
2537 return self.mesh.GetSubMeshElementType(ShapeID)
2539 ## Gets the mesh description
2540 # @return string value
2541 # @ingroup l1_meshinfo
2543 return self.mesh.Dump()
2546 # Get the information about nodes and elements of a mesh by its IDs:
2547 # -----------------------------------------------------------
2549 ## Gets XYZ coordinates of a node
2550 # \n If there is no nodes for the given ID - returns an empty list
2551 # @return a list of double precision values
2552 # @ingroup l1_meshinfo
2553 def GetNodeXYZ(self, id):
2554 return self.mesh.GetNodeXYZ(id)
2556 ## Returns list of IDs of inverse elements for the given node
2557 # \n If there is no node for the given ID - returns an empty list
2558 # @return a list of integer values
2559 # @ingroup l1_meshinfo
2560 def GetNodeInverseElements(self, id):
2561 return self.mesh.GetNodeInverseElements(id)
2563 ## @brief Returns the position of a node on the shape
2564 # @return SMESH::NodePosition
2565 # @ingroup l1_meshinfo
2566 def GetNodePosition(self,NodeID):
2567 return self.mesh.GetNodePosition(NodeID)
2569 ## @brief Returns the position of an element on the shape
2570 # @return SMESH::ElementPosition
2571 # @ingroup l1_meshinfo
2572 def GetElementPosition(self,ElemID):
2573 return self.mesh.GetElementPosition(ElemID)
2575 ## Returns the ID of the shape, on which the given node was generated.
2576 # @return an integer value > 0 or -1 if there is no node for the given
2577 # ID or the node is not assigned to any geometry
2578 # @ingroup l1_meshinfo
2579 def GetShapeID(self, id):
2580 return self.mesh.GetShapeID(id)
2582 ## Returns the ID of the shape, on which the given element was generated.
2583 # @return an integer value > 0 or -1 if there is no element for the given
2584 # ID or the element is not assigned to any geometry
2585 # @ingroup l1_meshinfo
2586 def GetShapeIDForElem(self,id):
2587 return self.mesh.GetShapeIDForElem(id)
2589 ## Returns the number of nodes of the given element
2590 # @return an integer value > 0 or -1 if there is no element for the given ID
2591 # @ingroup l1_meshinfo
2592 def GetElemNbNodes(self, id):
2593 return self.mesh.GetElemNbNodes(id)
2595 ## Returns the node ID the given (zero based) index for the given element
2596 # \n If there is no element for the given ID - returns -1
2597 # \n If there is no node for the given index - returns -2
2598 # @return an integer value
2599 # @ingroup l1_meshinfo
2600 def GetElemNode(self, id, index):
2601 return self.mesh.GetElemNode(id, index)
2603 ## Returns the IDs of nodes of the given element
2604 # @return a list of integer values
2605 # @ingroup l1_meshinfo
2606 def GetElemNodes(self, id):
2607 return self.mesh.GetElemNodes(id)
2609 ## Returns true if the given node is the medium node in the given quadratic element
2610 # @ingroup l1_meshinfo
2611 def IsMediumNode(self, elementID, nodeID):
2612 return self.mesh.IsMediumNode(elementID, nodeID)
2614 ## Returns true if the given node is the medium node in one of quadratic elements
2615 # @param nodeID ID of the node
2616 # @param elementType the type of elements to check a state of the node, either of
2617 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2618 # @ingroup l1_meshinfo
2619 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2620 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2622 ## Returns the number of edges for the given element
2623 # @ingroup l1_meshinfo
2624 def ElemNbEdges(self, id):
2625 return self.mesh.ElemNbEdges(id)
2627 ## Returns the number of faces for the given element
2628 # @ingroup l1_meshinfo
2629 def ElemNbFaces(self, id):
2630 return self.mesh.ElemNbFaces(id)
2632 ## Returns nodes of given face (counted from zero) for given volumic element.
2633 # @ingroup l1_meshinfo
2634 def GetElemFaceNodes(self,elemId, faceIndex):
2635 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2637 ## Returns three components of normal of given mesh face
2638 # (or an empty array in KO case)
2639 # @ingroup l1_meshinfo
2640 def GetFaceNormal(self, faceId, normalized=False):
2641 return self.mesh.GetFaceNormal(faceId,normalized)
2643 ## Returns an element based on all given nodes.
2644 # @ingroup l1_meshinfo
2645 def FindElementByNodes(self,nodes):
2646 return self.mesh.FindElementByNodes(nodes)
2648 ## Returns true if the given element is a polygon
2649 # @ingroup l1_meshinfo
2650 def IsPoly(self, id):
2651 return self.mesh.IsPoly(id)
2653 ## Returns true if the given element is quadratic
2654 # @ingroup l1_meshinfo
2655 def IsQuadratic(self, id):
2656 return self.mesh.IsQuadratic(id)
2658 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2659 # @ingroup l1_meshinfo
2660 def GetBallDiameter(self, id):
2661 return self.mesh.GetBallDiameter(id)
2663 ## Returns XYZ coordinates of the barycenter of the given element
2664 # \n If there is no element for the given ID - returns an empty list
2665 # @return a list of three double values
2666 # @ingroup l1_meshinfo
2667 def BaryCenter(self, id):
2668 return self.mesh.BaryCenter(id)
2670 ## Passes mesh elements through the given filter and return IDs of fitting elements
2671 # @param theFilter SMESH_Filter
2672 # @return a list of ids
2673 # @ingroup l1_controls
2674 def GetIdsFromFilter(self, theFilter):
2675 theFilter.SetMesh( self.mesh )
2676 return theFilter.GetIDs()
2678 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2679 # Returns a list of special structures (borders).
2680 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2681 # @ingroup l1_controls
2682 def GetFreeBorders(self):
2683 aFilterMgr = self.smeshpyD.CreateFilterManager()
2684 aPredicate = aFilterMgr.CreateFreeEdges()
2685 aPredicate.SetMesh(self.mesh)
2686 aBorders = aPredicate.GetBorders()
2687 aFilterMgr.UnRegister()
2691 # Get mesh measurements information:
2692 # ------------------------------------
2694 ## Get minimum distance between two nodes, elements or distance to the origin
2695 # @param id1 first node/element id
2696 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2697 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2698 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2699 # @return minimum distance value
2700 # @sa GetMinDistance()
2701 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2702 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2703 return aMeasure.value
2705 ## Get measure structure specifying minimum distance data between two objects
2706 # @param id1 first node/element id
2707 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2708 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2709 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2710 # @return Measure structure
2712 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2714 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2716 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2719 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2721 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2726 aMeasurements = self.smeshpyD.CreateMeasurements()
2727 aMeasure = aMeasurements.MinDistance(id1, id2)
2728 genObjUnRegister([aMeasurements,id1, id2])
2731 ## Get bounding box of the specified object(s)
2732 # @param objects single source object or list of source objects or list of nodes/elements IDs
2733 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2734 # @c False specifies that @a objects are nodes
2735 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2736 # @sa GetBoundingBox()
2737 def BoundingBox(self, objects=None, isElem=False):
2738 result = self.GetBoundingBox(objects, isElem)
2742 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2745 ## Get measure structure specifying bounding box data of the specified object(s)
2746 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2747 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2748 # @c False specifies that @a objects are nodes
2749 # @return Measure structure
2751 def GetBoundingBox(self, IDs=None, isElem=False):
2754 elif isinstance(IDs, tuple):
2756 if not isinstance(IDs, list):
2758 if len(IDs) > 0 and isinstance(IDs[0], int):
2761 unRegister = genObjUnRegister()
2763 if isinstance(o, Mesh):
2764 srclist.append(o.mesh)
2765 elif hasattr(o, "_narrow"):
2766 src = o._narrow(SMESH.SMESH_IDSource)
2767 if src: srclist.append(src)
2769 elif isinstance(o, list):
2771 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2773 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2774 unRegister.set( srclist[-1] )
2777 aMeasurements = self.smeshpyD.CreateMeasurements()
2778 unRegister.set( aMeasurements )
2779 aMeasure = aMeasurements.BoundingBox(srclist)
2782 # Mesh edition (SMESH_MeshEditor functionality):
2783 # ---------------------------------------------
2785 ## Removes the elements from the mesh by ids
2786 # @param IDsOfElements is a list of ids of elements to remove
2787 # @return True or False
2788 # @ingroup l2_modif_del
2789 def RemoveElements(self, IDsOfElements):
2790 return self.editor.RemoveElements(IDsOfElements)
2792 ## Removes nodes from mesh by ids
2793 # @param IDsOfNodes is a list of ids of nodes to remove
2794 # @return True or False
2795 # @ingroup l2_modif_del
2796 def RemoveNodes(self, IDsOfNodes):
2797 return self.editor.RemoveNodes(IDsOfNodes)
2799 ## Removes all orphan (free) nodes from mesh
2800 # @return number of the removed nodes
2801 # @ingroup l2_modif_del
2802 def RemoveOrphanNodes(self):
2803 return self.editor.RemoveOrphanNodes()
2805 ## Add a node to the mesh by coordinates
2806 # @return Id of the new node
2807 # @ingroup l2_modif_add
2808 def AddNode(self, x, y, z):
2809 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2810 if hasVars: self.mesh.SetParameters(Parameters)
2811 return self.editor.AddNode( x, y, z)
2813 ## Creates a 0D element on a node with given number.
2814 # @param IDOfNode the ID of node for creation of the element.
2815 # @return the Id of the new 0D element
2816 # @ingroup l2_modif_add
2817 def Add0DElement(self, IDOfNode):
2818 return self.editor.Add0DElement(IDOfNode)
2820 ## Create 0D elements on all nodes of the given elements except those
2821 # nodes on which a 0D element already exists.
2822 # @param theObject an object on whose nodes 0D elements will be created.
2823 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2824 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2825 # @param theGroupName optional name of a group to add 0D elements created
2826 # and/or found on nodes of \a theObject.
2827 # @return an object (a new group or a temporary SMESH_IDSource) holding
2828 # IDs of new and/or found 0D elements. IDs of 0D elements
2829 # can be retrieved from the returned object by calling GetIDs()
2830 # @ingroup l2_modif_add
2831 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2832 unRegister = genObjUnRegister()
2833 if isinstance( theObject, Mesh ):
2834 theObject = theObject.GetMesh()
2835 if isinstance( theObject, list ):
2836 theObject = self.GetIDSource( theObject, SMESH.ALL )
2837 unRegister.set( theObject )
2838 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2840 ## Creates a ball element on a node with given ID.
2841 # @param IDOfNode the ID of node for creation of the element.
2842 # @param diameter the bal diameter.
2843 # @return the Id of the new ball element
2844 # @ingroup l2_modif_add
2845 def AddBall(self, IDOfNode, diameter):
2846 return self.editor.AddBall( IDOfNode, diameter )
2848 ## Creates a linear or quadratic edge (this is determined
2849 # by the number of given nodes).
2850 # @param IDsOfNodes the list of node IDs for creation of the element.
2851 # The order of nodes in this list should correspond to the description
2852 # of MED. \n This description is located by the following link:
2853 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2854 # @return the Id of the new edge
2855 # @ingroup l2_modif_add
2856 def AddEdge(self, IDsOfNodes):
2857 return self.editor.AddEdge(IDsOfNodes)
2859 ## Creates a linear or quadratic face (this is determined
2860 # by the number of given nodes).
2861 # @param IDsOfNodes the list of node IDs for creation of the element.
2862 # The order of nodes in this list should correspond to the description
2863 # of MED. \n This description is located by the following link:
2864 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2865 # @return the Id of the new face
2866 # @ingroup l2_modif_add
2867 def AddFace(self, IDsOfNodes):
2868 return self.editor.AddFace(IDsOfNodes)
2870 ## Adds a polygonal face to the mesh by the list of node IDs
2871 # @param IdsOfNodes the list of node IDs for creation of the element.
2872 # @return the Id of the new face
2873 # @ingroup l2_modif_add
2874 def AddPolygonalFace(self, IdsOfNodes):
2875 return self.editor.AddPolygonalFace(IdsOfNodes)
2877 ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2878 # @param IdsOfNodes the list of node IDs for creation of the element;
2879 # corner nodes follow first.
2880 # @return the Id of the new face
2881 # @ingroup l2_modif_add
2882 def AddQuadPolygonalFace(self, IdsOfNodes):
2883 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2885 ## Creates both simple and quadratic volume (this is determined
2886 # by the number of given nodes).
2887 # @param IDsOfNodes the list of node IDs for creation of the element.
2888 # The order of nodes in this list should correspond to the description
2889 # of MED. \n This description is located by the following link:
2890 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2891 # @return the Id of the new volumic element
2892 # @ingroup l2_modif_add
2893 def AddVolume(self, IDsOfNodes):
2894 return self.editor.AddVolume(IDsOfNodes)
2896 ## Creates a volume of many faces, giving nodes for each face.
2897 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2898 # @param Quantities the list of integer values, Quantities[i]
2899 # gives the quantity of nodes in face number i.
2900 # @return the Id of the new volumic element
2901 # @ingroup l2_modif_add
2902 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2903 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2905 ## Creates a volume of many faces, giving the IDs of the existing faces.
2906 # @param IdsOfFaces the list of face IDs for volume creation.
2908 # Note: The created volume will refer only to the nodes
2909 # of the given faces, not to the faces themselves.
2910 # @return the Id of the new volumic element
2911 # @ingroup l2_modif_add
2912 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2913 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2916 ## @brief Binds a node to a vertex
2917 # @param NodeID a node ID
2918 # @param Vertex a vertex or vertex ID
2919 # @return True if succeed else raises an exception
2920 # @ingroup l2_modif_add
2921 def SetNodeOnVertex(self, NodeID, Vertex):
2922 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2923 VertexID = Vertex.GetSubShapeIndices()[0]
2927 self.editor.SetNodeOnVertex(NodeID, VertexID)
2928 except SALOME.SALOME_Exception, inst:
2929 raise ValueError, inst.details.text
2933 ## @brief Stores the node position on an edge
2934 # @param NodeID a node ID
2935 # @param Edge an edge or edge ID
2936 # @param paramOnEdge a parameter on the edge where the node is located
2937 # @return True if succeed else raises an exception
2938 # @ingroup l2_modif_add
2939 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2940 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2941 EdgeID = Edge.GetSubShapeIndices()[0]
2945 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2946 except SALOME.SALOME_Exception, inst:
2947 raise ValueError, inst.details.text
2950 ## @brief Stores node position on a face
2951 # @param NodeID a node ID
2952 # @param Face a face or face ID
2953 # @param u U parameter on the face where the node is located
2954 # @param v V parameter on the face where the node is located
2955 # @return True if succeed else raises an exception
2956 # @ingroup l2_modif_add
2957 def SetNodeOnFace(self, NodeID, Face, u, v):
2958 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2959 FaceID = Face.GetSubShapeIndices()[0]
2963 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2964 except SALOME.SALOME_Exception, inst:
2965 raise ValueError, inst.details.text
2968 ## @brief Binds a node to a solid
2969 # @param NodeID a node ID
2970 # @param Solid a solid or solid ID
2971 # @return True if succeed else raises an exception
2972 # @ingroup l2_modif_add
2973 def SetNodeInVolume(self, NodeID, Solid):
2974 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2975 SolidID = Solid.GetSubShapeIndices()[0]
2979 self.editor.SetNodeInVolume(NodeID, SolidID)
2980 except SALOME.SALOME_Exception, inst:
2981 raise ValueError, inst.details.text
2984 ## @brief Bind an element to a shape
2985 # @param ElementID an element ID
2986 # @param Shape a shape or shape ID
2987 # @return True if succeed else raises an exception
2988 # @ingroup l2_modif_add
2989 def SetMeshElementOnShape(self, ElementID, Shape):
2990 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2991 ShapeID = Shape.GetSubShapeIndices()[0]
2995 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2996 except SALOME.SALOME_Exception, inst:
2997 raise ValueError, inst.details.text
3001 ## Moves the node with the given id
3002 # @param NodeID the id of the node
3003 # @param x a new X coordinate
3004 # @param y a new Y coordinate
3005 # @param z a new Z coordinate
3006 # @return True if succeed else False
3007 # @ingroup l2_modif_movenode
3008 def MoveNode(self, NodeID, x, y, z):
3009 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3010 if hasVars: self.mesh.SetParameters(Parameters)
3011 return self.editor.MoveNode(NodeID, x, y, z)
3013 ## Finds the node closest to a point and moves it to a point location
3014 # @param x the X coordinate of a point
3015 # @param y the Y coordinate of a point
3016 # @param z the Z coordinate of a point
3017 # @param NodeID if specified (>0), the node with this ID is moved,
3018 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3019 # @return the ID of a node
3020 # @ingroup l2_modif_throughp
3021 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3022 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3023 if hasVars: self.mesh.SetParameters(Parameters)
3024 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3026 ## Finds the node closest to a point
3027 # @param x the X coordinate of a point
3028 # @param y the Y coordinate of a point
3029 # @param z the Z coordinate of a point
3030 # @return the ID of a node
3031 # @ingroup l2_modif_throughp
3032 def FindNodeClosestTo(self, x, y, z):
3033 #preview = self.mesh.GetMeshEditPreviewer()
3034 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3035 return self.editor.FindNodeClosestTo(x, y, z)
3037 ## Finds the elements where a point lays IN or ON
3038 # @param x the X coordinate of a point
3039 # @param y the Y coordinate of a point
3040 # @param z the Z coordinate of a point
3041 # @param elementType type of elements to find; either of
3042 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3043 # means elements of any type excluding nodes, discrete and 0D elements.
3044 # @param meshPart a part of mesh (group, sub-mesh) to search within
3045 # @return list of IDs of found elements
3046 # @ingroup l2_modif_throughp
3047 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3049 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3051 return self.editor.FindElementsByPoint(x, y, z, elementType)
3053 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3054 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3055 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3056 def GetPointState(self, x, y, z):
3057 return self.editor.GetPointState(x, y, z)
3059 ## Finds the node closest to a point and moves it to a point location
3060 # @param x the X coordinate of a point
3061 # @param y the Y coordinate of a point
3062 # @param z the Z coordinate of a point
3063 # @return the ID of a moved node
3064 # @ingroup l2_modif_throughp
3065 def MeshToPassThroughAPoint(self, x, y, z):
3066 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3068 ## Replaces two neighbour triangles sharing Node1-Node2 link
3069 # with the triangles built on the same 4 nodes but having other common link.
3070 # @param NodeID1 the ID of the first node
3071 # @param NodeID2 the ID of the second node
3072 # @return false if proper faces were not found
3073 # @ingroup l2_modif_invdiag
3074 def InverseDiag(self, NodeID1, NodeID2):
3075 return self.editor.InverseDiag(NodeID1, NodeID2)
3077 ## Replaces two neighbour triangles sharing Node1-Node2 link
3078 # with a quadrangle built on the same 4 nodes.
3079 # @param NodeID1 the ID of the first node
3080 # @param NodeID2 the ID of the second node
3081 # @return false if proper faces were not found
3082 # @ingroup l2_modif_unitetri
3083 def DeleteDiag(self, NodeID1, NodeID2):
3084 return self.editor.DeleteDiag(NodeID1, NodeID2)
3086 ## Reorients elements by ids
3087 # @param IDsOfElements if undefined reorients all mesh elements
3088 # @return True if succeed else False
3089 # @ingroup l2_modif_changori
3090 def Reorient(self, IDsOfElements=None):
3091 if IDsOfElements == None:
3092 IDsOfElements = self.GetElementsId()
3093 return self.editor.Reorient(IDsOfElements)
3095 ## Reorients all elements of the object
3096 # @param theObject mesh, submesh or group
3097 # @return True if succeed else False
3098 # @ingroup l2_modif_changori
3099 def ReorientObject(self, theObject):
3100 if ( isinstance( theObject, Mesh )):
3101 theObject = theObject.GetMesh()
3102 return self.editor.ReorientObject(theObject)
3104 ## Reorient faces contained in \a the2DObject.
3105 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3106 # @param theDirection is a desired direction of normal of \a theFace.
3107 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3108 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3109 # compared with theDirection. It can be either ID of face or a point
3110 # by which the face will be found. The point can be given as either
3111 # a GEOM vertex or a list of point coordinates.
3112 # @return number of reoriented faces
3113 # @ingroup l2_modif_changori
3114 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3115 unRegister = genObjUnRegister()
3117 if isinstance( the2DObject, Mesh ):
3118 the2DObject = the2DObject.GetMesh()
3119 if isinstance( the2DObject, list ):
3120 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3121 unRegister.set( the2DObject )
3122 # check theDirection
3123 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3124 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3125 if isinstance( theDirection, list ):
3126 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3127 # prepare theFace and thePoint
3128 theFace = theFaceOrPoint
3129 thePoint = PointStruct(0,0,0)
3130 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3131 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3133 if isinstance( theFaceOrPoint, list ):
3134 thePoint = PointStruct( *theFaceOrPoint )
3136 if isinstance( theFaceOrPoint, PointStruct ):
3137 thePoint = theFaceOrPoint
3139 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3141 ## Reorient faces according to adjacent volumes.
3142 # @param the2DObject is a mesh, sub-mesh, group or list of
3143 # either IDs of faces or face groups.
3144 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3145 # @param theOutsideNormal to orient faces to have their normals
3146 # pointing either \a outside or \a inside the adjacent volumes.
3147 # @return number of reoriented faces.
3148 # @ingroup l2_modif_changori
3149 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3150 unRegister = genObjUnRegister()
3152 if not isinstance( the2DObject, list ):
3153 the2DObject = [ the2DObject ]
3154 elif the2DObject and isinstance( the2DObject[0], int ):
3155 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3156 unRegister.set( the2DObject )
3157 the2DObject = [ the2DObject ]
3158 for i,obj2D in enumerate( the2DObject ):
3159 if isinstance( obj2D, Mesh ):
3160 the2DObject[i] = obj2D.GetMesh()
3161 if isinstance( obj2D, list ):
3162 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3163 unRegister.set( the2DObject[i] )
3165 if isinstance( the3DObject, Mesh ):
3166 the3DObject = the3DObject.GetMesh()
3167 if isinstance( the3DObject, list ):
3168 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3169 unRegister.set( the3DObject )
3170 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3172 ## Fuses the neighbouring triangles into quadrangles.
3173 # @param IDsOfElements The triangles to be fused.
3174 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3175 # choose a neighbour to fuse with.
3176 # Type SMESH.FunctorType._items in the Python Console to see all items.
3177 # Note that not all items corresponds to numerical functors.
3178 # @param MaxAngle is the maximum angle between element normals at which the fusion
3179 # is still performed; theMaxAngle is mesured in radians.
3180 # Also it could be a name of variable which defines angle in degrees.
3181 # @return TRUE in case of success, FALSE otherwise.
3182 # @ingroup l2_modif_unitetri
3183 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3184 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3185 self.mesh.SetParameters(Parameters)
3186 if not IDsOfElements:
3187 IDsOfElements = self.GetElementsId()
3188 Functor = self.smeshpyD.GetFunctor(theCriterion)
3189 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3191 ## Fuses the neighbouring triangles of the object into quadrangles
3192 # @param theObject is mesh, submesh or group
3193 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3194 # choose a neighbour to fuse with.
3195 # Type SMESH.FunctorType._items in the Python Console to see all items.
3196 # Note that not all items corresponds to numerical functors.
3197 # @param MaxAngle a max angle between element normals at which the fusion
3198 # is still performed; theMaxAngle is mesured in radians.
3199 # @return TRUE in case of success, FALSE otherwise.
3200 # @ingroup l2_modif_unitetri
3201 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3202 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3203 self.mesh.SetParameters(Parameters)
3204 if isinstance( theObject, Mesh ):
3205 theObject = theObject.GetMesh()
3206 Functor = self.smeshpyD.GetFunctor(theCriterion)
3207 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3209 ## Splits quadrangles into triangles.
3210 # @param IDsOfElements the faces to be splitted.
3211 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3212 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3213 # value, then quadrangles will be split by the smallest diagonal.
3214 # Type SMESH.FunctorType._items in the Python Console to see all items.
3215 # Note that not all items corresponds to numerical functors.
3216 # @return TRUE in case of success, FALSE otherwise.
3217 # @ingroup l2_modif_cutquadr
3218 def QuadToTri (self, IDsOfElements, theCriterion = None):
3219 if IDsOfElements == []:
3220 IDsOfElements = self.GetElementsId()
3221 if theCriterion is None:
3222 theCriterion = FT_MaxElementLength2D
3223 Functor = self.smeshpyD.GetFunctor(theCriterion)
3224 return self.editor.QuadToTri(IDsOfElements, Functor)
3226 ## Splits quadrangles into triangles.
3227 # @param theObject the object from which the list of elements is taken,
3228 # this is mesh, submesh or group
3229 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3230 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3231 # value, then quadrangles will be split by the smallest diagonal.
3232 # Type SMESH.FunctorType._items in the Python Console to see all items.
3233 # Note that not all items corresponds to numerical functors.
3234 # @return TRUE in case of success, FALSE otherwise.
3235 # @ingroup l2_modif_cutquadr
3236 def QuadToTriObject (self, theObject, theCriterion = None):
3237 if ( isinstance( theObject, Mesh )):
3238 theObject = theObject.GetMesh()
3239 if theCriterion is None:
3240 theCriterion = FT_MaxElementLength2D
3241 Functor = self.smeshpyD.GetFunctor(theCriterion)
3242 return self.editor.QuadToTriObject(theObject, Functor)
3244 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3246 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3247 # group or a list of face IDs. By default all quadrangles are split
3248 # @ingroup l2_modif_cutquadr
3249 def QuadTo4Tri (self, theElements=[]):
3250 unRegister = genObjUnRegister()
3251 if isinstance( theElements, Mesh ):
3252 theElements = theElements.mesh
3253 elif not theElements:
3254 theElements = self.mesh
3255 elif isinstance( theElements, list ):
3256 theElements = self.GetIDSource( theElements, SMESH.FACE )
3257 unRegister.set( theElements )
3258 return self.editor.QuadTo4Tri( theElements )
3260 ## Splits quadrangles into triangles.
3261 # @param IDsOfElements the faces to be splitted
3262 # @param Diag13 is used to choose a diagonal for splitting.
3263 # @return TRUE in case of success, FALSE otherwise.
3264 # @ingroup l2_modif_cutquadr
3265 def SplitQuad (self, IDsOfElements, Diag13):
3266 if IDsOfElements == []:
3267 IDsOfElements = self.GetElementsId()
3268 return self.editor.SplitQuad(IDsOfElements, Diag13)
3270 ## Splits quadrangles into triangles.
3271 # @param theObject the object from which the list of elements is taken,
3272 # this is mesh, submesh or group
3273 # @param Diag13 is used to choose a diagonal for splitting.
3274 # @return TRUE in case of success, FALSE otherwise.
3275 # @ingroup l2_modif_cutquadr
3276 def SplitQuadObject (self, theObject, Diag13):
3277 if ( isinstance( theObject, Mesh )):
3278 theObject = theObject.GetMesh()
3279 return self.editor.SplitQuadObject(theObject, Diag13)
3281 ## Finds a better splitting of the given quadrangle.
3282 # @param IDOfQuad the ID of the quadrangle to be splitted.
3283 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3284 # choose a diagonal for splitting.
3285 # Type SMESH.FunctorType._items in the Python Console to see all items.
3286 # Note that not all items corresponds to numerical functors.
3287 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3288 # diagonal is better, 0 if error occurs.
3289 # @ingroup l2_modif_cutquadr
3290 def BestSplit (self, IDOfQuad, theCriterion):
3291 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))