1 # Copyright (C) 2007-2013 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.
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
96 ## @addtogroup l1_auxiliary
99 ## Converts an angle from degrees to radians
100 def DegreesToRadians(AngleInDegrees):
102 return AngleInDegrees * pi / 180.0
104 import salome_notebook
105 notebook = salome_notebook.notebook
106 # Salome notebook variable separator
109 ## Return list of variable values from salome notebook.
110 # The last argument, if is callable, is used to modify values got from notebook
111 def ParseParameters(*args):
116 if args and callable( args[-1] ):
117 args, varModifFun = args[:-1], args[-1]
118 for parameter in args:
120 Parameters += str(parameter) + var_separator
122 if isinstance(parameter,str):
123 # check if there is an inexistent variable name
124 if not notebook.isVariable(parameter):
125 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
126 parameter = notebook.get(parameter)
129 parameter = varModifFun(parameter)
132 Result.append(parameter)
135 Parameters = Parameters[:-1]
136 Result.append( Parameters )
137 Result.append( hasVariables )
140 # Parse parameters converting variables to radians
141 def ParseAngles(*args):
142 return ParseParameters( *( args + (DegreesToRadians, )))
144 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
145 # Parameters are stored in PointStruct.parameters attribute
146 def __initPointStruct(point,*args):
147 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
149 SMESH.PointStruct.__init__ = __initPointStruct
151 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
152 # Parameters are stored in AxisStruct.parameters attribute
153 def __initAxisStruct(ax,*args):
154 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
156 SMESH.AxisStruct.__init__ = __initAxisStruct
158 smeshPrecisionConfusion = 1.e-07
159 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
160 if abs(val1 - val2) < tol:
170 if isinstance(obj, SALOMEDS._objref_SObject):
174 ior = salome.orb.object_to_string(obj)
179 studies = salome.myStudyManager.GetOpenStudies()
180 for sname in studies:
181 s = salome.myStudyManager.GetStudyByName(sname)
183 sobj = s.FindObjectIOR(ior)
184 if not sobj: continue
185 return sobj.GetName()
186 if hasattr(obj, "GetName"):
187 # unknown CORBA object, having GetName() method
190 # unknown CORBA object, no GetName() method
193 if hasattr(obj, "GetName"):
194 # unknown non-CORBA object, having GetName() method
197 raise RuntimeError, "Null or invalid object"
199 ## Prints error message if a hypothesis was not assigned.
200 def TreatHypoStatus(status, hypName, geomName, isAlgo):
202 hypType = "algorithm"
204 hypType = "hypothesis"
206 if status == HYP_UNKNOWN_FATAL :
207 reason = "for unknown reason"
208 elif status == HYP_INCOMPATIBLE :
209 reason = "this hypothesis mismatches the algorithm"
210 elif status == HYP_NOTCONFORM :
211 reason = "a non-conform mesh would be built"
212 elif status == HYP_ALREADY_EXIST :
213 if isAlgo: return # it does not influence anything
214 reason = hypType + " of the same dimension is already assigned to this shape"
215 elif status == HYP_BAD_DIM :
216 reason = hypType + " mismatches the shape"
217 elif status == HYP_CONCURENT :
218 reason = "there are concurrent hypotheses on sub-shapes"
219 elif status == HYP_BAD_SUBSHAPE :
220 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
221 elif status == HYP_BAD_GEOMETRY:
222 reason = "geometry mismatches the expectation of the algorithm"
223 elif status == HYP_HIDDEN_ALGO:
224 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
225 elif status == HYP_HIDING_ALGO:
226 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
227 elif status == HYP_NEED_SHAPE:
228 reason = "Algorithm can't work without shape"
231 hypName = '"' + hypName + '"'
232 geomName= '"' + geomName+ '"'
233 if status < HYP_UNKNOWN_FATAL and not geomName =='""':
234 print hypName, "was assigned to", geomName,"but", reason
235 elif not geomName == '""':
236 print hypName, "was not assigned to",geomName,":", reason
238 print hypName, "was not assigned:", reason
241 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
242 def AssureGeomPublished(mesh, geom, name=''):
243 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
245 if not geom.GetStudyEntry() and \
246 mesh.smeshpyD.GetCurrentStudy():
248 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
249 if studyID != mesh.geompyD.myStudyId:
250 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
252 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
253 # for all groups SubShapeName() returns "Compound_-1"
254 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
256 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
258 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
261 ## Return the first vertex of a geometrical edge by ignoring orientation
262 def FirstVertexOnCurve(mesh, edge):
263 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
265 raise TypeError, "Given object has no vertices"
266 if len( vv ) == 1: return vv[0]
267 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
268 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
269 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
270 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
273 dist1 += abs( xyz[i] - xyz1[i] )
274 dist2 += abs( xyz[i] - xyz2[i] )
280 # end of l1_auxiliary
284 # Warning: smeshInst is a singleton
290 ## This class allows to create, load or manipulate meshes
291 # It has a set of methods to create load or copy meshes, to combine several meshes.
292 # It also has methods to get infos on meshes.
293 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
295 # MirrorType enumeration
296 POINT = SMESH_MeshEditor.POINT
297 AXIS = SMESH_MeshEditor.AXIS
298 PLANE = SMESH_MeshEditor.PLANE
300 # Smooth_Method enumeration
301 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
302 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
304 PrecisionConfusion = smeshPrecisionConfusion
306 # TopAbs_State enumeration
307 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
309 # Methods of splitting a hexahedron into tetrahedra
310 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
316 #print "==== __new__", engine, smeshInst, doLcc
318 if smeshInst is None:
319 # smesh engine is either retrieved from engine, or created
321 # Following test avoids a recursive loop
323 if smeshInst is not None:
324 # smesh engine not created: existing engine found
328 # FindOrLoadComponent called:
329 # 1. CORBA resolution of server
330 # 2. the __new__ method is called again
331 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
332 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
334 # FindOrLoadComponent not called
335 if smeshInst is None:
336 # smeshBuilder instance is created from lcc.FindOrLoadComponent
337 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
338 smeshInst = super(smeshBuilder,cls).__new__(cls)
340 # smesh engine not created: existing engine found
341 #print "==== existing ", engine, smeshInst, doLcc
343 #print "====1 ", smeshInst
346 #print "====2 ", smeshInst
351 #print "--------------- smeshbuilder __init__ ---", created
354 SMESH._objref_SMESH_Gen.__init__(self)
356 ## Dump component to the Python script
357 # This method overrides IDL function to allow default values for the parameters.
358 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
359 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
361 ## Set mode of DumpPython(), \a historical or \a snapshot.
362 # In the \a historical mode, the Python Dump script includes all commands
363 # performed by SMESH engine. In the \a snapshot mode, commands
364 # relating to objects removed from the Study are excluded from the script
365 # as well as commands not influencing the current state of meshes
366 def SetDumpPythonHistorical(self, isHistorical):
367 if isHistorical: val = "true"
369 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
371 ## Sets the current study and Geometry component
372 # @ingroup l1_auxiliary
373 def init_smesh(self,theStudy,geompyD = None):
375 self.SetCurrentStudy(theStudy,geompyD)
377 ## Creates an empty Mesh. This mesh can have an underlying geometry.
378 # @param obj the Geometrical object on which the mesh is built. If not defined,
379 # the mesh will have no underlying geometry.
380 # @param name the name for the new mesh.
381 # @return an instance of Mesh class.
382 # @ingroup l2_construct
383 def Mesh(self, obj=0, name=0):
384 if isinstance(obj,str):
386 return Mesh(self,self.geompyD,obj,name)
388 ## Returns a long value from enumeration
389 # @ingroup l1_controls
390 def EnumToLong(self,theItem):
393 ## Returns a string representation of the color.
394 # To be used with filters.
395 # @param c color value (SALOMEDS.Color)
396 # @ingroup l1_controls
397 def ColorToString(self,c):
399 if isinstance(c, SALOMEDS.Color):
400 val = "%s;%s;%s" % (c.R, c.G, c.B)
401 elif isinstance(c, str):
404 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
407 ## Gets PointStruct from vertex
408 # @param theVertex a GEOM object(vertex)
409 # @return SMESH.PointStruct
410 # @ingroup l1_auxiliary
411 def GetPointStruct(self,theVertex):
412 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
413 return PointStruct(x,y,z)
415 ## Gets DirStruct from vector
416 # @param theVector a GEOM object(vector)
417 # @return SMESH.DirStruct
418 # @ingroup l1_auxiliary
419 def GetDirStruct(self,theVector):
420 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
421 if(len(vertices) != 2):
422 print "Error: vector object is incorrect."
424 p1 = self.geompyD.PointCoordinates(vertices[0])
425 p2 = self.geompyD.PointCoordinates(vertices[1])
426 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
427 dirst = DirStruct(pnt)
430 ## Makes DirStruct from a triplet
431 # @param x,y,z vector components
432 # @return SMESH.DirStruct
433 # @ingroup l1_auxiliary
434 def MakeDirStruct(self,x,y,z):
435 pnt = PointStruct(x,y,z)
436 return DirStruct(pnt)
438 ## Get AxisStruct from object
439 # @param theObj a GEOM object (line or plane)
440 # @return SMESH.AxisStruct
441 # @ingroup l1_auxiliary
442 def GetAxisStruct(self,theObj):
443 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
445 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
446 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
447 vertex1 = self.geompyD.PointCoordinates(vertex1)
448 vertex2 = self.geompyD.PointCoordinates(vertex2)
449 vertex3 = self.geompyD.PointCoordinates(vertex3)
450 vertex4 = self.geompyD.PointCoordinates(vertex4)
451 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
452 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
453 normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
454 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
456 elif len(edges) == 1:
457 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
458 p1 = self.geompyD.PointCoordinates( vertex1 )
459 p2 = self.geompyD.PointCoordinates( vertex2 )
460 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
464 # From SMESH_Gen interface:
465 # ------------------------
467 ## Sets the given name to the object
468 # @param obj the object to rename
469 # @param name a new object name
470 # @ingroup l1_auxiliary
471 def SetName(self, obj, name):
472 if isinstance( obj, Mesh ):
474 elif isinstance( obj, Mesh_Algorithm ):
475 obj = obj.GetAlgorithm()
476 ior = salome.orb.object_to_string(obj)
477 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
479 ## Sets the current mode
480 # @ingroup l1_auxiliary
481 def SetEmbeddedMode( self,theMode ):
482 #self.SetEmbeddedMode(theMode)
483 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
485 ## Gets the current mode
486 # @ingroup l1_auxiliary
487 def IsEmbeddedMode(self):
488 #return self.IsEmbeddedMode()
489 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
491 ## Sets the current study
492 # @ingroup l1_auxiliary
493 def SetCurrentStudy( self, theStudy, geompyD = None ):
494 #self.SetCurrentStudy(theStudy)
496 from salome.geom import geomBuilder
497 geompyD = geomBuilder.geom
500 self.SetGeomEngine(geompyD)
501 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
504 notebook = salome_notebook.NoteBook( theStudy )
506 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
508 ## Gets the current study
509 # @ingroup l1_auxiliary
510 def GetCurrentStudy(self):
511 #return self.GetCurrentStudy()
512 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
514 ## Creates a Mesh object importing data from the given UNV file
515 # @return an instance of Mesh class
517 def CreateMeshesFromUNV( self,theFileName ):
518 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
519 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
522 ## Creates a Mesh object(s) importing data from the given MED file
523 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
525 def CreateMeshesFromMED( self,theFileName ):
526 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
527 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
528 return aMeshes, aStatus
530 ## Creates a Mesh object(s) importing data from the given SAUV file
531 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
533 def CreateMeshesFromSAUV( self,theFileName ):
534 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
535 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
536 return aMeshes, aStatus
538 ## Creates a Mesh object importing data from the given STL file
539 # @return an instance of Mesh class
541 def CreateMeshesFromSTL( self, theFileName ):
542 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
543 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
546 ## Creates Mesh objects importing data from the given CGNS file
547 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
549 def CreateMeshesFromCGNS( self, theFileName ):
550 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
551 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
552 return aMeshes, aStatus
554 ## Creates a Mesh object importing data from the given GMF file.
555 # GMF files must have .mesh extension for the ASCII format and .meshb for
557 # @return [ an instance of Mesh class, SMESH.ComputeError ]
559 def CreateMeshesFromGMF( self, theFileName ):
560 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
563 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
564 return Mesh(self, self.geompyD, aSmeshMesh), error
566 ## Concatenate the given meshes into one mesh.
567 # @return an instance of Mesh class
568 # @param meshes the meshes to combine into one mesh
569 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
570 # @param mergeNodesAndElements if true, equal nodes and elements aremerged
571 # @param mergeTolerance tolerance for merging nodes
572 # @param allGroups forces creation of groups of all elements
573 # @param name name of a new mesh
574 def Concatenate( self, meshes, uniteIdenticalGroups,
575 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
577 if not meshes: return None
578 for i,m in enumerate(meshes):
579 if isinstance(m, Mesh):
580 meshes[i] = m.GetMesh()
581 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
582 meshes[0].SetParameters(Parameters)
584 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
585 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
587 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
588 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
589 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
592 ## Create a mesh by copying a part of another mesh.
593 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
594 # to copy nodes or elements not contained in any mesh object,
595 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
596 # @param meshName a name of the new mesh
597 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
598 # @param toKeepIDs to preserve IDs of the copied elements or not
599 # @return an instance of Mesh class
600 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
601 if (isinstance( meshPart, Mesh )):
602 meshPart = meshPart.GetMesh()
603 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
604 return Mesh(self, self.geompyD, mesh)
606 ## From SMESH_Gen interface
607 # @return the list of integer values
608 # @ingroup l1_auxiliary
609 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
610 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
612 ## From SMESH_Gen interface. Creates a pattern
613 # @return an instance of SMESH_Pattern
615 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
616 # @ingroup l2_modif_patterns
617 def GetPattern(self):
618 return SMESH._objref_SMESH_Gen.GetPattern(self)
620 ## Sets number of segments per diagonal of boundary box of geometry by which
621 # default segment length of appropriate 1D hypotheses is defined.
622 # Default value is 10
623 # @ingroup l1_auxiliary
624 def SetBoundaryBoxSegmentation(self, nbSegments):
625 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
627 # Filtering. Auxiliary functions:
628 # ------------------------------
630 ## Creates an empty criterion
631 # @return SMESH.Filter.Criterion
632 # @ingroup l1_controls
633 def GetEmptyCriterion(self):
634 Type = self.EnumToLong(FT_Undefined)
635 Compare = self.EnumToLong(FT_Undefined)
639 UnaryOp = self.EnumToLong(FT_Undefined)
640 BinaryOp = self.EnumToLong(FT_Undefined)
643 Precision = -1 ##@1e-07
644 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
645 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
647 ## Creates a criterion by the given parameters
648 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
649 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
650 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
651 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
652 # @param Threshold the threshold value (range of ids as string, shape, numeric)
653 # @param UnaryOp FT_LogicalNOT or FT_Undefined
654 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
655 # FT_Undefined (must be for the last criterion of all criteria)
656 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
657 # FT_LyingOnGeom, FT_CoplanarFaces criteria
658 # @return SMESH.Filter.Criterion
660 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
661 # @ingroup l1_controls
662 def GetCriterion(self,elementType,
664 Compare = FT_EqualTo,
666 UnaryOp=FT_Undefined,
667 BinaryOp=FT_Undefined,
669 if not CritType in SMESH.FunctorType._items:
670 raise TypeError, "CritType should be of SMESH.FunctorType"
671 aCriterion = self.GetEmptyCriterion()
672 aCriterion.TypeOfElement = elementType
673 aCriterion.Type = self.EnumToLong(CritType)
674 aCriterion.Tolerance = Tolerance
676 aThreshold = Threshold
678 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
679 aCriterion.Compare = self.EnumToLong(Compare)
680 elif Compare == "=" or Compare == "==":
681 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
683 aCriterion.Compare = self.EnumToLong(FT_LessThan)
685 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
686 elif Compare != FT_Undefined:
687 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
690 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
691 FT_BelongToCylinder, FT_LyingOnGeom]:
692 # Checks that Threshold is GEOM object
693 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
694 aCriterion.ThresholdStr = GetName(aThreshold)
695 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
696 if not aCriterion.ThresholdID:
697 name = aCriterion.ThresholdStr
699 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
700 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
701 #raise RuntimeError, "Threshold shape must be published"
703 print "Error: The Threshold should be a shape."
705 if isinstance(UnaryOp,float):
706 aCriterion.Tolerance = UnaryOp
707 UnaryOp = FT_Undefined
709 elif CritType == FT_RangeOfIds:
710 # Checks that Threshold is string
711 if isinstance(aThreshold, str):
712 aCriterion.ThresholdStr = aThreshold
714 print "Error: The Threshold should be a string."
716 elif CritType == FT_CoplanarFaces:
717 # Checks the Threshold
718 if isinstance(aThreshold, int):
719 aCriterion.ThresholdID = str(aThreshold)
720 elif isinstance(aThreshold, str):
723 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
724 aCriterion.ThresholdID = aThreshold
727 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
728 elif CritType == FT_ConnectedElements:
729 # Checks the Threshold
730 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
731 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
732 if not aCriterion.ThresholdID:
733 name = aThreshold.GetName()
735 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
736 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
737 elif isinstance(aThreshold, int): # node id
738 aCriterion.Threshold = aThreshold
739 elif isinstance(aThreshold, list): # 3 point coordinates
740 if len( aThreshold ) < 3:
741 raise ValueError, "too few point coordinates, must be 3"
742 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
743 elif isinstance(aThreshold, str):
744 if aThreshold.isdigit():
745 aCriterion.Threshold = aThreshold # node id
747 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
750 "The Threshold should either a VERTEX, or a node ID, "\
751 "or a list of point coordinates and not '%s'"%aThreshold
752 elif CritType == FT_ElemGeomType:
753 # Checks the Threshold
755 aCriterion.Threshold = self.EnumToLong(aThreshold)
756 assert( aThreshold in SMESH.GeometryType._items )
758 if isinstance(aThreshold, int):
759 aCriterion.Threshold = aThreshold
761 print "Error: The Threshold should be an integer or SMESH.GeometryType."
765 elif CritType == FT_EntityType:
766 # Checks the Threshold
768 aCriterion.Threshold = self.EnumToLong(aThreshold)
769 assert( aThreshold in SMESH.EntityType._items )
771 if isinstance(aThreshold, int):
772 aCriterion.Threshold = aThreshold
774 print "Error: The Threshold should be an integer or SMESH.EntityType."
779 elif CritType == FT_GroupColor:
780 # Checks the Threshold
782 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
784 print "Error: The threshold value should be of SALOMEDS.Color type"
787 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
788 FT_LinearOrQuadratic, FT_BadOrientedVolume,
789 FT_BareBorderFace, FT_BareBorderVolume,
790 FT_OverConstrainedFace, FT_OverConstrainedVolume,
791 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
792 # At this point the Threshold is unnecessary
793 if aThreshold == FT_LogicalNOT:
794 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
795 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
796 aCriterion.BinaryOp = aThreshold
800 aThreshold = float(aThreshold)
801 aCriterion.Threshold = aThreshold
803 print "Error: The Threshold should be a number."
806 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
807 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
809 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
810 aCriterion.BinaryOp = self.EnumToLong(Threshold)
812 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
813 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
815 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
816 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
820 ## Creates a filter with the given parameters
821 # @param elementType the type of elements in the group
822 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
823 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
824 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
825 # @param UnaryOp FT_LogicalNOT or FT_Undefined
826 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
827 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
828 # @param mesh the mesh to initialize the filter with
829 # @return SMESH_Filter
831 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
832 # @ingroup l1_controls
833 def GetFilter(self,elementType,
834 CritType=FT_Undefined,
837 UnaryOp=FT_Undefined,
840 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
841 aFilterMgr = self.CreateFilterManager()
842 aFilter = aFilterMgr.CreateFilter()
844 aCriteria.append(aCriterion)
845 aFilter.SetCriteria(aCriteria)
847 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
848 else : aFilter.SetMesh( mesh )
849 aFilterMgr.UnRegister()
852 ## Creates a filter from criteria
853 # @param criteria a list of criteria
854 # @param binOp binary operator used when binary operator of criteria is undefined
855 # @return SMESH_Filter
857 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
858 # @ingroup l1_controls
859 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
860 for i in range( len( criteria ) - 1 ):
861 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
862 criteria[i].BinaryOp = self.EnumToLong( binOp )
863 aFilterMgr = self.CreateFilterManager()
864 aFilter = aFilterMgr.CreateFilter()
865 aFilter.SetCriteria(criteria)
866 aFilterMgr.UnRegister()
869 ## Creates a numerical functor by its type
870 # @param theCriterion FT_...; functor type
871 # @return SMESH_NumericalFunctor
872 # @ingroup l1_controls
873 def GetFunctor(self,theCriterion):
874 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
876 aFilterMgr = self.CreateFilterManager()
878 if theCriterion == FT_AspectRatio:
879 functor = aFilterMgr.CreateAspectRatio()
880 elif theCriterion == FT_AspectRatio3D:
881 functor = aFilterMgr.CreateAspectRatio3D()
882 elif theCriterion == FT_Warping:
883 functor = aFilterMgr.CreateWarping()
884 elif theCriterion == FT_MinimumAngle:
885 functor = aFilterMgr.CreateMinimumAngle()
886 elif theCriterion == FT_Taper:
887 functor = aFilterMgr.CreateTaper()
888 elif theCriterion == FT_Skew:
889 functor = aFilterMgr.CreateSkew()
890 elif theCriterion == FT_Area:
891 functor = aFilterMgr.CreateArea()
892 elif theCriterion == FT_Volume3D:
893 functor = aFilterMgr.CreateVolume3D()
894 elif theCriterion == FT_MaxElementLength2D:
895 functor = aFilterMgr.CreateMaxElementLength2D()
896 elif theCriterion == FT_MaxElementLength3D:
897 functor = aFilterMgr.CreateMaxElementLength3D()
898 elif theCriterion == FT_MultiConnection:
899 functor = aFilterMgr.CreateMultiConnection()
900 elif theCriterion == FT_MultiConnection2D:
901 functor = aFilterMgr.CreateMultiConnection2D()
902 elif theCriterion == FT_Length:
903 functor = aFilterMgr.CreateLength()
904 elif theCriterion == FT_Length2D:
905 functor = aFilterMgr.CreateLength2D()
907 print "Error: given parameter is not numerical functor type."
908 aFilterMgr.UnRegister()
911 ## Creates hypothesis
912 # @param theHType mesh hypothesis type (string)
913 # @param theLibName mesh plug-in library name
914 # @return created hypothesis instance
915 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
916 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
918 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
921 # wrap hypothesis methods
922 #print "HYPOTHESIS", theHType
923 for meth_name in dir( hyp.__class__ ):
924 if not meth_name.startswith("Get") and \
925 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
926 method = getattr ( hyp.__class__, meth_name )
928 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
932 ## Gets the mesh statistic
933 # @return dictionary "element type" - "count of elements"
934 # @ingroup l1_meshinfo
935 def GetMeshInfo(self, obj):
936 if isinstance( obj, Mesh ):
939 if hasattr(obj, "GetMeshInfo"):
940 values = obj.GetMeshInfo()
941 for i in range(SMESH.Entity_Last._v):
942 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
946 ## Get minimum distance between two objects
948 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
949 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
951 # @param src1 first source object
952 # @param src2 second source object
953 # @param id1 node/element id from the first source
954 # @param id2 node/element id from the second (or first) source
955 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
956 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
957 # @return minimum distance value
958 # @sa GetMinDistance()
959 # @ingroup l1_measurements
960 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
961 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
965 result = result.value
968 ## Get measure structure specifying minimum distance data between two objects
970 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
971 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
973 # @param src1 first source object
974 # @param src2 second source object
975 # @param id1 node/element id from the first source
976 # @param id2 node/element id from the second (or first) source
977 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
978 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
979 # @return Measure structure or None if input data is invalid
981 # @ingroup l1_measurements
982 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
983 if isinstance(src1, Mesh): src1 = src1.mesh
984 if isinstance(src2, Mesh): src2 = src2.mesh
985 if src2 is None and id2 != 0: src2 = src1
986 if not hasattr(src1, "_narrow"): return None
987 src1 = src1._narrow(SMESH.SMESH_IDSource)
988 if not src1: return None
989 unRegister = genObjUnRegister()
992 e = m.GetMeshEditor()
994 src1 = e.MakeIDSource([id1], SMESH.FACE)
996 src1 = e.MakeIDSource([id1], SMESH.NODE)
997 unRegister.set( src1 )
999 if hasattr(src2, "_narrow"):
1000 src2 = src2._narrow(SMESH.SMESH_IDSource)
1001 if src2 and id2 != 0:
1003 e = m.GetMeshEditor()
1005 src2 = e.MakeIDSource([id2], SMESH.FACE)
1007 src2 = e.MakeIDSource([id2], SMESH.NODE)
1008 unRegister.set( src2 )
1011 aMeasurements = self.CreateMeasurements()
1012 unRegister.set( aMeasurements )
1013 result = aMeasurements.MinDistance(src1, src2)
1016 ## Get bounding box of the specified object(s)
1017 # @param objects single source object or list of source objects
1018 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1019 # @sa GetBoundingBox()
1020 # @ingroup l1_measurements
1021 def BoundingBox(self, objects):
1022 result = self.GetBoundingBox(objects)
1026 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1029 ## Get measure structure specifying bounding box data of the specified object(s)
1030 # @param objects single source object or list of source objects
1031 # @return Measure structure
1033 # @ingroup l1_measurements
1034 def GetBoundingBox(self, objects):
1035 if isinstance(objects, tuple):
1036 objects = list(objects)
1037 if not isinstance(objects, list):
1041 if isinstance(o, Mesh):
1042 srclist.append(o.mesh)
1043 elif hasattr(o, "_narrow"):
1044 src = o._narrow(SMESH.SMESH_IDSource)
1045 if src: srclist.append(src)
1048 aMeasurements = self.CreateMeasurements()
1049 result = aMeasurements.BoundingBox(srclist)
1050 aMeasurements.UnRegister()
1053 ## Get sum of lengths of all 1D elements in the mesh object.
1054 # @param obj mesh, submesh or group
1055 # @return sum of lengths of all 1D elements
1056 # @ingroup l1_measurements
1057 def GetLength(self, obj):
1058 if isinstance(obj, Mesh): obj = obj.mesh
1059 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1060 aMeasurements = self.CreateMeasurements()
1061 value = aMeasurements.Length(obj)
1062 aMeasurements.UnRegister()
1065 ## Get sum of areas of all 2D elements in the mesh object.
1066 # @param obj mesh, submesh or group
1067 # @return sum of areas of all 2D elements
1068 # @ingroup l1_measurements
1069 def GetArea(self, obj):
1070 if isinstance(obj, Mesh): obj = obj.mesh
1071 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1072 aMeasurements = self.CreateMeasurements()
1073 value = aMeasurements.Area(obj)
1074 aMeasurements.UnRegister()
1077 ## Get sum of volumes of all 3D elements in the mesh object.
1078 # @param obj mesh, submesh or group
1079 # @return sum of volumes of all 3D elements
1080 # @ingroup l1_measurements
1081 def GetVolume(self, obj):
1082 if isinstance(obj, Mesh): obj = obj.mesh
1083 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1084 aMeasurements = self.CreateMeasurements()
1085 value = aMeasurements.Volume(obj)
1086 aMeasurements.UnRegister()
1089 pass # end of class smeshBuilder
1092 #Registering the new proxy for SMESH_Gen
1093 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1095 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1096 # interface to create or load meshes.
1101 # salome.salome_init()
1102 # from salome.smesh import smeshBuilder
1103 # smesh = smeshBuilder.New(theStudy)
1105 # @param study SALOME study, generally obtained by salome.myStudy.
1106 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1107 # @return smeshBuilder instance
1109 def New( study, instance=None):
1111 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1112 interface to create or load meshes.
1116 salome.salome_init()
1117 from salome.smesh import smeshBuilder
1118 smesh = smeshBuilder.New(theStudy)
1121 study SALOME study, generally obtained by salome.myStudy.
1122 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1124 smeshBuilder instance
1132 smeshInst = smeshBuilder()
1133 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1134 smeshInst.init_smesh(study)
1138 # Public class: Mesh
1139 # ==================
1141 ## This class allows defining and managing a mesh.
1142 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1143 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1144 # new nodes and elements and by changing the existing entities), to get information
1145 # about a mesh and to export a mesh into different formats.
1154 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1155 # sets the GUI name of this mesh to \a name.
1156 # @param smeshpyD an instance of smeshBuilder class
1157 # @param geompyD an instance of geomBuilder class
1158 # @param obj Shape to be meshed or SMESH_Mesh object
1159 # @param name Study name of the mesh
1160 # @ingroup l2_construct
1161 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1162 self.smeshpyD=smeshpyD
1163 self.geompyD=geompyD
1168 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1171 # publish geom of mesh (issue 0021122)
1172 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1174 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1175 if studyID != geompyD.myStudyId:
1176 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1179 geo_name = name + " shape"
1181 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1182 geompyD.addToStudy( self.geom, geo_name )
1183 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1185 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1188 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1190 self.smeshpyD.SetName(self.mesh, name)
1192 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1195 self.geom = self.mesh.GetShapeToMesh()
1197 self.editor = self.mesh.GetMeshEditor()
1198 self.functors = [None] * SMESH.FT_Undefined._v
1200 # set self to algoCreator's
1201 for attrName in dir(self):
1202 attr = getattr( self, attrName )
1203 if isinstance( attr, algoCreator ):
1204 #print "algoCreator ", attrName
1205 setattr( self, attrName, attr.copy( self ))
1210 ## Destructor. Clean-up resources
1213 #self.mesh.UnRegister()
1217 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1218 # @param theMesh a SMESH_Mesh object
1219 # @ingroup l2_construct
1220 def SetMesh(self, theMesh):
1221 # do not call Register() as this prevents mesh servant deletion at closing study
1222 #if self.mesh: self.mesh.UnRegister()
1225 #self.mesh.Register()
1226 self.geom = self.mesh.GetShapeToMesh()
1229 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1230 # @return a SMESH_Mesh object
1231 # @ingroup l2_construct
1235 ## Gets the name of the mesh
1236 # @return the name of the mesh as a string
1237 # @ingroup l2_construct
1239 name = GetName(self.GetMesh())
1242 ## Sets a name to the mesh
1243 # @param name a new name of the mesh
1244 # @ingroup l2_construct
1245 def SetName(self, name):
1246 self.smeshpyD.SetName(self.GetMesh(), name)
1248 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1249 # The subMesh object gives access to the IDs of nodes and elements.
1250 # @param geom a geometrical object (shape)
1251 # @param name a name for the submesh
1252 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1253 # @ingroup l2_submeshes
1254 def GetSubMesh(self, geom, name):
1255 AssureGeomPublished( self, geom, name )
1256 submesh = self.mesh.GetSubMesh( geom, name )
1259 ## Returns the shape associated to the mesh
1260 # @return a GEOM_Object
1261 # @ingroup l2_construct
1265 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1266 # @param geom the shape to be meshed (GEOM_Object)
1267 # @ingroup l2_construct
1268 def SetShape(self, geom):
1269 self.mesh = self.smeshpyD.CreateMesh(geom)
1271 ## Loads mesh from the study after opening the study
1275 ## Returns true if the hypotheses are defined well
1276 # @param theSubObject a sub-shape of a mesh shape
1277 # @return True or False
1278 # @ingroup l2_construct
1279 def IsReadyToCompute(self, theSubObject):
1280 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1282 ## Returns errors of hypotheses definition.
1283 # The list of errors is empty if everything is OK.
1284 # @param theSubObject a sub-shape of a mesh shape
1285 # @return a list of errors
1286 # @ingroup l2_construct
1287 def GetAlgoState(self, theSubObject):
1288 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1290 ## Returns a geometrical object on which the given element was built.
1291 # The returned geometrical object, if not nil, is either found in the
1292 # study or published by this method with the given name
1293 # @param theElementID the id of the mesh element
1294 # @param theGeomName the user-defined name of the geometrical object
1295 # @return GEOM::GEOM_Object instance
1296 # @ingroup l2_construct
1297 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1298 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1300 ## Returns the mesh dimension depending on the dimension of the underlying shape
1301 # or, if the mesh is not based on any shape, basing on deimension of elements
1302 # @return mesh dimension as an integer value [0,3]
1303 # @ingroup l1_auxiliary
1304 def MeshDimension(self):
1305 if self.mesh.HasShapeToMesh():
1306 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1307 if len( shells ) > 0 :
1309 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1311 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1316 if self.NbVolumes() > 0: return 3
1317 if self.NbFaces() > 0: return 2
1318 if self.NbEdges() > 0: return 1
1321 ## Evaluates size of prospective mesh on a shape
1322 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1323 # To know predicted number of e.g. edges, inquire it this way
1324 # Evaluate()[ EnumToLong( Entity_Edge )]
1325 def Evaluate(self, geom=0):
1326 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1328 geom = self.mesh.GetShapeToMesh()
1331 return self.smeshpyD.Evaluate(self.mesh, geom)
1334 ## Computes the mesh and returns the status of the computation
1335 # @param geom geomtrical shape on which mesh data should be computed
1336 # @param discardModifs if True and the mesh has been edited since
1337 # a last total re-compute and that may prevent successful partial re-compute,
1338 # then the mesh is cleaned before Compute()
1339 # @return True or False
1340 # @ingroup l2_construct
1341 def Compute(self, geom=0, discardModifs=False):
1342 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1344 geom = self.mesh.GetShapeToMesh()
1349 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1351 ok = self.smeshpyD.Compute(self.mesh, geom)
1352 except SALOME.SALOME_Exception, ex:
1353 print "Mesh computation failed, exception caught:"
1354 print " ", ex.details.text
1357 print "Mesh computation failed, exception caught:"
1358 traceback.print_exc()
1362 # Treat compute errors
1363 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1364 for err in computeErrors:
1366 if self.mesh.HasShapeToMesh():
1368 mainIOR = salome.orb.object_to_string(geom)
1369 for sname in salome.myStudyManager.GetOpenStudies():
1370 s = salome.myStudyManager.GetStudyByName(sname)
1372 mainSO = s.FindObjectIOR(mainIOR)
1373 if not mainSO: continue
1374 if err.subShapeID == 1:
1375 shapeText = ' on "%s"' % mainSO.GetName()
1376 subIt = s.NewChildIterator(mainSO)
1378 subSO = subIt.Value()
1380 obj = subSO.GetObject()
1381 if not obj: continue
1382 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1384 ids = go.GetSubShapeIndices()
1385 if len(ids) == 1 and ids[0] == err.subShapeID:
1386 shapeText = ' on "%s"' % subSO.GetName()
1389 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1391 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1393 shapeText = " on subshape #%s" % (err.subShapeID)
1395 shapeText = " on subshape #%s" % (err.subShapeID)
1397 stdErrors = ["OK", #COMPERR_OK
1398 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1399 "std::exception", #COMPERR_STD_EXCEPTION
1400 "OCC exception", #COMPERR_OCC_EXCEPTION
1401 "..", #COMPERR_SLM_EXCEPTION
1402 "Unknown exception", #COMPERR_EXCEPTION
1403 "Memory allocation problem", #COMPERR_MEMORY_PB
1404 "Algorithm failed", #COMPERR_ALGO_FAILED
1405 "Unexpected geometry", #COMPERR_BAD_SHAPE
1406 "Warning", #COMPERR_WARNING
1407 "Computation cancelled",#COMPERR_CANCELED
1408 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1410 if err.code < len(stdErrors): errText = stdErrors[err.code]
1412 errText = "code %s" % -err.code
1413 if errText: errText += ". "
1414 errText += err.comment
1415 if allReasons != "":allReasons += "\n"
1417 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1419 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1423 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1425 if err.isGlobalAlgo:
1433 reason = '%s %sD algorithm is missing' % (glob, dim)
1434 elif err.state == HYP_MISSING:
1435 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1436 % (glob, dim, name, dim))
1437 elif err.state == HYP_NOTCONFORM:
1438 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1439 elif err.state == HYP_BAD_PARAMETER:
1440 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1441 % ( glob, dim, name ))
1442 elif err.state == HYP_BAD_GEOMETRY:
1443 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1444 'geometry' % ( glob, dim, name ))
1445 elif err.state == HYP_HIDDEN_ALGO:
1446 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1447 'algorithm of upper dimension generating %sD mesh'
1448 % ( glob, dim, name, glob, dim ))
1450 reason = ("For unknown reason. "
1451 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1453 if allReasons != "":allReasons += "\n"
1454 allReasons += "- " + reason
1456 if not ok or allReasons != "":
1457 msg = '"' + GetName(self.mesh) + '"'
1458 if ok: msg += " has been computed with warnings"
1459 else: msg += " has not been computed"
1460 if allReasons != "": msg += ":"
1465 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1466 smeshgui = salome.ImportComponentGUI("SMESH")
1467 smeshgui.Init(self.mesh.GetStudyId())
1468 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1469 salome.sg.updateObjBrowser(1)
1473 ## Return submesh objects list in meshing order
1474 # @return list of list of submesh objects
1475 # @ingroup l2_construct
1476 def GetMeshOrder(self):
1477 return self.mesh.GetMeshOrder()
1479 ## Return submesh objects list in meshing order
1480 # @return list of list of submesh objects
1481 # @ingroup l2_construct
1482 def SetMeshOrder(self, submeshes):
1483 return self.mesh.SetMeshOrder(submeshes)
1485 ## Removes all nodes and elements
1486 # @ingroup l2_construct
1489 if ( salome.sg.hasDesktop() and
1490 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1491 smeshgui = salome.ImportComponentGUI("SMESH")
1492 smeshgui.Init(self.mesh.GetStudyId())
1493 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1494 salome.sg.updateObjBrowser(1)
1496 ## Removes all nodes and elements of indicated shape
1497 # @ingroup l2_construct
1498 def ClearSubMesh(self, geomId):
1499 self.mesh.ClearSubMesh(geomId)
1500 if salome.sg.hasDesktop():
1501 smeshgui = salome.ImportComponentGUI("SMESH")
1502 smeshgui.Init(self.mesh.GetStudyId())
1503 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1504 salome.sg.updateObjBrowser(1)
1506 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1507 # @param fineness [0.0,1.0] defines mesh fineness
1508 # @return True or False
1509 # @ingroup l3_algos_basic
1510 def AutomaticTetrahedralization(self, fineness=0):
1511 dim = self.MeshDimension()
1513 self.RemoveGlobalHypotheses()
1514 self.Segment().AutomaticLength(fineness)
1516 self.Triangle().LengthFromEdges()
1519 from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1520 self.Tetrahedron(NETGEN)
1522 return self.Compute()
1524 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1525 # @param fineness [0.0, 1.0] defines mesh fineness
1526 # @return True or False
1527 # @ingroup l3_algos_basic
1528 def AutomaticHexahedralization(self, fineness=0):
1529 dim = self.MeshDimension()
1530 # assign the hypotheses
1531 self.RemoveGlobalHypotheses()
1532 self.Segment().AutomaticLength(fineness)
1539 return self.Compute()
1541 ## Assigns a hypothesis
1542 # @param hyp a hypothesis to assign
1543 # @param geom a subhape of mesh geometry
1544 # @return SMESH.Hypothesis_Status
1545 # @ingroup l2_hypotheses
1546 def AddHypothesis(self, hyp, geom=0):
1547 if isinstance( hyp, Mesh_Algorithm ):
1548 hyp = hyp.GetAlgorithm()
1553 geom = self.mesh.GetShapeToMesh()
1555 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1556 status = self.mesh.AddHypothesis(geom, hyp)
1557 isAlgo = hyp._narrow( SMESH_Algo )
1558 hyp_name = GetName( hyp )
1561 geom_name = GetName( geom )
1562 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1565 ## Return True if an algorithm of hypothesis is assigned to a given shape
1566 # @param hyp a hypothesis to check
1567 # @param geom a subhape of mesh geometry
1568 # @return True of False
1569 # @ingroup l2_hypotheses
1570 def IsUsedHypothesis(self, hyp, geom):
1571 if not hyp: # or not geom
1573 if isinstance( hyp, Mesh_Algorithm ):
1574 hyp = hyp.GetAlgorithm()
1576 hyps = self.GetHypothesisList(geom)
1578 if h.GetId() == hyp.GetId():
1582 ## Unassigns a hypothesis
1583 # @param hyp a hypothesis to unassign
1584 # @param geom a sub-shape of mesh geometry
1585 # @return SMESH.Hypothesis_Status
1586 # @ingroup l2_hypotheses
1587 def RemoveHypothesis(self, hyp, geom=0):
1590 if isinstance( hyp, Mesh_Algorithm ):
1591 hyp = hyp.GetAlgorithm()
1597 if self.IsUsedHypothesis( hyp, shape ):
1598 return self.mesh.RemoveHypothesis( shape, hyp )
1599 hypName = GetName( hyp )
1600 geoName = GetName( shape )
1601 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1604 ## Gets the list of hypotheses added on a geometry
1605 # @param geom a sub-shape of mesh geometry
1606 # @return the sequence of SMESH_Hypothesis
1607 # @ingroup l2_hypotheses
1608 def GetHypothesisList(self, geom):
1609 return self.mesh.GetHypothesisList( geom )
1611 ## Removes all global hypotheses
1612 # @ingroup l2_hypotheses
1613 def RemoveGlobalHypotheses(self):
1614 current_hyps = self.mesh.GetHypothesisList( self.geom )
1615 for hyp in current_hyps:
1616 self.mesh.RemoveHypothesis( self.geom, hyp )
1620 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1621 ## allowing to overwrite the file if it exists or add the exported data to its contents
1622 # @param f is the file name
1623 # @param auto_groups boolean parameter for creating/not creating
1624 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1625 # the typical use is auto_groups=false.
1626 # @param version MED format version(MED_V2_1 or MED_V2_2)
1627 # @param overwrite boolean parameter for overwriting/not overwriting the file
1628 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1629 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1630 # - 1D if all mesh nodes lie on OX coordinate axis, or
1631 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1632 # - 3D in the rest cases.
1634 # If @a autoDimension is @c False, the space dimension is always 3.
1635 # @ingroup l2_impexp
1636 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1637 overwrite=1, meshPart=None, autoDimension=True):
1639 unRegister = genObjUnRegister()
1640 if isinstance( meshPart, list ):
1641 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1642 unRegister.set( meshPart )
1643 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension)
1645 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1647 ## Exports the mesh in a file in SAUV format
1648 # @param f is the file name
1649 # @param auto_groups boolean parameter for creating/not creating
1650 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1651 # the typical use is auto_groups=false.
1652 # @ingroup l2_impexp
1653 def ExportSAUV(self, f, auto_groups=0):
1654 self.mesh.ExportSAUV(f, auto_groups)
1656 ## Exports the mesh in a file in DAT format
1657 # @param f the file name
1658 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1659 # @ingroup l2_impexp
1660 def ExportDAT(self, f, meshPart=None):
1662 unRegister = genObjUnRegister()
1663 if isinstance( meshPart, list ):
1664 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1665 unRegister.set( meshPart )
1666 self.mesh.ExportPartToDAT( meshPart, f )
1668 self.mesh.ExportDAT(f)
1670 ## Exports the mesh in a file in UNV format
1671 # @param f the file name
1672 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1673 # @ingroup l2_impexp
1674 def ExportUNV(self, f, meshPart=None):
1676 unRegister = genObjUnRegister()
1677 if isinstance( meshPart, list ):
1678 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1679 unRegister.set( meshPart )
1680 self.mesh.ExportPartToUNV( meshPart, f )
1682 self.mesh.ExportUNV(f)
1684 ## Export the mesh in a file in STL format
1685 # @param f the file name
1686 # @param ascii defines the file encoding
1687 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1688 # @ingroup l2_impexp
1689 def ExportSTL(self, f, ascii=1, meshPart=None):
1691 unRegister = genObjUnRegister()
1692 if isinstance( meshPart, list ):
1693 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1694 unRegister.set( meshPart )
1695 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1697 self.mesh.ExportSTL(f, ascii)
1699 ## Exports the mesh in a file in CGNS format
1700 # @param f is the file name
1701 # @param overwrite boolean parameter for overwriting/not overwriting the file
1702 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1703 # @ingroup l2_impexp
1704 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1705 unRegister = genObjUnRegister()
1706 if isinstance( meshPart, list ):
1707 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1708 unRegister.set( meshPart )
1709 if isinstance( meshPart, Mesh ):
1710 meshPart = meshPart.mesh
1712 meshPart = self.mesh
1713 self.mesh.ExportCGNS(meshPart, f, overwrite)
1715 ## Exports the mesh in a file in GMF format.
1716 # GMF files must have .mesh extension for the ASCII format and .meshb for
1717 # the bynary format. Other extensions are not allowed.
1718 # @param f is the file name
1719 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1720 # @ingroup l2_impexp
1721 def ExportGMF(self, f, meshPart=None):
1722 unRegister = genObjUnRegister()
1723 if isinstance( meshPart, list ):
1724 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1725 unRegister.set( meshPart )
1726 if isinstance( meshPart, Mesh ):
1727 meshPart = meshPart.mesh
1729 meshPart = self.mesh
1730 self.mesh.ExportGMF(meshPart, f, True)
1732 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1733 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1734 ## allowing to overwrite the file if it exists or add the exported data to its contents
1735 # @param f the file name
1736 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1737 # @param opt boolean parameter for creating/not creating
1738 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1739 # @param overwrite boolean parameter for overwriting/not overwriting the file
1740 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1741 # - 1D if all mesh nodes lie on OX coordinate axis, or
1742 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1743 # - 3D in the rest cases.
1745 # If @a autoDimension is @c False, the space dimension is always 3.
1746 # @ingroup l2_impexp
1747 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1748 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1750 # Operations with groups:
1751 # ----------------------
1753 ## Creates an empty mesh group
1754 # @param elementType the type of elements in the group
1755 # @param name the name of the mesh group
1756 # @return SMESH_Group
1757 # @ingroup l2_grps_create
1758 def CreateEmptyGroup(self, elementType, name):
1759 return self.mesh.CreateGroup(elementType, name)
1761 ## Creates a mesh group based on the geometric object \a grp
1762 # and gives a \a name, \n if this parameter is not defined
1763 # the name is the same as the geometric group name \n
1764 # Note: Works like GroupOnGeom().
1765 # @param grp a geometric group, a vertex, an edge, a face or a solid
1766 # @param name the name of the mesh group
1767 # @return SMESH_GroupOnGeom
1768 # @ingroup l2_grps_create
1769 def Group(self, grp, name=""):
1770 return self.GroupOnGeom(grp, name)
1772 ## Creates a mesh group based on the geometrical object \a grp
1773 # and gives a \a name, \n if this parameter is not defined
1774 # the name is the same as the geometrical group name
1775 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1776 # @param name the name of the mesh group
1777 # @param typ the type of elements in the group. If not set, it is
1778 # automatically detected by the type of the geometry
1779 # @return SMESH_GroupOnGeom
1780 # @ingroup l2_grps_create
1781 def GroupOnGeom(self, grp, name="", typ=None):
1782 AssureGeomPublished( self, grp, name )
1784 name = grp.GetName()
1786 typ = self._groupTypeFromShape( grp )
1787 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1789 ## Pivate method to get a type of group on geometry
1790 def _groupTypeFromShape( self, shape ):
1791 tgeo = str(shape.GetShapeType())
1792 if tgeo == "VERTEX":
1794 elif tgeo == "EDGE":
1796 elif tgeo == "FACE" or tgeo == "SHELL":
1798 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1800 elif tgeo == "COMPOUND":
1801 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1803 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1804 return self._groupTypeFromShape( sub[0] )
1807 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1810 ## Creates a mesh group with given \a name based on the \a filter which
1811 ## is a special type of group dynamically updating it's contents during
1812 ## mesh modification
1813 # @param typ the type of elements in the group
1814 # @param name the name of the mesh group
1815 # @param filter the filter defining group contents
1816 # @return SMESH_GroupOnFilter
1817 # @ingroup l2_grps_create
1818 def GroupOnFilter(self, typ, name, filter):
1819 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1821 ## Creates a mesh group by the given ids of elements
1822 # @param groupName the name of the mesh group
1823 # @param elementType the type of elements in the group
1824 # @param elemIDs the list of ids
1825 # @return SMESH_Group
1826 # @ingroup l2_grps_create
1827 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1828 group = self.mesh.CreateGroup(elementType, groupName)
1832 ## Creates a mesh group by the given conditions
1833 # @param groupName the name of the mesh group
1834 # @param elementType the type of elements in the group
1835 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1836 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1837 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1838 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1839 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1840 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1841 # @return SMESH_Group
1842 # @ingroup l2_grps_create
1846 CritType=FT_Undefined,
1849 UnaryOp=FT_Undefined,
1851 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1852 group = self.MakeGroupByCriterion(groupName, aCriterion)
1855 ## Creates a mesh group by the given criterion
1856 # @param groupName the name of the mesh group
1857 # @param Criterion the instance of Criterion class
1858 # @return SMESH_Group
1859 # @ingroup l2_grps_create
1860 def MakeGroupByCriterion(self, groupName, Criterion):
1861 aFilterMgr = self.smeshpyD.CreateFilterManager()
1862 aFilter = aFilterMgr.CreateFilter()
1864 aCriteria.append(Criterion)
1865 aFilter.SetCriteria(aCriteria)
1866 group = self.MakeGroupByFilter(groupName, aFilter)
1867 aFilterMgr.UnRegister()
1870 ## Creates a mesh group by the given criteria (list of criteria)
1871 # @param groupName the name of the mesh group
1872 # @param theCriteria the list of criteria
1873 # @return SMESH_Group
1874 # @ingroup l2_grps_create
1875 def MakeGroupByCriteria(self, groupName, theCriteria):
1876 aFilterMgr = self.smeshpyD.CreateFilterManager()
1877 aFilter = aFilterMgr.CreateFilter()
1878 aFilter.SetCriteria(theCriteria)
1879 group = self.MakeGroupByFilter(groupName, aFilter)
1880 aFilterMgr.UnRegister()
1883 ## Creates a mesh group by the given filter
1884 # @param groupName the name of the mesh group
1885 # @param theFilter the instance of Filter class
1886 # @return SMESH_Group
1887 # @ingroup l2_grps_create
1888 def MakeGroupByFilter(self, groupName, theFilter):
1889 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1890 theFilter.SetMesh( self.mesh )
1891 group.AddFrom( theFilter )
1895 # @ingroup l2_grps_delete
1896 def RemoveGroup(self, group):
1897 self.mesh.RemoveGroup(group)
1899 ## Removes a group with its contents
1900 # @ingroup l2_grps_delete
1901 def RemoveGroupWithContents(self, group):
1902 self.mesh.RemoveGroupWithContents(group)
1904 ## Gets the list of groups existing in the mesh
1905 # @return a sequence of SMESH_GroupBase
1906 # @ingroup l2_grps_create
1907 def GetGroups(self):
1908 return self.mesh.GetGroups()
1910 ## Gets the number of groups existing in the mesh
1911 # @return the quantity of groups as an integer value
1912 # @ingroup l2_grps_create
1914 return self.mesh.NbGroups()
1916 ## Gets the list of names of groups existing in the mesh
1917 # @return list of strings
1918 # @ingroup l2_grps_create
1919 def GetGroupNames(self):
1920 groups = self.GetGroups()
1922 for group in groups:
1923 names.append(group.GetName())
1926 ## Produces a union of two groups
1927 # A new group is created. All mesh elements that are
1928 # present in the initial groups are added to the new one
1929 # @return an instance of SMESH_Group
1930 # @ingroup l2_grps_operon
1931 def UnionGroups(self, group1, group2, name):
1932 return self.mesh.UnionGroups(group1, group2, name)
1934 ## Produces a union list of groups
1935 # New group is created. All mesh elements that are present in
1936 # initial groups are added to the new one
1937 # @return an instance of SMESH_Group
1938 # @ingroup l2_grps_operon
1939 def UnionListOfGroups(self, groups, name):
1940 return self.mesh.UnionListOfGroups(groups, name)
1942 ## Prodices an intersection of two groups
1943 # A new group is created. All mesh elements that are common
1944 # for the two initial groups are added to the new one.
1945 # @return an instance of SMESH_Group
1946 # @ingroup l2_grps_operon
1947 def IntersectGroups(self, group1, group2, name):
1948 return self.mesh.IntersectGroups(group1, group2, name)
1950 ## Produces an intersection of groups
1951 # New group is created. All mesh elements that are present in all
1952 # initial groups simultaneously are added to the new one
1953 # @return an instance of SMESH_Group
1954 # @ingroup l2_grps_operon
1955 def IntersectListOfGroups(self, groups, name):
1956 return self.mesh.IntersectListOfGroups(groups, name)
1958 ## Produces a cut of two groups
1959 # A new group is created. All mesh elements that are present in
1960 # the main group but are not present in the tool group are added to the new one
1961 # @return an instance of SMESH_Group
1962 # @ingroup l2_grps_operon
1963 def CutGroups(self, main_group, tool_group, name):
1964 return self.mesh.CutGroups(main_group, tool_group, name)
1966 ## Produces a cut of groups
1967 # A new group is created. All mesh elements that are present in main groups
1968 # but do not present in tool groups are added to the new one
1969 # @return an instance of SMESH_Group
1970 # @ingroup l2_grps_operon
1971 def CutListOfGroups(self, main_groups, tool_groups, name):
1972 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1974 ## Produces a group of elements of specified type using list of existing groups
1975 # A new group is created. System
1976 # 1) extracts all nodes on which groups elements are built
1977 # 2) combines all elements of specified dimension laying on these nodes
1978 # @return an instance of SMESH_Group
1979 # @ingroup l2_grps_operon
1980 def CreateDimGroup(self, groups, elem_type, name):
1981 return self.mesh.CreateDimGroup(groups, elem_type, name)
1984 ## Convert group on geom into standalone group
1985 # @ingroup l2_grps_delete
1986 def ConvertToStandalone(self, group):
1987 return self.mesh.ConvertToStandalone(group)
1989 # Get some info about mesh:
1990 # ------------------------
1992 ## Returns the log of nodes and elements added or removed
1993 # since the previous clear of the log.
1994 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
1995 # @return list of log_block structures:
2000 # @ingroup l1_auxiliary
2001 def GetLog(self, clearAfterGet):
2002 return self.mesh.GetLog(clearAfterGet)
2004 ## Clears the log of nodes and elements added or removed since the previous
2005 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2006 # @ingroup l1_auxiliary
2008 self.mesh.ClearLog()
2010 ## Toggles auto color mode on the object.
2011 # @param theAutoColor the flag which toggles auto color mode.
2012 # @ingroup l1_auxiliary
2013 def SetAutoColor(self, theAutoColor):
2014 self.mesh.SetAutoColor(theAutoColor)
2016 ## Gets flag of object auto color mode.
2017 # @return True or False
2018 # @ingroup l1_auxiliary
2019 def GetAutoColor(self):
2020 return self.mesh.GetAutoColor()
2022 ## Gets the internal ID
2023 # @return integer value, which is the internal Id of the mesh
2024 # @ingroup l1_auxiliary
2026 return self.mesh.GetId()
2029 # @return integer value, which is the study Id of the mesh
2030 # @ingroup l1_auxiliary
2031 def GetStudyId(self):
2032 return self.mesh.GetStudyId()
2034 ## Checks the group names for duplications.
2035 # Consider the maximum group name length stored in MED file.
2036 # @return True or False
2037 # @ingroup l1_auxiliary
2038 def HasDuplicatedGroupNamesMED(self):
2039 return self.mesh.HasDuplicatedGroupNamesMED()
2041 ## Obtains the mesh editor tool
2042 # @return an instance of SMESH_MeshEditor
2043 # @ingroup l1_modifying
2044 def GetMeshEditor(self):
2047 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2048 # can be passed as argument to a method accepting mesh, group or sub-mesh
2049 # @return an instance of SMESH_IDSource
2050 # @ingroup l1_auxiliary
2051 def GetIDSource(self, ids, elemType):
2052 return self.editor.MakeIDSource(ids, elemType)
2055 # Get informations about mesh contents:
2056 # ------------------------------------
2058 ## Gets the mesh stattistic
2059 # @return dictionary type element - count of elements
2060 # @ingroup l1_meshinfo
2061 def GetMeshInfo(self, obj = None):
2062 if not obj: obj = self.mesh
2063 return self.smeshpyD.GetMeshInfo(obj)
2065 ## Returns the number of nodes in the mesh
2066 # @return an integer value
2067 # @ingroup l1_meshinfo
2069 return self.mesh.NbNodes()
2071 ## Returns the number of elements in the mesh
2072 # @return an integer value
2073 # @ingroup l1_meshinfo
2074 def NbElements(self):
2075 return self.mesh.NbElements()
2077 ## Returns the number of 0d elements in the mesh
2078 # @return an integer value
2079 # @ingroup l1_meshinfo
2080 def Nb0DElements(self):
2081 return self.mesh.Nb0DElements()
2083 ## Returns the number of ball discrete elements in the mesh
2084 # @return an integer value
2085 # @ingroup l1_meshinfo
2087 return self.mesh.NbBalls()
2089 ## Returns the number of edges in the mesh
2090 # @return an integer value
2091 # @ingroup l1_meshinfo
2093 return self.mesh.NbEdges()
2095 ## Returns the number of edges with the given order in the mesh
2096 # @param elementOrder the order of elements:
2097 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2098 # @return an integer value
2099 # @ingroup l1_meshinfo
2100 def NbEdgesOfOrder(self, elementOrder):
2101 return self.mesh.NbEdgesOfOrder(elementOrder)
2103 ## Returns the number of faces in the mesh
2104 # @return an integer value
2105 # @ingroup l1_meshinfo
2107 return self.mesh.NbFaces()
2109 ## Returns the number of faces with the given order in the mesh
2110 # @param elementOrder the order of elements:
2111 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2112 # @return an integer value
2113 # @ingroup l1_meshinfo
2114 def NbFacesOfOrder(self, elementOrder):
2115 return self.mesh.NbFacesOfOrder(elementOrder)
2117 ## Returns the number of triangles in the mesh
2118 # @return an integer value
2119 # @ingroup l1_meshinfo
2120 def NbTriangles(self):
2121 return self.mesh.NbTriangles()
2123 ## Returns the number of triangles with the given order in the mesh
2124 # @param elementOrder is the order of elements:
2125 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2126 # @return an integer value
2127 # @ingroup l1_meshinfo
2128 def NbTrianglesOfOrder(self, elementOrder):
2129 return self.mesh.NbTrianglesOfOrder(elementOrder)
2131 ## Returns the number of biquadratic triangles in the mesh
2132 # @return an integer value
2133 # @ingroup l1_meshinfo
2134 def NbBiQuadTriangles(self):
2135 return self.mesh.NbBiQuadTriangles()
2137 ## Returns the number of quadrangles in the mesh
2138 # @return an integer value
2139 # @ingroup l1_meshinfo
2140 def NbQuadrangles(self):
2141 return self.mesh.NbQuadrangles()
2143 ## Returns the number of quadrangles with the given order in the mesh
2144 # @param elementOrder the order of elements:
2145 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2146 # @return an integer value
2147 # @ingroup l1_meshinfo
2148 def NbQuadranglesOfOrder(self, elementOrder):
2149 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2151 ## Returns the number of biquadratic quadrangles in the mesh
2152 # @return an integer value
2153 # @ingroup l1_meshinfo
2154 def NbBiQuadQuadrangles(self):
2155 return self.mesh.NbBiQuadQuadrangles()
2157 ## Returns the number of polygons in the mesh
2158 # @return an integer value
2159 # @ingroup l1_meshinfo
2160 def NbPolygons(self):
2161 return self.mesh.NbPolygons()
2163 ## Returns the number of volumes in the mesh
2164 # @return an integer value
2165 # @ingroup l1_meshinfo
2166 def NbVolumes(self):
2167 return self.mesh.NbVolumes()
2169 ## Returns the number of volumes with the given order in the mesh
2170 # @param elementOrder the order of elements:
2171 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2172 # @return an integer value
2173 # @ingroup l1_meshinfo
2174 def NbVolumesOfOrder(self, elementOrder):
2175 return self.mesh.NbVolumesOfOrder(elementOrder)
2177 ## Returns the number of tetrahedrons in the mesh
2178 # @return an integer value
2179 # @ingroup l1_meshinfo
2181 return self.mesh.NbTetras()
2183 ## Returns the number of tetrahedrons with the given order in the mesh
2184 # @param elementOrder the order of elements:
2185 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2186 # @return an integer value
2187 # @ingroup l1_meshinfo
2188 def NbTetrasOfOrder(self, elementOrder):
2189 return self.mesh.NbTetrasOfOrder(elementOrder)
2191 ## Returns the number of hexahedrons in the mesh
2192 # @return an integer value
2193 # @ingroup l1_meshinfo
2195 return self.mesh.NbHexas()
2197 ## Returns the number of hexahedrons with the given order in the mesh
2198 # @param elementOrder the order of elements:
2199 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2200 # @return an integer value
2201 # @ingroup l1_meshinfo
2202 def NbHexasOfOrder(self, elementOrder):
2203 return self.mesh.NbHexasOfOrder(elementOrder)
2205 ## Returns the number of triquadratic hexahedrons in the mesh
2206 # @return an integer value
2207 # @ingroup l1_meshinfo
2208 def NbTriQuadraticHexas(self):
2209 return self.mesh.NbTriQuadraticHexas()
2211 ## Returns the number of pyramids in the mesh
2212 # @return an integer value
2213 # @ingroup l1_meshinfo
2214 def NbPyramids(self):
2215 return self.mesh.NbPyramids()
2217 ## Returns the number of pyramids with the given order in the mesh
2218 # @param elementOrder the order of elements:
2219 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2220 # @return an integer value
2221 # @ingroup l1_meshinfo
2222 def NbPyramidsOfOrder(self, elementOrder):
2223 return self.mesh.NbPyramidsOfOrder(elementOrder)
2225 ## Returns the number of prisms in the mesh
2226 # @return an integer value
2227 # @ingroup l1_meshinfo
2229 return self.mesh.NbPrisms()
2231 ## Returns the number of prisms with the given order in the mesh
2232 # @param elementOrder the order of elements:
2233 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2234 # @return an integer value
2235 # @ingroup l1_meshinfo
2236 def NbPrismsOfOrder(self, elementOrder):
2237 return self.mesh.NbPrismsOfOrder(elementOrder)
2239 ## Returns the number of hexagonal prisms in the mesh
2240 # @return an integer value
2241 # @ingroup l1_meshinfo
2242 def NbHexagonalPrisms(self):
2243 return self.mesh.NbHexagonalPrisms()
2245 ## Returns the number of polyhedrons in the mesh
2246 # @return an integer value
2247 # @ingroup l1_meshinfo
2248 def NbPolyhedrons(self):
2249 return self.mesh.NbPolyhedrons()
2251 ## Returns the number of submeshes in the mesh
2252 # @return an integer value
2253 # @ingroup l1_meshinfo
2254 def NbSubMesh(self):
2255 return self.mesh.NbSubMesh()
2257 ## Returns the list of mesh elements IDs
2258 # @return the list of integer values
2259 # @ingroup l1_meshinfo
2260 def GetElementsId(self):
2261 return self.mesh.GetElementsId()
2263 ## Returns the list of IDs of mesh elements with the given type
2264 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2265 # @return list of integer values
2266 # @ingroup l1_meshinfo
2267 def GetElementsByType(self, elementType):
2268 return self.mesh.GetElementsByType(elementType)
2270 ## Returns the list of mesh nodes IDs
2271 # @return the list of integer values
2272 # @ingroup l1_meshinfo
2273 def GetNodesId(self):
2274 return self.mesh.GetNodesId()
2276 # Get the information about mesh elements:
2277 # ------------------------------------
2279 ## Returns the type of mesh element
2280 # @return the value from SMESH::ElementType enumeration
2281 # @ingroup l1_meshinfo
2282 def GetElementType(self, id, iselem):
2283 return self.mesh.GetElementType(id, iselem)
2285 ## Returns the geometric type of mesh element
2286 # @return the value from SMESH::EntityType enumeration
2287 # @ingroup l1_meshinfo
2288 def GetElementGeomType(self, id):
2289 return self.mesh.GetElementGeomType(id)
2291 ## Returns the shape type of mesh element
2292 # @return the value from SMESH::GeometryType enumeration
2293 # @ingroup l1_meshinfo
2294 def GetElementShape(self, id):
2295 return self.mesh.GetElementShape(id)
2297 ## Returns the list of submesh elements IDs
2298 # @param Shape a geom object(sub-shape) IOR
2299 # Shape must be the sub-shape of a ShapeToMesh()
2300 # @return the list of integer values
2301 # @ingroup l1_meshinfo
2302 def GetSubMeshElementsId(self, Shape):
2303 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2304 ShapeID = Shape.GetSubShapeIndices()[0]
2307 return self.mesh.GetSubMeshElementsId(ShapeID)
2309 ## Returns the list of submesh nodes IDs
2310 # @param Shape a geom object(sub-shape) IOR
2311 # Shape must be the sub-shape of a ShapeToMesh()
2312 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2313 # @return the list of integer values
2314 # @ingroup l1_meshinfo
2315 def GetSubMeshNodesId(self, Shape, all):
2316 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2317 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2320 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2322 ## Returns type of elements on given shape
2323 # @param Shape a geom object(sub-shape) IOR
2324 # Shape must be a sub-shape of a ShapeToMesh()
2325 # @return element type
2326 # @ingroup l1_meshinfo
2327 def GetSubMeshElementType(self, Shape):
2328 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2329 ShapeID = Shape.GetSubShapeIndices()[0]
2332 return self.mesh.GetSubMeshElementType(ShapeID)
2334 ## Gets the mesh description
2335 # @return string value
2336 # @ingroup l1_meshinfo
2338 return self.mesh.Dump()
2341 # Get the information about nodes and elements of a mesh by its IDs:
2342 # -----------------------------------------------------------
2344 ## Gets XYZ coordinates of a node
2345 # \n If there is no nodes for the given ID - returns an empty list
2346 # @return a list of double precision values
2347 # @ingroup l1_meshinfo
2348 def GetNodeXYZ(self, id):
2349 return self.mesh.GetNodeXYZ(id)
2351 ## Returns list of IDs of inverse elements for the given node
2352 # \n If there is no node for the given ID - returns an empty list
2353 # @return a list of integer values
2354 # @ingroup l1_meshinfo
2355 def GetNodeInverseElements(self, id):
2356 return self.mesh.GetNodeInverseElements(id)
2358 ## @brief Returns the position of a node on the shape
2359 # @return SMESH::NodePosition
2360 # @ingroup l1_meshinfo
2361 def GetNodePosition(self,NodeID):
2362 return self.mesh.GetNodePosition(NodeID)
2364 ## @brief Returns the position of an element on the shape
2365 # @return SMESH::ElementPosition
2366 # @ingroup l1_meshinfo
2367 def GetElementPosition(self,ElemID):
2368 return self.mesh.GetElementPosition(ElemID)
2370 ## If the given element is a node, returns the ID of shape
2371 # \n If there is no node for the given ID - returns -1
2372 # @return an integer value
2373 # @ingroup l1_meshinfo
2374 def GetShapeID(self, id):
2375 return self.mesh.GetShapeID(id)
2377 ## Returns the ID of the result shape after
2378 # FindShape() from SMESH_MeshEditor for the given element
2379 # \n If there is no element for the given ID - returns -1
2380 # @return an integer value
2381 # @ingroup l1_meshinfo
2382 def GetShapeIDForElem(self,id):
2383 return self.mesh.GetShapeIDForElem(id)
2385 ## Returns the number of nodes for the given element
2386 # \n If there is no element for the given ID - returns -1
2387 # @return an integer value
2388 # @ingroup l1_meshinfo
2389 def GetElemNbNodes(self, id):
2390 return self.mesh.GetElemNbNodes(id)
2392 ## Returns the node ID the given (zero based) index for the given element
2393 # \n If there is no element for the given ID - returns -1
2394 # \n If there is no node for the given index - returns -2
2395 # @return an integer value
2396 # @ingroup l1_meshinfo
2397 def GetElemNode(self, id, index):
2398 return self.mesh.GetElemNode(id, index)
2400 ## Returns the IDs of nodes of the given element
2401 # @return a list of integer values
2402 # @ingroup l1_meshinfo
2403 def GetElemNodes(self, id):
2404 return self.mesh.GetElemNodes(id)
2406 ## Returns true if the given node is the medium node in the given quadratic element
2407 # @ingroup l1_meshinfo
2408 def IsMediumNode(self, elementID, nodeID):
2409 return self.mesh.IsMediumNode(elementID, nodeID)
2411 ## Returns true if the given node is the medium node in one of quadratic elements
2412 # @ingroup l1_meshinfo
2413 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2414 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2416 ## Returns the number of edges for the given element
2417 # @ingroup l1_meshinfo
2418 def ElemNbEdges(self, id):
2419 return self.mesh.ElemNbEdges(id)
2421 ## Returns the number of faces for the given element
2422 # @ingroup l1_meshinfo
2423 def ElemNbFaces(self, id):
2424 return self.mesh.ElemNbFaces(id)
2426 ## Returns nodes of given face (counted from zero) for given volumic element.
2427 # @ingroup l1_meshinfo
2428 def GetElemFaceNodes(self,elemId, faceIndex):
2429 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2431 ## Returns three components of normal of given mesh face
2432 # (or an empty array in KO case)
2433 # @ingroup l1_meshinfo
2434 def GetFaceNormal(self, faceId, normalized=False):
2435 return self.mesh.GetFaceNormal(faceId,normalized)
2437 ## Returns an element based on all given nodes.
2438 # @ingroup l1_meshinfo
2439 def FindElementByNodes(self,nodes):
2440 return self.mesh.FindElementByNodes(nodes)
2442 ## Returns true if the given element is a polygon
2443 # @ingroup l1_meshinfo
2444 def IsPoly(self, id):
2445 return self.mesh.IsPoly(id)
2447 ## Returns true if the given element is quadratic
2448 # @ingroup l1_meshinfo
2449 def IsQuadratic(self, id):
2450 return self.mesh.IsQuadratic(id)
2452 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2453 # @ingroup l1_meshinfo
2454 def GetBallDiameter(self, id):
2455 return self.mesh.GetBallDiameter(id)
2457 ## Returns XYZ coordinates of the barycenter of the given element
2458 # \n If there is no element for the given ID - returns an empty list
2459 # @return a list of three double values
2460 # @ingroup l1_meshinfo
2461 def BaryCenter(self, id):
2462 return self.mesh.BaryCenter(id)
2464 ## Passes mesh elements through the given filter and return IDs of fitting elements
2465 # @param theFilter SMESH_Filter
2466 # @return a list of ids
2467 # @ingroup l1_controls
2468 def GetIdsFromFilter(self, theFilter):
2469 theFilter.SetMesh( self.mesh )
2470 return theFilter.GetIDs()
2472 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2473 # Returns a list of special structures (borders).
2474 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2475 # @ingroup l1_controls
2476 def GetFreeBorders(self):
2477 aFilterMgr = self.smeshpyD.CreateFilterManager()
2478 aPredicate = aFilterMgr.CreateFreeEdges()
2479 aPredicate.SetMesh(self.mesh)
2480 aBorders = aPredicate.GetBorders()
2481 aFilterMgr.UnRegister()
2485 # Get mesh measurements information:
2486 # ------------------------------------
2488 ## Get minimum distance between two nodes, elements or distance to the origin
2489 # @param id1 first node/element id
2490 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2491 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2492 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2493 # @return minimum distance value
2494 # @sa GetMinDistance()
2495 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2496 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2497 return aMeasure.value
2499 ## Get measure structure specifying minimum distance data between two objects
2500 # @param id1 first node/element id
2501 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2502 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2503 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2504 # @return Measure structure
2506 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2508 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2510 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2513 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2515 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2520 aMeasurements = self.smeshpyD.CreateMeasurements()
2521 aMeasure = aMeasurements.MinDistance(id1, id2)
2522 genObjUnRegister([aMeasurements,id1, id2])
2525 ## Get bounding box of the specified object(s)
2526 # @param objects single source object or list of source objects or list of nodes/elements IDs
2527 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2528 # @c False specifies that @a objects are nodes
2529 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2530 # @sa GetBoundingBox()
2531 def BoundingBox(self, objects=None, isElem=False):
2532 result = self.GetBoundingBox(objects, isElem)
2536 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2539 ## Get measure structure specifying bounding box data of the specified object(s)
2540 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2541 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2542 # @c False specifies that @a objects are nodes
2543 # @return Measure structure
2545 def GetBoundingBox(self, IDs=None, isElem=False):
2548 elif isinstance(IDs, tuple):
2550 if not isinstance(IDs, list):
2552 if len(IDs) > 0 and isinstance(IDs[0], int):
2555 unRegister = genObjUnRegister()
2557 if isinstance(o, Mesh):
2558 srclist.append(o.mesh)
2559 elif hasattr(o, "_narrow"):
2560 src = o._narrow(SMESH.SMESH_IDSource)
2561 if src: srclist.append(src)
2563 elif isinstance(o, list):
2565 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2567 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2568 unRegister.set( srclist[-1] )
2571 aMeasurements = self.smeshpyD.CreateMeasurements()
2572 unRegister.set( aMeasurements )
2573 aMeasure = aMeasurements.BoundingBox(srclist)
2576 # Mesh edition (SMESH_MeshEditor functionality):
2577 # ---------------------------------------------
2579 ## Removes the elements from the mesh by ids
2580 # @param IDsOfElements is a list of ids of elements to remove
2581 # @return True or False
2582 # @ingroup l2_modif_del
2583 def RemoveElements(self, IDsOfElements):
2584 return self.editor.RemoveElements(IDsOfElements)
2586 ## Removes nodes from mesh by ids
2587 # @param IDsOfNodes is a list of ids of nodes to remove
2588 # @return True or False
2589 # @ingroup l2_modif_del
2590 def RemoveNodes(self, IDsOfNodes):
2591 return self.editor.RemoveNodes(IDsOfNodes)
2593 ## Removes all orphan (free) nodes from mesh
2594 # @return number of the removed nodes
2595 # @ingroup l2_modif_del
2596 def RemoveOrphanNodes(self):
2597 return self.editor.RemoveOrphanNodes()
2599 ## Add a node to the mesh by coordinates
2600 # @return Id of the new node
2601 # @ingroup l2_modif_add
2602 def AddNode(self, x, y, z):
2603 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2604 if hasVars: self.mesh.SetParameters(Parameters)
2605 return self.editor.AddNode( x, y, z)
2607 ## Creates a 0D element on a node with given number.
2608 # @param IDOfNode the ID of node for creation of the element.
2609 # @return the Id of the new 0D element
2610 # @ingroup l2_modif_add
2611 def Add0DElement(self, IDOfNode):
2612 return self.editor.Add0DElement(IDOfNode)
2614 ## Create 0D elements on all nodes of the given elements except those
2615 # nodes on which a 0D element already exists.
2616 # @param theObject an object on whose nodes 0D elements will be created.
2617 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2618 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2619 # @param theGroupName optional name of a group to add 0D elements created
2620 # and/or found on nodes of \a theObject.
2621 # @return an object (a new group or a temporary SMESH_IDSource) holding
2622 # IDs of new and/or found 0D elements. IDs of 0D elements
2623 # can be retrieved from the returned object by calling GetIDs()
2624 # @ingroup l2_modif_add
2625 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2626 unRegister = genObjUnRegister()
2627 if isinstance( theObject, Mesh ):
2628 theObject = theObject.GetMesh()
2629 if isinstance( theObject, list ):
2630 theObject = self.GetIDSource( theObject, SMESH.ALL )
2631 unRegister.set( theObject )
2632 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2634 ## Creates a ball element on a node with given ID.
2635 # @param IDOfNode the ID of node for creation of the element.
2636 # @param diameter the bal diameter.
2637 # @return the Id of the new ball element
2638 # @ingroup l2_modif_add
2639 def AddBall(self, IDOfNode, diameter):
2640 return self.editor.AddBall( IDOfNode, diameter )
2642 ## Creates a linear or quadratic edge (this is determined
2643 # by the number of given nodes).
2644 # @param IDsOfNodes the list of node IDs for creation of the element.
2645 # The order of nodes in this list should correspond to the description
2646 # of MED. \n This description is located by the following link:
2647 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2648 # @return the Id of the new edge
2649 # @ingroup l2_modif_add
2650 def AddEdge(self, IDsOfNodes):
2651 return self.editor.AddEdge(IDsOfNodes)
2653 ## Creates a linear or quadratic face (this is determined
2654 # by the number of given nodes).
2655 # @param IDsOfNodes the list of node IDs for creation of the element.
2656 # The order of nodes in this list should correspond to the description
2657 # of MED. \n This description is located by the following link:
2658 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2659 # @return the Id of the new face
2660 # @ingroup l2_modif_add
2661 def AddFace(self, IDsOfNodes):
2662 return self.editor.AddFace(IDsOfNodes)
2664 ## Adds a polygonal face to the mesh by the list of node IDs
2665 # @param IdsOfNodes the list of node IDs for creation of the element.
2666 # @return the Id of the new face
2667 # @ingroup l2_modif_add
2668 def AddPolygonalFace(self, IdsOfNodes):
2669 return self.editor.AddPolygonalFace(IdsOfNodes)
2671 ## Creates both simple and quadratic volume (this is determined
2672 # by the number of given nodes).
2673 # @param IDsOfNodes the list of node IDs for creation of the element.
2674 # The order of nodes in this list should correspond to the description
2675 # of MED. \n This description is located by the following link:
2676 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2677 # @return the Id of the new volumic element
2678 # @ingroup l2_modif_add
2679 def AddVolume(self, IDsOfNodes):
2680 return self.editor.AddVolume(IDsOfNodes)
2682 ## Creates a volume of many faces, giving nodes for each face.
2683 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2684 # @param Quantities the list of integer values, Quantities[i]
2685 # gives the quantity of nodes in face number i.
2686 # @return the Id of the new volumic element
2687 # @ingroup l2_modif_add
2688 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2689 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2691 ## Creates a volume of many faces, giving the IDs of the existing faces.
2692 # @param IdsOfFaces the list of face IDs for volume creation.
2694 # Note: The created volume will refer only to the nodes
2695 # of the given faces, not to the faces themselves.
2696 # @return the Id of the new volumic element
2697 # @ingroup l2_modif_add
2698 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2699 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2702 ## @brief Binds a node to a vertex
2703 # @param NodeID a node ID
2704 # @param Vertex a vertex or vertex ID
2705 # @return True if succeed else raises an exception
2706 # @ingroup l2_modif_add
2707 def SetNodeOnVertex(self, NodeID, Vertex):
2708 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2709 VertexID = Vertex.GetSubShapeIndices()[0]
2713 self.editor.SetNodeOnVertex(NodeID, VertexID)
2714 except SALOME.SALOME_Exception, inst:
2715 raise ValueError, inst.details.text
2719 ## @brief Stores the node position on an edge
2720 # @param NodeID a node ID
2721 # @param Edge an edge or edge ID
2722 # @param paramOnEdge a parameter on the edge where the node is located
2723 # @return True if succeed else raises an exception
2724 # @ingroup l2_modif_add
2725 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2726 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2727 EdgeID = Edge.GetSubShapeIndices()[0]
2731 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2732 except SALOME.SALOME_Exception, inst:
2733 raise ValueError, inst.details.text
2736 ## @brief Stores node position on a face
2737 # @param NodeID a node ID
2738 # @param Face a face or face ID
2739 # @param u U parameter on the face where the node is located
2740 # @param v V parameter on the face where the node is located
2741 # @return True if succeed else raises an exception
2742 # @ingroup l2_modif_add
2743 def SetNodeOnFace(self, NodeID, Face, u, v):
2744 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2745 FaceID = Face.GetSubShapeIndices()[0]
2749 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2750 except SALOME.SALOME_Exception, inst:
2751 raise ValueError, inst.details.text
2754 ## @brief Binds a node to a solid
2755 # @param NodeID a node ID
2756 # @param Solid a solid or solid ID
2757 # @return True if succeed else raises an exception
2758 # @ingroup l2_modif_add
2759 def SetNodeInVolume(self, NodeID, Solid):
2760 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2761 SolidID = Solid.GetSubShapeIndices()[0]
2765 self.editor.SetNodeInVolume(NodeID, SolidID)
2766 except SALOME.SALOME_Exception, inst:
2767 raise ValueError, inst.details.text
2770 ## @brief Bind an element to a shape
2771 # @param ElementID an element ID
2772 # @param Shape a shape or shape ID
2773 # @return True if succeed else raises an exception
2774 # @ingroup l2_modif_add
2775 def SetMeshElementOnShape(self, ElementID, Shape):
2776 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2777 ShapeID = Shape.GetSubShapeIndices()[0]
2781 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2782 except SALOME.SALOME_Exception, inst:
2783 raise ValueError, inst.details.text
2787 ## Moves the node with the given id
2788 # @param NodeID the id of the node
2789 # @param x a new X coordinate
2790 # @param y a new Y coordinate
2791 # @param z a new Z coordinate
2792 # @return True if succeed else False
2793 # @ingroup l2_modif_movenode
2794 def MoveNode(self, NodeID, x, y, z):
2795 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2796 if hasVars: self.mesh.SetParameters(Parameters)
2797 return self.editor.MoveNode(NodeID, x, y, z)
2799 ## Finds the node closest to a point and moves it to a point location
2800 # @param x the X coordinate of a point
2801 # @param y the Y coordinate of a point
2802 # @param z the Z coordinate of a point
2803 # @param NodeID if specified (>0), the node with this ID is moved,
2804 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2805 # @return the ID of a node
2806 # @ingroup l2_modif_throughp
2807 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2808 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2809 if hasVars: self.mesh.SetParameters(Parameters)
2810 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2812 ## Finds the node closest to a point
2813 # @param x the X coordinate of a point
2814 # @param y the Y coordinate of a point
2815 # @param z the Z coordinate of a point
2816 # @return the ID of a node
2817 # @ingroup l2_modif_throughp
2818 def FindNodeClosestTo(self, x, y, z):
2819 #preview = self.mesh.GetMeshEditPreviewer()
2820 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2821 return self.editor.FindNodeClosestTo(x, y, z)
2823 ## Finds the elements where a point lays IN or ON
2824 # @param x the X coordinate of a point
2825 # @param y the Y coordinate of a point
2826 # @param z the Z coordinate of a point
2827 # @param elementType type of elements to find (SMESH.ALL type
2828 # means elements of any type excluding nodes, discrete and 0D elements)
2829 # @param meshPart a part of mesh (group, sub-mesh) to search within
2830 # @return list of IDs of found elements
2831 # @ingroup l2_modif_throughp
2832 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2834 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2836 return self.editor.FindElementsByPoint(x, y, z, elementType)
2838 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2839 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2840 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2842 def GetPointState(self, x, y, z):
2843 return self.editor.GetPointState(x, y, z)
2845 ## Finds the node closest to a point and moves it to a point location
2846 # @param x the X coordinate of a point
2847 # @param y the Y coordinate of a point
2848 # @param z the Z coordinate of a point
2849 # @return the ID of a moved node
2850 # @ingroup l2_modif_throughp
2851 def MeshToPassThroughAPoint(self, x, y, z):
2852 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2854 ## Replaces two neighbour triangles sharing Node1-Node2 link
2855 # with the triangles built on the same 4 nodes but having other common link.
2856 # @param NodeID1 the ID of the first node
2857 # @param NodeID2 the ID of the second node
2858 # @return false if proper faces were not found
2859 # @ingroup l2_modif_invdiag
2860 def InverseDiag(self, NodeID1, NodeID2):
2861 return self.editor.InverseDiag(NodeID1, NodeID2)
2863 ## Replaces two neighbour triangles sharing Node1-Node2 link
2864 # with a quadrangle built on the same 4 nodes.
2865 # @param NodeID1 the ID of the first node
2866 # @param NodeID2 the ID of the second node
2867 # @return false if proper faces were not found
2868 # @ingroup l2_modif_unitetri
2869 def DeleteDiag(self, NodeID1, NodeID2):
2870 return self.editor.DeleteDiag(NodeID1, NodeID2)
2872 ## Reorients elements by ids
2873 # @param IDsOfElements if undefined reorients all mesh elements
2874 # @return True if succeed else False
2875 # @ingroup l2_modif_changori
2876 def Reorient(self, IDsOfElements=None):
2877 if IDsOfElements == None:
2878 IDsOfElements = self.GetElementsId()
2879 return self.editor.Reorient(IDsOfElements)
2881 ## Reorients all elements of the object
2882 # @param theObject mesh, submesh or group
2883 # @return True if succeed else False
2884 # @ingroup l2_modif_changori
2885 def ReorientObject(self, theObject):
2886 if ( isinstance( theObject, Mesh )):
2887 theObject = theObject.GetMesh()
2888 return self.editor.ReorientObject(theObject)
2890 ## Reorient faces contained in \a the2DObject.
2891 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2892 # @param theDirection is a desired direction of normal of \a theFace.
2893 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2894 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2895 # compared with theDirection. It can be either ID of face or a point
2896 # by which the face will be found. The point can be given as either
2897 # a GEOM vertex or a list of point coordinates.
2898 # @return number of reoriented faces
2899 # @ingroup l2_modif_changori
2900 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2901 unRegister = genObjUnRegister()
2903 if isinstance( the2DObject, Mesh ):
2904 the2DObject = the2DObject.GetMesh()
2905 if isinstance( the2DObject, list ):
2906 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2907 unRegister.set( the2DObject )
2908 # check theDirection
2909 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2910 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2911 if isinstance( theDirection, list ):
2912 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2913 # prepare theFace and thePoint