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 quadrangles
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 = 1, 2, 3
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 list of Mesh class instances
525 def CreateMeshesFromMED( self,theFileName ):
526 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
528 for iMesh in range(len(aSmeshMeshes)) :
529 aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
530 aMeshes.append(aMesh)
531 return aMeshes, aStatus
533 ## Creates a Mesh object(s) importing data from the given SAUV file
534 # @return a list of Mesh class instances
536 def CreateMeshesFromSAUV( self,theFileName ):
537 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
539 for iMesh in range(len(aSmeshMeshes)) :
540 aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
541 aMeshes.append(aMesh)
542 return aMeshes, aStatus
544 ## Creates a Mesh object importing data from the given STL file
545 # @return an instance of Mesh class
547 def CreateMeshesFromSTL( self, theFileName ):
548 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
549 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
552 ## Creates Mesh objects importing data from the given CGNS file
553 # @return an instance of Mesh class
555 def CreateMeshesFromCGNS( self, theFileName ):
556 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
558 for iMesh in range(len(aSmeshMeshes)) :
559 aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
560 aMeshes.append(aMesh)
561 return aMeshes, aStatus
563 ## Creates a Mesh object importing data from the given GMF file
564 # @return [ an instance of Mesh class, SMESH::ComputeError ]
566 def CreateMeshesFromGMF( self, theFileName ):
567 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
570 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
571 return Mesh(self, self.geompyD, aSmeshMesh), error
573 ## Concatenate the given meshes into one mesh.
574 # @return an instance of Mesh class
575 # @param meshes the meshes to combine into one mesh
576 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
577 # @param mergeNodesAndElements if true, equal nodes and elements aremerged
578 # @param mergeTolerance tolerance for merging nodes
579 # @param allGroups forces creation of groups of all elements
580 # @param name name of a new mesh
581 def Concatenate( self, meshes, uniteIdenticalGroups,
582 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
584 if not meshes: return None
585 for i,m in enumerate(meshes):
586 if isinstance(m, Mesh):
587 meshes[i] = m.GetMesh()
588 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
589 meshes[0].SetParameters(Parameters)
591 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
592 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
594 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
595 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
596 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
599 ## Create a mesh by copying a part of another mesh.
600 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
601 # to copy nodes or elements not contained in any mesh object,
602 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
603 # @param meshName a name of the new mesh
604 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
605 # @param toKeepIDs to preserve IDs of the copied elements or not
606 # @return an instance of Mesh class
607 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
608 if (isinstance( meshPart, Mesh )):
609 meshPart = meshPart.GetMesh()
610 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
611 return Mesh(self, self.geompyD, mesh)
613 ## From SMESH_Gen interface
614 # @return the list of integer values
615 # @ingroup l1_auxiliary
616 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
617 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
619 ## From SMESH_Gen interface. Creates a pattern
620 # @return an instance of SMESH_Pattern
622 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
623 # @ingroup l2_modif_patterns
624 def GetPattern(self):
625 return SMESH._objref_SMESH_Gen.GetPattern(self)
627 ## Sets number of segments per diagonal of boundary box of geometry by which
628 # default segment length of appropriate 1D hypotheses is defined.
629 # Default value is 10
630 # @ingroup l1_auxiliary
631 def SetBoundaryBoxSegmentation(self, nbSegments):
632 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
634 # Filtering. Auxiliary functions:
635 # ------------------------------
637 ## Creates an empty criterion
638 # @return SMESH.Filter.Criterion
639 # @ingroup l1_controls
640 def GetEmptyCriterion(self):
641 Type = self.EnumToLong(FT_Undefined)
642 Compare = self.EnumToLong(FT_Undefined)
646 UnaryOp = self.EnumToLong(FT_Undefined)
647 BinaryOp = self.EnumToLong(FT_Undefined)
650 Precision = -1 ##@1e-07
651 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
652 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
654 ## Creates a criterion by the given parameters
655 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
656 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
657 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
658 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
659 # @param Threshold the threshold value (range of ids as string, shape, numeric)
660 # @param UnaryOp FT_LogicalNOT or FT_Undefined
661 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
662 # FT_Undefined (must be for the last criterion of all criteria)
663 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
664 # FT_LyingOnGeom, FT_CoplanarFaces criteria
665 # @return SMESH.Filter.Criterion
667 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
668 # @ingroup l1_controls
669 def GetCriterion(self,elementType,
671 Compare = FT_EqualTo,
673 UnaryOp=FT_Undefined,
674 BinaryOp=FT_Undefined,
676 if not CritType in SMESH.FunctorType._items:
677 raise TypeError, "CritType should be of SMESH.FunctorType"
678 aCriterion = self.GetEmptyCriterion()
679 aCriterion.TypeOfElement = elementType
680 aCriterion.Type = self.EnumToLong(CritType)
681 aCriterion.Tolerance = Tolerance
683 aThreshold = Threshold
685 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
686 aCriterion.Compare = self.EnumToLong(Compare)
687 elif Compare == "=" or Compare == "==":
688 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
690 aCriterion.Compare = self.EnumToLong(FT_LessThan)
692 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
693 elif Compare != FT_Undefined:
694 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
697 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
698 FT_BelongToCylinder, FT_LyingOnGeom]:
699 # Checks that Threshold is GEOM object
700 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
701 aCriterion.ThresholdStr = GetName(aThreshold)
702 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
703 if not aCriterion.ThresholdID:
704 name = aCriterion.ThresholdStr
706 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
707 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
708 #raise RuntimeError, "Threshold shape must be published"
710 print "Error: The Threshold should be a shape."
712 if isinstance(UnaryOp,float):
713 aCriterion.Tolerance = UnaryOp
714 UnaryOp = FT_Undefined
716 elif CritType == FT_RangeOfIds:
717 # Checks that Threshold is string
718 if isinstance(aThreshold, str):
719 aCriterion.ThresholdStr = aThreshold
721 print "Error: The Threshold should be a string."
723 elif CritType == FT_CoplanarFaces:
724 # Checks the Threshold
725 if isinstance(aThreshold, int):
726 aCriterion.ThresholdID = str(aThreshold)
727 elif isinstance(aThreshold, str):
730 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
731 aCriterion.ThresholdID = aThreshold
734 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
735 elif CritType == FT_ElemGeomType:
736 # Checks the Threshold
738 aCriterion.Threshold = self.EnumToLong(aThreshold)
739 assert( aThreshold in SMESH.GeometryType._items )
741 if isinstance(aThreshold, int):
742 aCriterion.Threshold = aThreshold
744 print "Error: The Threshold should be an integer or SMESH.GeometryType."
748 elif CritType == FT_EntityType:
749 # Checks the Threshold
751 aCriterion.Threshold = self.EnumToLong(aThreshold)
752 assert( aThreshold in SMESH.EntityType._items )
754 if isinstance(aThreshold, int):
755 aCriterion.Threshold = aThreshold
757 print "Error: The Threshold should be an integer or SMESH.EntityType."
762 elif CritType == FT_GroupColor:
763 # Checks the Threshold
765 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
767 print "Error: The threshold value should be of SALOMEDS.Color type"
770 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
771 FT_LinearOrQuadratic, FT_BadOrientedVolume,
772 FT_BareBorderFace, FT_BareBorderVolume,
773 FT_OverConstrainedFace, FT_OverConstrainedVolume,
774 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
775 # At this point the Threshold is unnecessary
776 if aThreshold == FT_LogicalNOT:
777 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
778 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
779 aCriterion.BinaryOp = aThreshold
783 aThreshold = float(aThreshold)
784 aCriterion.Threshold = aThreshold
786 print "Error: The Threshold should be a number."
789 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
790 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
792 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
793 aCriterion.BinaryOp = self.EnumToLong(Threshold)
795 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
796 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
798 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
799 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
803 ## Creates a filter with the given parameters
804 # @param elementType the type of elements in the group
805 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
806 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
807 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
808 # @param UnaryOp FT_LogicalNOT or FT_Undefined
809 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
810 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
811 # @return SMESH_Filter
813 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
814 # @ingroup l1_controls
815 def GetFilter(self,elementType,
816 CritType=FT_Undefined,
819 UnaryOp=FT_Undefined,
821 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
822 aFilterMgr = self.CreateFilterManager()
823 aFilter = aFilterMgr.CreateFilter()
825 aCriteria.append(aCriterion)
826 aFilter.SetCriteria(aCriteria)
827 aFilterMgr.UnRegister()
830 ## Creates a filter from criteria
831 # @param criteria a list of criteria
832 # @return SMESH_Filter
834 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
835 # @ingroup l1_controls
836 def GetFilterFromCriteria(self,criteria):
837 aFilterMgr = self.CreateFilterManager()
838 aFilter = aFilterMgr.CreateFilter()
839 aFilter.SetCriteria(criteria)
840 aFilterMgr.UnRegister()
843 ## Creates a numerical functor by its type
844 # @param theCriterion FT_...; functor type
845 # @return SMESH_NumericalFunctor
846 # @ingroup l1_controls
847 def GetFunctor(self,theCriterion):
848 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
850 aFilterMgr = self.CreateFilterManager()
852 if theCriterion == FT_AspectRatio:
853 functor = aFilterMgr.CreateAspectRatio()
854 elif theCriterion == FT_AspectRatio3D:
855 functor = aFilterMgr.CreateAspectRatio3D()
856 elif theCriterion == FT_Warping:
857 functor = aFilterMgr.CreateWarping()
858 elif theCriterion == FT_MinimumAngle:
859 functor = aFilterMgr.CreateMinimumAngle()
860 elif theCriterion == FT_Taper:
861 functor = aFilterMgr.CreateTaper()
862 elif theCriterion == FT_Skew:
863 functor = aFilterMgr.CreateSkew()
864 elif theCriterion == FT_Area:
865 functor = aFilterMgr.CreateArea()
866 elif theCriterion == FT_Volume3D:
867 functor = aFilterMgr.CreateVolume3D()
868 elif theCriterion == FT_MaxElementLength2D:
869 functor = aFilterMgr.CreateMaxElementLength2D()
870 elif theCriterion == FT_MaxElementLength3D:
871 functor = aFilterMgr.CreateMaxElementLength3D()
872 elif theCriterion == FT_MultiConnection:
873 functor = aFilterMgr.CreateMultiConnection()
874 elif theCriterion == FT_MultiConnection2D:
875 functor = aFilterMgr.CreateMultiConnection2D()
876 elif theCriterion == FT_Length:
877 functor = aFilterMgr.CreateLength()
878 elif theCriterion == FT_Length2D:
879 functor = aFilterMgr.CreateLength2D()
881 print "Error: given parameter is not numerical functor type."
882 aFilterMgr.UnRegister()
885 ## Creates hypothesis
886 # @param theHType mesh hypothesis type (string)
887 # @param theLibName mesh plug-in library name
888 # @return created hypothesis instance
889 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
890 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
892 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
895 # wrap hypothesis methods
896 #print "HYPOTHESIS", theHType
897 for meth_name in dir( hyp.__class__ ):
898 if not meth_name.startswith("Get") and \
899 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
900 method = getattr ( hyp.__class__, meth_name )
902 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
906 ## Gets the mesh statistic
907 # @return dictionary "element type" - "count of elements"
908 # @ingroup l1_meshinfo
909 def GetMeshInfo(self, obj):
910 if isinstance( obj, Mesh ):
913 if hasattr(obj, "GetMeshInfo"):
914 values = obj.GetMeshInfo()
915 for i in range(SMESH.Entity_Last._v):
916 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
920 ## Get minimum distance between two objects
922 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
923 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
925 # @param src1 first source object
926 # @param src2 second source object
927 # @param id1 node/element id from the first source
928 # @param id2 node/element id from the second (or first) source
929 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
930 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
931 # @return minimum distance value
932 # @sa GetMinDistance()
933 # @ingroup l1_measurements
934 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
935 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
939 result = result.value
942 ## Get measure structure specifying minimum distance data between two objects
944 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
945 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
947 # @param src1 first source object
948 # @param src2 second source object
949 # @param id1 node/element id from the first source
950 # @param id2 node/element id from the second (or first) source
951 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
952 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
953 # @return Measure structure or None if input data is invalid
955 # @ingroup l1_measurements
956 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
957 if isinstance(src1, Mesh): src1 = src1.mesh
958 if isinstance(src2, Mesh): src2 = src2.mesh
959 if src2 is None and id2 != 0: src2 = src1
960 if not hasattr(src1, "_narrow"): return None
961 src1 = src1._narrow(SMESH.SMESH_IDSource)
962 if not src1: return None
965 e = m.GetMeshEditor()
967 src1 = e.MakeIDSource([id1], SMESH.FACE)
969 src1 = e.MakeIDSource([id1], SMESH.NODE)
971 if hasattr(src2, "_narrow"):
972 src2 = src2._narrow(SMESH.SMESH_IDSource)
973 if src2 and id2 != 0:
975 e = m.GetMeshEditor()
977 src2 = e.MakeIDSource([id2], SMESH.FACE)
979 src2 = e.MakeIDSource([id2], SMESH.NODE)
982 aMeasurements = self.CreateMeasurements()
983 result = aMeasurements.MinDistance(src1, src2)
984 aMeasurements.UnRegister()
987 ## Get bounding box of the specified object(s)
988 # @param objects single source object or list of source objects
989 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
990 # @sa GetBoundingBox()
991 # @ingroup l1_measurements
992 def BoundingBox(self, objects):
993 result = self.GetBoundingBox(objects)
997 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1000 ## Get measure structure specifying bounding box data of the specified object(s)
1001 # @param objects single source object or list of source objects
1002 # @return Measure structure
1004 # @ingroup l1_measurements
1005 def GetBoundingBox(self, objects):
1006 if isinstance(objects, tuple):
1007 objects = list(objects)
1008 if not isinstance(objects, list):
1012 if isinstance(o, Mesh):
1013 srclist.append(o.mesh)
1014 elif hasattr(o, "_narrow"):
1015 src = o._narrow(SMESH.SMESH_IDSource)
1016 if src: srclist.append(src)
1019 aMeasurements = self.CreateMeasurements()
1020 result = aMeasurements.BoundingBox(srclist)
1021 aMeasurements.UnRegister()
1025 #Registering the new proxy for SMESH_Gen
1026 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1028 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1029 # interface to create or load meshes.
1034 # salome.salome_init()
1035 # from salome.smesh import smeshBuilder
1036 # smesh = smeshBuilder.New(theStudy)
1038 # @param study SALOME study, generally obtained by salome.myStudy.
1039 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1040 # @return smeshBuilder instance
1042 def New( study, instance=None):
1044 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1045 interface to create or load meshes.
1049 salome.salome_init()
1050 from salome.smesh import smeshBuilder
1051 smesh = smeshBuilder.New(theStudy)
1054 study SALOME study, generally obtained by salome.myStudy.
1055 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1057 smeshBuilder instance
1065 smeshInst = smeshBuilder()
1066 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1067 smeshInst.init_smesh(study)
1071 # Public class: Mesh
1072 # ==================
1074 ## This class allows defining and managing a mesh.
1075 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1076 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1077 # new nodes and elements and by changing the existing entities), to get information
1078 # about a mesh and to export a mesh into different formats.
1087 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1088 # sets the GUI name of this mesh to \a name.
1089 # @param smeshpyD an instance of smeshBuilder class
1090 # @param geompyD an instance of geomBuilder class
1091 # @param obj Shape to be meshed or SMESH_Mesh object
1092 # @param name Study name of the mesh
1093 # @ingroup l2_construct
1094 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1095 self.smeshpyD=smeshpyD
1096 self.geompyD=geompyD
1101 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1104 # publish geom of mesh (issue 0021122)
1105 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1107 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1108 if studyID != geompyD.myStudyId:
1109 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1112 geo_name = name + " shape"
1114 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1115 geompyD.addToStudy( self.geom, geo_name )
1116 self.mesh = self.smeshpyD.CreateMesh(self.geom)
1118 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1121 self.mesh = self.smeshpyD.CreateEmptyMesh()
1123 self.smeshpyD.SetName(self.mesh, name)
1125 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1128 self.geom = self.mesh.GetShapeToMesh()
1130 self.editor = self.mesh.GetMeshEditor()
1131 self.functors = [None] * SMESH.FT_Undefined._v
1133 # set self to algoCreator's
1134 for attrName in dir(self):
1135 attr = getattr( self, attrName )
1136 if isinstance( attr, algoCreator ):
1137 #print "algoCreator ", attrName
1138 setattr( self, attrName, attr.copy( self ))
1140 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1141 # @param theMesh a SMESH_Mesh object
1142 # @ingroup l2_construct
1143 def SetMesh(self, theMesh):
1144 if self.mesh: self.mesh.UnRegister()
1147 self.mesh.Register()
1148 self.geom = self.mesh.GetShapeToMesh()
1150 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1151 # @return a SMESH_Mesh object
1152 # @ingroup l2_construct
1156 ## Gets the name of the mesh
1157 # @return the name of the mesh as a string
1158 # @ingroup l2_construct
1160 name = GetName(self.GetMesh())
1163 ## Sets a name to the mesh
1164 # @param name a new name of the mesh
1165 # @ingroup l2_construct
1166 def SetName(self, name):
1167 self.smeshpyD.SetName(self.GetMesh(), name)
1169 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1170 # The subMesh object gives access to the IDs of nodes and elements.
1171 # @param geom a geometrical object (shape)
1172 # @param name a name for the submesh
1173 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1174 # @ingroup l2_submeshes
1175 def GetSubMesh(self, geom, name):
1176 AssureGeomPublished( self, geom, name )
1177 submesh = self.mesh.GetSubMesh( geom, name )
1180 ## Returns the shape associated to the mesh
1181 # @return a GEOM_Object
1182 # @ingroup l2_construct
1186 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1187 # @param geom the shape to be meshed (GEOM_Object)
1188 # @ingroup l2_construct
1189 def SetShape(self, geom):
1190 self.mesh = self.smeshpyD.CreateMesh(geom)
1192 ## Loads mesh from the study after opening the study
1196 ## Returns true if the hypotheses are defined well
1197 # @param theSubObject a sub-shape of a mesh shape
1198 # @return True or False
1199 # @ingroup l2_construct
1200 def IsReadyToCompute(self, theSubObject):
1201 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1203 ## Returns errors of hypotheses definition.
1204 # The list of errors is empty if everything is OK.
1205 # @param theSubObject a sub-shape of a mesh shape
1206 # @return a list of errors
1207 # @ingroup l2_construct
1208 def GetAlgoState(self, theSubObject):
1209 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1211 ## Returns a geometrical object on which the given element was built.
1212 # The returned geometrical object, if not nil, is either found in the
1213 # study or published by this method with the given name
1214 # @param theElementID the id of the mesh element
1215 # @param theGeomName the user-defined name of the geometrical object
1216 # @return GEOM::GEOM_Object instance
1217 # @ingroup l2_construct
1218 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1219 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1221 ## Returns the mesh dimension depending on the dimension of the underlying shape
1222 # or, if the mesh is not based on any shape, basing on deimension of elements
1223 # @return mesh dimension as an integer value [0,3]
1224 # @ingroup l1_auxiliary
1225 def MeshDimension(self):
1226 if self.mesh.HasShapeToMesh():
1227 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1228 if len( shells ) > 0 :
1230 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1232 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1237 if self.NbVolumes() > 0: return 3
1238 if self.NbFaces() > 0: return 2
1239 if self.NbEdges() > 0: return 1
1242 ## Evaluates size of prospective mesh on a shape
1243 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1244 # To know predicted number of e.g. edges, inquire it this way
1245 # Evaluate()[ EnumToLong( Entity_Edge )]
1246 def Evaluate(self, geom=0):
1247 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1249 geom = self.mesh.GetShapeToMesh()
1252 return self.smeshpyD.Evaluate(self.mesh, geom)
1255 ## Computes the mesh and returns the status of the computation
1256 # @param geom geomtrical shape on which mesh data should be computed
1257 # @param discardModifs if True and the mesh has been edited since
1258 # a last total re-compute and that may prevent successful partial re-compute,
1259 # then the mesh is cleaned before Compute()
1260 # @return True or False
1261 # @ingroup l2_construct
1262 def Compute(self, geom=0, discardModifs=False):
1263 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1265 geom = self.mesh.GetShapeToMesh()
1270 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1272 ok = self.smeshpyD.Compute(self.mesh, geom)
1273 except SALOME.SALOME_Exception, ex:
1274 print "Mesh computation failed, exception caught:"
1275 print " ", ex.details.text
1278 print "Mesh computation failed, exception caught:"
1279 traceback.print_exc()
1283 # Treat compute errors
1284 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1285 for err in computeErrors:
1287 if self.mesh.HasShapeToMesh():
1289 mainIOR = salome.orb.object_to_string(geom)
1290 for sname in salome.myStudyManager.GetOpenStudies():
1291 s = salome.myStudyManager.GetStudyByName(sname)
1293 mainSO = s.FindObjectIOR(mainIOR)
1294 if not mainSO: continue
1295 if err.subShapeID == 1:
1296 shapeText = ' on "%s"' % mainSO.GetName()
1297 subIt = s.NewChildIterator(mainSO)
1299 subSO = subIt.Value()
1301 obj = subSO.GetObject()
1302 if not obj: continue
1303 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1305 ids = go.GetSubShapeIndices()
1306 if len(ids) == 1 and ids[0] == err.subShapeID:
1307 shapeText = ' on "%s"' % subSO.GetName()
1310 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1312 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1314 shapeText = " on subshape #%s" % (err.subShapeID)
1316 shapeText = " on subshape #%s" % (err.subShapeID)
1318 stdErrors = ["OK", #COMPERR_OK
1319 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1320 "std::exception", #COMPERR_STD_EXCEPTION
1321 "OCC exception", #COMPERR_OCC_EXCEPTION
1322 "..", #COMPERR_SLM_EXCEPTION
1323 "Unknown exception", #COMPERR_EXCEPTION
1324 "Memory allocation problem", #COMPERR_MEMORY_PB
1325 "Algorithm failed", #COMPERR_ALGO_FAILED
1326 "Unexpected geometry", #COMPERR_BAD_SHAPE
1327 "Warning", #COMPERR_WARNING
1328 "Computation cancelled",#COMPERR_CANCELED
1329 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1331 if err.code < len(stdErrors): errText = stdErrors[err.code]
1333 errText = "code %s" % -err.code
1334 if errText: errText += ". "
1335 errText += err.comment
1336 if allReasons != "":allReasons += "\n"
1337 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1341 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1343 if err.isGlobalAlgo:
1351 reason = '%s %sD algorithm is missing' % (glob, dim)
1352 elif err.state == HYP_MISSING:
1353 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1354 % (glob, dim, name, dim))
1355 elif err.state == HYP_NOTCONFORM:
1356 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1357 elif err.state == HYP_BAD_PARAMETER:
1358 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1359 % ( glob, dim, name ))
1360 elif err.state == HYP_BAD_GEOMETRY:
1361 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1362 'geometry' % ( glob, dim, name ))
1363 elif err.state == HYP_HIDDEN_ALGO:
1364 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1365 'algorithm of upper dimension generating %sD mesh'
1366 % ( glob, dim, name, glob, dim ))
1368 reason = ("For unknown reason. "
1369 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1371 if allReasons != "":allReasons += "\n"
1372 allReasons += "- " + reason
1374 if not ok or allReasons != "":
1375 msg = '"' + GetName(self.mesh) + '"'
1376 if ok: msg += " has been computed with warnings"
1377 else: msg += " has not been computed"
1378 if allReasons != "": msg += ":"
1383 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1384 smeshgui = salome.ImportComponentGUI("SMESH")
1385 smeshgui.Init(self.mesh.GetStudyId())
1386 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1387 salome.sg.updateObjBrowser(1)
1391 ## Return submesh objects list in meshing order
1392 # @return list of list of submesh objects
1393 # @ingroup l2_construct
1394 def GetMeshOrder(self):
1395 return self.mesh.GetMeshOrder()
1397 ## Return submesh objects list in meshing order
1398 # @return list of list of submesh objects
1399 # @ingroup l2_construct
1400 def SetMeshOrder(self, submeshes):
1401 return self.mesh.SetMeshOrder(submeshes)
1403 ## Removes all nodes and elements
1404 # @ingroup l2_construct
1407 if ( salome.sg.hasDesktop() and
1408 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1409 smeshgui = salome.ImportComponentGUI("SMESH")
1410 smeshgui.Init(self.mesh.GetStudyId())
1411 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1412 salome.sg.updateObjBrowser(1)
1414 ## Removes all nodes and elements of indicated shape
1415 # @ingroup l2_construct
1416 def ClearSubMesh(self, geomId):
1417 self.mesh.ClearSubMesh(geomId)
1418 if salome.sg.hasDesktop():
1419 smeshgui = salome.ImportComponentGUI("SMESH")
1420 smeshgui.Init(self.mesh.GetStudyId())
1421 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1422 salome.sg.updateObjBrowser(1)
1424 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1425 # @param fineness [0.0,1.0] defines mesh fineness
1426 # @return True or False
1427 # @ingroup l3_algos_basic
1428 def AutomaticTetrahedralization(self, fineness=0):
1429 dim = self.MeshDimension()
1431 self.RemoveGlobalHypotheses()
1432 self.Segment().AutomaticLength(fineness)
1434 self.Triangle().LengthFromEdges()
1437 from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1438 self.Tetrahedron(NETGEN)
1440 return self.Compute()
1442 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1443 # @param fineness [0.0, 1.0] defines mesh fineness
1444 # @return True or False
1445 # @ingroup l3_algos_basic
1446 def AutomaticHexahedralization(self, fineness=0):
1447 dim = self.MeshDimension()
1448 # assign the hypotheses
1449 self.RemoveGlobalHypotheses()
1450 self.Segment().AutomaticLength(fineness)
1457 return self.Compute()
1459 ## Assigns a hypothesis
1460 # @param hyp a hypothesis to assign
1461 # @param geom a subhape of mesh geometry
1462 # @return SMESH.Hypothesis_Status
1463 # @ingroup l2_hypotheses
1464 def AddHypothesis(self, hyp, geom=0):
1465 if isinstance( hyp, Mesh_Algorithm ):
1466 hyp = hyp.GetAlgorithm()
1471 geom = self.mesh.GetShapeToMesh()
1473 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1474 status = self.mesh.AddHypothesis(geom, hyp)
1475 isAlgo = hyp._narrow( SMESH_Algo )
1476 hyp_name = GetName( hyp )
1479 geom_name = GetName( geom )
1480 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1483 ## Return True if an algorithm of hypothesis is assigned to a given shape
1484 # @param hyp a hypothesis to check
1485 # @param geom a subhape of mesh geometry
1486 # @return True of False
1487 # @ingroup l2_hypotheses
1488 def IsUsedHypothesis(self, hyp, geom):
1489 if not hyp: # or not geom
1491 if isinstance( hyp, Mesh_Algorithm ):
1492 hyp = hyp.GetAlgorithm()
1494 hyps = self.GetHypothesisList(geom)
1496 if h.GetId() == hyp.GetId():
1500 ## Unassigns a hypothesis
1501 # @param hyp a hypothesis to unassign
1502 # @param geom a sub-shape of mesh geometry
1503 # @return SMESH.Hypothesis_Status
1504 # @ingroup l2_hypotheses
1505 def RemoveHypothesis(self, hyp, geom=0):
1506 if isinstance( hyp, Mesh_Algorithm ):
1507 hyp = hyp.GetAlgorithm()
1513 if self.IsUsedHypothesis( hyp, shape ):
1514 return self.mesh.RemoveHypothesis( shape, hyp )
1515 hypName = GetName( hyp )
1516 geoName = GetName( shape )
1517 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1520 ## Gets the list of hypotheses added on a geometry
1521 # @param geom a sub-shape of mesh geometry
1522 # @return the sequence of SMESH_Hypothesis
1523 # @ingroup l2_hypotheses
1524 def GetHypothesisList(self, geom):
1525 return self.mesh.GetHypothesisList( geom )
1527 ## Removes all global hypotheses
1528 # @ingroup l2_hypotheses
1529 def RemoveGlobalHypotheses(self):
1530 current_hyps = self.mesh.GetHypothesisList( self.geom )
1531 for hyp in current_hyps:
1532 self.mesh.RemoveHypothesis( self.geom, hyp )
1536 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1537 ## allowing to overwrite the file if it exists or add the exported data to its contents
1538 # @param f is the file name
1539 # @param auto_groups boolean parameter for creating/not creating
1540 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1541 # the typical use is auto_groups=false.
1542 # @param version MED format version(MED_V2_1 or MED_V2_2)
1543 # @param overwrite boolean parameter for overwriting/not overwriting the file
1544 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1545 # @ingroup l2_impexp
1546 def ExportMED(self, f, auto_groups=0, version=MED_V2_2, overwrite=1, meshPart=None):
1548 if isinstance( meshPart, list ):
1549 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1550 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite )
1552 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite)
1554 ## Exports the mesh in a file in SAUV format
1555 # @param f is the file name
1556 # @param auto_groups boolean parameter for creating/not creating
1557 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1558 # the typical use is auto_groups=false.
1559 # @ingroup l2_impexp
1560 def ExportSAUV(self, f, auto_groups=0):
1561 self.mesh.ExportSAUV(f, auto_groups)
1563 ## Exports the mesh in a file in DAT format
1564 # @param f the file name
1565 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1566 # @ingroup l2_impexp
1567 def ExportDAT(self, f, meshPart=None):
1569 if isinstance( meshPart, list ):
1570 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1571 self.mesh.ExportPartToDAT( meshPart, f )
1573 self.mesh.ExportDAT(f)
1575 ## Exports the mesh in a file in UNV format
1576 # @param f the file name
1577 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1578 # @ingroup l2_impexp
1579 def ExportUNV(self, f, meshPart=None):
1581 if isinstance( meshPart, list ):
1582 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1583 self.mesh.ExportPartToUNV( meshPart, f )
1585 self.mesh.ExportUNV(f)
1587 ## Export the mesh in a file in STL format
1588 # @param f the file name
1589 # @param ascii defines the file encoding
1590 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1591 # @ingroup l2_impexp
1592 def ExportSTL(self, f, ascii=1, meshPart=None):
1594 if isinstance( meshPart, list ):
1595 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1596 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1598 self.mesh.ExportSTL(f, ascii)
1600 ## Exports the mesh in a file in CGNS format
1601 # @param f is the file name
1602 # @param overwrite boolean parameter for overwriting/not overwriting the file
1603 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1604 # @ingroup l2_impexp
1605 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1606 if isinstance( meshPart, list ):
1607 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1608 if isinstance( meshPart, Mesh ):
1609 meshPart = meshPart.mesh
1611 meshPart = self.mesh
1612 self.mesh.ExportCGNS(meshPart, f, overwrite)
1614 ## Exports the mesh in a file in GMF format
1615 # @param f is the file name
1616 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1617 # @ingroup l2_impexp
1618 def ExportGMF(self, f, meshPart=None):
1619 if isinstance( meshPart, list ):
1620 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1621 if isinstance( meshPart, Mesh ):
1622 meshPart = meshPart.mesh
1624 meshPart = self.mesh
1625 self.mesh.ExportGMF(meshPart, f, True)
1627 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1628 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1629 ## allowing to overwrite the file if it exists or add the exported data to its contents
1630 # @param f the file name
1631 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1632 # @param opt boolean parameter for creating/not creating
1633 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1634 # @param overwrite boolean parameter for overwriting/not overwriting the file
1635 # @ingroup l2_impexp
1636 def ExportToMED(self, f, version, opt=0, overwrite=1):
1637 self.mesh.ExportToMEDX(f, opt, version, overwrite)
1639 # Operations with groups:
1640 # ----------------------
1642 ## Creates an empty mesh group
1643 # @param elementType the type of elements in the group
1644 # @param name the name of the mesh group
1645 # @return SMESH_Group
1646 # @ingroup l2_grps_create
1647 def CreateEmptyGroup(self, elementType, name):
1648 return self.mesh.CreateGroup(elementType, name)
1650 ## Creates a mesh group based on the geometric object \a grp
1651 # and gives a \a name, \n if this parameter is not defined
1652 # the name is the same as the geometric group name \n
1653 # Note: Works like GroupOnGeom().
1654 # @param grp a geometric group, a vertex, an edge, a face or a solid
1655 # @param name the name of the mesh group
1656 # @return SMESH_GroupOnGeom
1657 # @ingroup l2_grps_create
1658 def Group(self, grp, name=""):
1659 return self.GroupOnGeom(grp, name)
1661 ## Creates a mesh group based on the geometrical object \a grp
1662 # and gives a \a name, \n if this parameter is not defined
1663 # the name is the same as the geometrical group name
1664 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1665 # @param name the name of the mesh group
1666 # @param typ the type of elements in the group. If not set, it is
1667 # automatically detected by the type of the geometry
1668 # @return SMESH_GroupOnGeom
1669 # @ingroup l2_grps_create
1670 def GroupOnGeom(self, grp, name="", typ=None):
1671 AssureGeomPublished( self, grp, name )
1673 name = grp.GetName()
1675 typ = self._groupTypeFromShape( grp )
1676 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1678 ## Pivate method to get a type of group on geometry
1679 def _groupTypeFromShape( self, shape ):
1680 tgeo = str(shape.GetShapeType())
1681 if tgeo == "VERTEX":
1683 elif tgeo == "EDGE":
1685 elif tgeo == "FACE" or tgeo == "SHELL":
1687 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1689 elif tgeo == "COMPOUND":
1690 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1692 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1693 return self._groupTypeFromShape( sub[0] )
1696 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1699 ## Creates a mesh group with given \a name based on the \a filter which
1700 ## is a special type of group dynamically updating it's contents during
1701 ## mesh modification
1702 # @param typ the type of elements in the group
1703 # @param name the name of the mesh group
1704 # @param filter the filter defining group contents
1705 # @return SMESH_GroupOnFilter
1706 # @ingroup l2_grps_create
1707 def GroupOnFilter(self, typ, name, filter):
1708 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1710 ## Creates a mesh group by the given ids of elements
1711 # @param groupName the name of the mesh group
1712 # @param elementType the type of elements in the group
1713 # @param elemIDs the list of ids
1714 # @return SMESH_Group
1715 # @ingroup l2_grps_create
1716 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1717 group = self.mesh.CreateGroup(elementType, groupName)
1721 ## Creates a mesh group by the given conditions
1722 # @param groupName the name of the mesh group
1723 # @param elementType the type of elements in the group
1724 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1725 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1726 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1727 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1728 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1729 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1730 # @return SMESH_Group
1731 # @ingroup l2_grps_create
1735 CritType=FT_Undefined,
1738 UnaryOp=FT_Undefined,
1740 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1741 group = self.MakeGroupByCriterion(groupName, aCriterion)
1744 ## Creates a mesh group by the given criterion
1745 # @param groupName the name of the mesh group
1746 # @param Criterion the instance of Criterion class
1747 # @return SMESH_Group
1748 # @ingroup l2_grps_create
1749 def MakeGroupByCriterion(self, groupName, Criterion):
1750 aFilterMgr = self.smeshpyD.CreateFilterManager()
1751 aFilter = aFilterMgr.CreateFilter()
1753 aCriteria.append(Criterion)
1754 aFilter.SetCriteria(aCriteria)
1755 group = self.MakeGroupByFilter(groupName, aFilter)
1756 aFilterMgr.UnRegister()
1759 ## Creates a mesh group by the given criteria (list of criteria)
1760 # @param groupName the name of the mesh group
1761 # @param theCriteria the list of criteria
1762 # @return SMESH_Group
1763 # @ingroup l2_grps_create
1764 def MakeGroupByCriteria(self, groupName, theCriteria):
1765 aFilterMgr = self.smeshpyD.CreateFilterManager()
1766 aFilter = aFilterMgr.CreateFilter()
1767 aFilter.SetCriteria(theCriteria)
1768 group = self.MakeGroupByFilter(groupName, aFilter)
1769 aFilterMgr.UnRegister()
1772 ## Creates a mesh group by the given filter
1773 # @param groupName the name of the mesh group
1774 # @param theFilter the instance of Filter class
1775 # @return SMESH_Group
1776 # @ingroup l2_grps_create
1777 def MakeGroupByFilter(self, groupName, theFilter):
1778 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1779 theFilter.SetMesh( self.mesh )
1780 group.AddFrom( theFilter )
1784 # @ingroup l2_grps_delete
1785 def RemoveGroup(self, group):
1786 self.mesh.RemoveGroup(group)
1788 ## Removes a group with its contents
1789 # @ingroup l2_grps_delete
1790 def RemoveGroupWithContents(self, group):
1791 self.mesh.RemoveGroupWithContents(group)
1793 ## Gets the list of groups existing in the mesh
1794 # @return a sequence of SMESH_GroupBase
1795 # @ingroup l2_grps_create
1796 def GetGroups(self):
1797 return self.mesh.GetGroups()
1799 ## Gets the number of groups existing in the mesh
1800 # @return the quantity of groups as an integer value
1801 # @ingroup l2_grps_create
1803 return self.mesh.NbGroups()
1805 ## Gets the list of names of groups existing in the mesh
1806 # @return list of strings
1807 # @ingroup l2_grps_create
1808 def GetGroupNames(self):
1809 groups = self.GetGroups()
1811 for group in groups:
1812 names.append(group.GetName())
1815 ## Produces a union of two groups
1816 # A new group is created. All mesh elements that are
1817 # present in the initial groups are added to the new one
1818 # @return an instance of SMESH_Group
1819 # @ingroup l2_grps_operon
1820 def UnionGroups(self, group1, group2, name):
1821 return self.mesh.UnionGroups(group1, group2, name)
1823 ## Produces a union list of groups
1824 # New group is created. All mesh elements that are present in
1825 # initial groups are added to the new one
1826 # @return an instance of SMESH_Group
1827 # @ingroup l2_grps_operon
1828 def UnionListOfGroups(self, groups, name):
1829 return self.mesh.UnionListOfGroups(groups, name)
1831 ## Prodices an intersection of two groups
1832 # A new group is created. All mesh elements that are common
1833 # for the two initial groups are added to the new one.
1834 # @return an instance of SMESH_Group
1835 # @ingroup l2_grps_operon
1836 def IntersectGroups(self, group1, group2, name):
1837 return self.mesh.IntersectGroups(group1, group2, name)
1839 ## Produces an intersection of groups
1840 # New group is created. All mesh elements that are present in all
1841 # initial groups simultaneously are added to the new one
1842 # @return an instance of SMESH_Group
1843 # @ingroup l2_grps_operon
1844 def IntersectListOfGroups(self, groups, name):
1845 return self.mesh.IntersectListOfGroups(groups, name)
1847 ## Produces a cut of two groups
1848 # A new group is created. All mesh elements that are present in
1849 # the main group but are not present in the tool group are added to the new one
1850 # @return an instance of SMESH_Group
1851 # @ingroup l2_grps_operon
1852 def CutGroups(self, main_group, tool_group, name):
1853 return self.mesh.CutGroups(main_group, tool_group, name)
1855 ## Produces a cut of groups
1856 # A new group is created. All mesh elements that are present in main groups
1857 # but do not present in tool groups are added to the new one
1858 # @return an instance of SMESH_Group
1859 # @ingroup l2_grps_operon
1860 def CutListOfGroups(self, main_groups, tool_groups, name):
1861 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1863 ## Produces a group of elements of specified type using list of existing groups
1864 # A new group is created. System
1865 # 1) extracts all nodes on which groups elements are built
1866 # 2) combines all elements of specified dimension laying on these nodes
1867 # @return an instance of SMESH_Group
1868 # @ingroup l2_grps_operon
1869 def CreateDimGroup(self, groups, elem_type, name):
1870 return self.mesh.CreateDimGroup(groups, elem_type, name)
1873 ## Convert group on geom into standalone group
1874 # @ingroup l2_grps_delete
1875 def ConvertToStandalone(self, group):
1876 return self.mesh.ConvertToStandalone(group)
1878 # Get some info about mesh:
1879 # ------------------------
1881 ## Returns the log of nodes and elements added or removed
1882 # since the previous clear of the log.
1883 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
1884 # @return list of log_block structures:
1889 # @ingroup l1_auxiliary
1890 def GetLog(self, clearAfterGet):
1891 return self.mesh.GetLog(clearAfterGet)
1893 ## Clears the log of nodes and elements added or removed since the previous
1894 # clear. Must be used immediately after GetLog if clearAfterGet is false.
1895 # @ingroup l1_auxiliary
1897 self.mesh.ClearLog()
1899 ## Toggles auto color mode on the object.
1900 # @param theAutoColor the flag which toggles auto color mode.
1901 # @ingroup l1_auxiliary
1902 def SetAutoColor(self, theAutoColor):
1903 self.mesh.SetAutoColor(theAutoColor)
1905 ## Gets flag of object auto color mode.
1906 # @return True or False
1907 # @ingroup l1_auxiliary
1908 def GetAutoColor(self):
1909 return self.mesh.GetAutoColor()
1911 ## Gets the internal ID
1912 # @return integer value, which is the internal Id of the mesh
1913 # @ingroup l1_auxiliary
1915 return self.mesh.GetId()
1918 # @return integer value, which is the study Id of the mesh
1919 # @ingroup l1_auxiliary
1920 def GetStudyId(self):
1921 return self.mesh.GetStudyId()
1923 ## Checks the group names for duplications.
1924 # Consider the maximum group name length stored in MED file.
1925 # @return True or False
1926 # @ingroup l1_auxiliary
1927 def HasDuplicatedGroupNamesMED(self):
1928 return self.mesh.HasDuplicatedGroupNamesMED()
1930 ## Obtains the mesh editor tool
1931 # @return an instance of SMESH_MeshEditor
1932 # @ingroup l1_modifying
1933 def GetMeshEditor(self):
1936 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
1937 # can be passed as argument to a method accepting mesh, group or sub-mesh
1938 # @return an instance of SMESH_IDSource
1939 # @ingroup l1_auxiliary
1940 def GetIDSource(self, ids, elemType):
1941 return self.editor.MakeIDSource(ids, elemType)
1944 # @return an instance of SALOME_MED::MESH
1945 # @ingroup l1_auxiliary
1946 def GetMEDMesh(self):
1947 return self.mesh.GetMEDMesh()
1950 # Get informations about mesh contents:
1951 # ------------------------------------
1953 ## Gets the mesh stattistic
1954 # @return dictionary type element - count of elements
1955 # @ingroup l1_meshinfo
1956 def GetMeshInfo(self, obj = None):
1957 if not obj: obj = self.mesh
1958 return self.smeshpyD.GetMeshInfo(obj)
1960 ## Returns the number of nodes in the mesh
1961 # @return an integer value
1962 # @ingroup l1_meshinfo
1964 return self.mesh.NbNodes()
1966 ## Returns the number of elements in the mesh
1967 # @return an integer value
1968 # @ingroup l1_meshinfo
1969 def NbElements(self):
1970 return self.mesh.NbElements()
1972 ## Returns the number of 0d elements in the mesh
1973 # @return an integer value
1974 # @ingroup l1_meshinfo
1975 def Nb0DElements(self):
1976 return self.mesh.Nb0DElements()
1978 ## Returns the number of ball discrete elements in the mesh
1979 # @return an integer value
1980 # @ingroup l1_meshinfo
1982 return self.mesh.NbBalls()
1984 ## Returns the number of edges in the mesh
1985 # @return an integer value
1986 # @ingroup l1_meshinfo
1988 return self.mesh.NbEdges()
1990 ## Returns the number of edges with the given order in the mesh
1991 # @param elementOrder the order of elements:
1992 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1993 # @return an integer value
1994 # @ingroup l1_meshinfo
1995 def NbEdgesOfOrder(self, elementOrder):
1996 return self.mesh.NbEdgesOfOrder(elementOrder)
1998 ## Returns the number of faces in the mesh
1999 # @return an integer value
2000 # @ingroup l1_meshinfo
2002 return self.mesh.NbFaces()
2004 ## Returns the number of faces with the given order in the mesh
2005 # @param elementOrder the order of elements:
2006 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2007 # @return an integer value
2008 # @ingroup l1_meshinfo
2009 def NbFacesOfOrder(self, elementOrder):
2010 return self.mesh.NbFacesOfOrder(elementOrder)
2012 ## Returns the number of triangles in the mesh
2013 # @return an integer value
2014 # @ingroup l1_meshinfo
2015 def NbTriangles(self):
2016 return self.mesh.NbTriangles()
2018 ## Returns the number of triangles with the given order in the mesh
2019 # @param elementOrder is the order of elements:
2020 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2021 # @return an integer value
2022 # @ingroup l1_meshinfo
2023 def NbTrianglesOfOrder(self, elementOrder):
2024 return self.mesh.NbTrianglesOfOrder(elementOrder)
2026 ## Returns the number of quadrangles in the mesh
2027 # @return an integer value
2028 # @ingroup l1_meshinfo
2029 def NbQuadrangles(self):
2030 return self.mesh.NbQuadrangles()
2032 ## Returns the number of quadrangles with the given order in the mesh
2033 # @param elementOrder the order of elements:
2034 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2035 # @return an integer value
2036 # @ingroup l1_meshinfo
2037 def NbQuadranglesOfOrder(self, elementOrder):
2038 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2040 ## Returns the number of biquadratic quadrangles in the mesh
2041 # @return an integer value
2042 # @ingroup l1_meshinfo
2043 def NbBiQuadQuadrangles(self):
2044 return self.mesh.NbBiQuadQuadrangles()
2046 ## Returns the number of polygons in the mesh
2047 # @return an integer value
2048 # @ingroup l1_meshinfo
2049 def NbPolygons(self):
2050 return self.mesh.NbPolygons()
2052 ## Returns the number of volumes in the mesh
2053 # @return an integer value
2054 # @ingroup l1_meshinfo
2055 def NbVolumes(self):
2056 return self.mesh.NbVolumes()
2058 ## Returns the number of volumes with the given order in the mesh
2059 # @param elementOrder the order of elements:
2060 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2061 # @return an integer value
2062 # @ingroup l1_meshinfo
2063 def NbVolumesOfOrder(self, elementOrder):
2064 return self.mesh.NbVolumesOfOrder(elementOrder)
2066 ## Returns the number of tetrahedrons in the mesh
2067 # @return an integer value
2068 # @ingroup l1_meshinfo
2070 return self.mesh.NbTetras()
2072 ## Returns the number of tetrahedrons with the given order in the mesh
2073 # @param elementOrder the order of elements:
2074 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2075 # @return an integer value
2076 # @ingroup l1_meshinfo
2077 def NbTetrasOfOrder(self, elementOrder):
2078 return self.mesh.NbTetrasOfOrder(elementOrder)
2080 ## Returns the number of hexahedrons in the mesh
2081 # @return an integer value
2082 # @ingroup l1_meshinfo
2084 return self.mesh.NbHexas()
2086 ## Returns the number of hexahedrons with the given order in the mesh
2087 # @param elementOrder the order of elements:
2088 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2089 # @return an integer value
2090 # @ingroup l1_meshinfo
2091 def NbHexasOfOrder(self, elementOrder):
2092 return self.mesh.NbHexasOfOrder(elementOrder)
2094 ## Returns the number of triquadratic hexahedrons in the mesh
2095 # @return an integer value
2096 # @ingroup l1_meshinfo
2097 def NbTriQuadraticHexas(self):
2098 return self.mesh.NbTriQuadraticHexas()
2100 ## Returns the number of pyramids in the mesh
2101 # @return an integer value
2102 # @ingroup l1_meshinfo
2103 def NbPyramids(self):
2104 return self.mesh.NbPyramids()
2106 ## Returns the number of pyramids with the given order in the mesh
2107 # @param elementOrder the order of elements:
2108 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2109 # @return an integer value
2110 # @ingroup l1_meshinfo
2111 def NbPyramidsOfOrder(self, elementOrder):
2112 return self.mesh.NbPyramidsOfOrder(elementOrder)
2114 ## Returns the number of prisms in the mesh
2115 # @return an integer value
2116 # @ingroup l1_meshinfo
2118 return self.mesh.NbPrisms()
2120 ## Returns the number of prisms with the given order in the mesh
2121 # @param elementOrder the order of elements:
2122 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2123 # @return an integer value
2124 # @ingroup l1_meshinfo
2125 def NbPrismsOfOrder(self, elementOrder):
2126 return self.mesh.NbPrismsOfOrder(elementOrder)
2128 ## Returns the number of hexagonal prisms in the mesh
2129 # @return an integer value
2130 # @ingroup l1_meshinfo
2131 def NbHexagonalPrisms(self):
2132 return self.mesh.NbHexagonalPrisms()
2134 ## Returns the number of polyhedrons in the mesh
2135 # @return an integer value
2136 # @ingroup l1_meshinfo
2137 def NbPolyhedrons(self):
2138 return self.mesh.NbPolyhedrons()
2140 ## Returns the number of submeshes in the mesh
2141 # @return an integer value
2142 # @ingroup l1_meshinfo
2143 def NbSubMesh(self):
2144 return self.mesh.NbSubMesh()
2146 ## Returns the list of mesh elements IDs
2147 # @return the list of integer values
2148 # @ingroup l1_meshinfo
2149 def GetElementsId(self):
2150 return self.mesh.GetElementsId()
2152 ## Returns the list of IDs of mesh elements with the given type
2153 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2154 # @return list of integer values
2155 # @ingroup l1_meshinfo
2156 def GetElementsByType(self, elementType):
2157 return self.mesh.GetElementsByType(elementType)
2159 ## Returns the list of mesh nodes IDs
2160 # @return the list of integer values
2161 # @ingroup l1_meshinfo
2162 def GetNodesId(self):
2163 return self.mesh.GetNodesId()
2165 # Get the information about mesh elements:
2166 # ------------------------------------
2168 ## Returns the type of mesh element
2169 # @return the value from SMESH::ElementType enumeration
2170 # @ingroup l1_meshinfo
2171 def GetElementType(self, id, iselem):
2172 return self.mesh.GetElementType(id, iselem)
2174 ## Returns the geometric type of mesh element
2175 # @return the value from SMESH::EntityType enumeration
2176 # @ingroup l1_meshinfo
2177 def GetElementGeomType(self, id):
2178 return self.mesh.GetElementGeomType(id)
2180 ## Returns the list of submesh elements IDs
2181 # @param Shape a geom object(sub-shape) IOR
2182 # Shape must be the sub-shape of a ShapeToMesh()
2183 # @return the list of integer values
2184 # @ingroup l1_meshinfo
2185 def GetSubMeshElementsId(self, Shape):
2186 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2187 ShapeID = Shape.GetSubShapeIndices()[0]
2190 return self.mesh.GetSubMeshElementsId(ShapeID)
2192 ## Returns the list of submesh nodes IDs
2193 # @param Shape a geom object(sub-shape) IOR
2194 # Shape must be the sub-shape of a ShapeToMesh()
2195 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2196 # @return the list of integer values
2197 # @ingroup l1_meshinfo
2198 def GetSubMeshNodesId(self, Shape, all):
2199 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2200 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2203 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2205 ## Returns type of elements on given shape
2206 # @param Shape a geom object(sub-shape) IOR
2207 # Shape must be a sub-shape of a ShapeToMesh()
2208 # @return element type
2209 # @ingroup l1_meshinfo
2210 def GetSubMeshElementType(self, Shape):
2211 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2212 ShapeID = Shape.GetSubShapeIndices()[0]
2215 return self.mesh.GetSubMeshElementType(ShapeID)
2217 ## Gets the mesh description
2218 # @return string value
2219 # @ingroup l1_meshinfo
2221 return self.mesh.Dump()
2224 # Get the information about nodes and elements of a mesh by its IDs:
2225 # -----------------------------------------------------------
2227 ## Gets XYZ coordinates of a node
2228 # \n If there is no nodes for the given ID - returns an empty list
2229 # @return a list of double precision values
2230 # @ingroup l1_meshinfo
2231 def GetNodeXYZ(self, id):
2232 return self.mesh.GetNodeXYZ(id)
2234 ## Returns list of IDs of inverse elements for the given node
2235 # \n If there is no node for the given ID - returns an empty list
2236 # @return a list of integer values
2237 # @ingroup l1_meshinfo
2238 def GetNodeInverseElements(self, id):
2239 return self.mesh.GetNodeInverseElements(id)
2241 ## @brief Returns the position of a node on the shape
2242 # @return SMESH::NodePosition
2243 # @ingroup l1_meshinfo
2244 def GetNodePosition(self,NodeID):
2245 return self.mesh.GetNodePosition(NodeID)
2247 ## @brief Returns the position of an element on the shape
2248 # @return SMESH::ElementPosition
2249 # @ingroup l1_meshinfo
2250 def GetElementPosition(self,ElemID):
2251 return self.mesh.GetElementPosition(ElemID)
2253 ## If the given element is a node, returns the ID of shape
2254 # \n If there is no node for the given ID - returns -1
2255 # @return an integer value
2256 # @ingroup l1_meshinfo
2257 def GetShapeID(self, id):
2258 return self.mesh.GetShapeID(id)
2260 ## Returns the ID of the result shape after
2261 # FindShape() from SMESH_MeshEditor for the given element
2262 # \n If there is no element for the given ID - returns -1
2263 # @return an integer value
2264 # @ingroup l1_meshinfo
2265 def GetShapeIDForElem(self,id):
2266 return self.mesh.GetShapeIDForElem(id)
2268 ## Returns the number of nodes for the given element
2269 # \n If there is no element for the given ID - returns -1
2270 # @return an integer value
2271 # @ingroup l1_meshinfo
2272 def GetElemNbNodes(self, id):
2273 return self.mesh.GetElemNbNodes(id)
2275 ## Returns the node ID the given (zero based) index for the given element
2276 # \n If there is no element for the given ID - returns -1
2277 # \n If there is no node for the given index - returns -2
2278 # @return an integer value
2279 # @ingroup l1_meshinfo
2280 def GetElemNode(self, id, index):
2281 return self.mesh.GetElemNode(id, index)
2283 ## Returns the IDs of nodes of the given element
2284 # @return a list of integer values
2285 # @ingroup l1_meshinfo
2286 def GetElemNodes(self, id):
2287 return self.mesh.GetElemNodes(id)
2289 ## Returns true if the given node is the medium node in the given quadratic element
2290 # @ingroup l1_meshinfo
2291 def IsMediumNode(self, elementID, nodeID):
2292 return self.mesh.IsMediumNode(elementID, nodeID)
2294 ## Returns true if the given node is the medium node in one of quadratic elements
2295 # @ingroup l1_meshinfo
2296 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2297 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2299 ## Returns the number of edges for the given element
2300 # @ingroup l1_meshinfo
2301 def ElemNbEdges(self, id):
2302 return self.mesh.ElemNbEdges(id)
2304 ## Returns the number of faces for the given element
2305 # @ingroup l1_meshinfo
2306 def ElemNbFaces(self, id):
2307 return self.mesh.ElemNbFaces(id)
2309 ## Returns nodes of given face (counted from zero) for given volumic element.
2310 # @ingroup l1_meshinfo
2311 def GetElemFaceNodes(self,elemId, faceIndex):
2312 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2314 ## Returns an element based on all given nodes.
2315 # @ingroup l1_meshinfo
2316 def FindElementByNodes(self,nodes):
2317 return self.mesh.FindElementByNodes(nodes)
2319 ## Returns true if the given element is a polygon
2320 # @ingroup l1_meshinfo
2321 def IsPoly(self, id):
2322 return self.mesh.IsPoly(id)
2324 ## Returns true if the given element is quadratic
2325 # @ingroup l1_meshinfo
2326 def IsQuadratic(self, id):
2327 return self.mesh.IsQuadratic(id)
2329 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2330 # @ingroup l1_meshinfo
2331 def GetBallDiameter(self, id):
2332 return self.mesh.GetBallDiameter(id)
2334 ## Returns XYZ coordinates of the barycenter of the given element
2335 # \n If there is no element for the given ID - returns an empty list
2336 # @return a list of three double values
2337 # @ingroup l1_meshinfo
2338 def BaryCenter(self, id):
2339 return self.mesh.BaryCenter(id)
2341 ## Passes mesh elements through the given filter and return IDs of fitting elements
2342 # @param theFilter SMESH_Filter
2343 # @return a list of ids
2344 # @ingroup l1_controls
2345 def GetIdsFromFilter(self, theFilter):
2346 theFilter.SetMesh( self.mesh )
2347 return theFilter.GetIDs()
2349 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2350 # Returns a list of special structures (borders).
2351 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2352 # @ingroup l1_controls
2353 def GetFreeBorders(self):
2354 aFilterMgr = self.smeshpyD.CreateFilterManager()
2355 aPredicate = aFilterMgr.CreateFreeEdges()
2356 aPredicate.SetMesh(self.mesh)
2357 aBorders = aPredicate.GetBorders()
2358 aFilterMgr.UnRegister()
2362 # Get mesh measurements information:
2363 # ------------------------------------
2365 ## Get minimum distance between two nodes, elements or distance to the origin
2366 # @param id1 first node/element id
2367 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2368 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2369 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2370 # @return minimum distance value
2371 # @sa GetMinDistance()
2372 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2373 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2374 return aMeasure.value
2376 ## Get measure structure specifying minimum distance data between two objects
2377 # @param id1 first node/element id
2378 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2379 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2380 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2381 # @return Measure structure
2383 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2385 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2387 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2390 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2392 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2397 aMeasurements = self.smeshpyD.CreateMeasurements()
2398 aMeasure = aMeasurements.MinDistance(id1, id2)
2399 aMeasurements.UnRegister()
2402 ## Get bounding box of the specified object(s)
2403 # @param objects single source object or list of source objects or list of nodes/elements IDs
2404 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2405 # @c False specifies that @a objects are nodes
2406 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2407 # @sa GetBoundingBox()
2408 def BoundingBox(self, objects=None, isElem=False):
2409 result = self.GetBoundingBox(objects, isElem)
2413 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2416 ## Get measure structure specifying bounding box data of the specified object(s)
2417 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2418 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2419 # @c False specifies that @a objects are nodes
2420 # @return Measure structure
2422 def GetBoundingBox(self, IDs=None, isElem=False):
2425 elif isinstance(IDs, tuple):
2427 if not isinstance(IDs, list):
2429 if len(IDs) > 0 and isinstance(IDs[0], int):
2433 if isinstance(o, Mesh):
2434 srclist.append(o.mesh)
2435 elif hasattr(o, "_narrow"):
2436 src = o._narrow(SMESH.SMESH_IDSource)
2437 if src: srclist.append(src)
2439 elif isinstance(o, list):
2441 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2443 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2446 aMeasurements = self.smeshpyD.CreateMeasurements()
2447 aMeasure = aMeasurements.BoundingBox(srclist)
2448 aMeasurements.UnRegister()
2451 # Mesh edition (SMESH_MeshEditor functionality):
2452 # ---------------------------------------------
2454 ## Removes the elements from the mesh by ids
2455 # @param IDsOfElements is a list of ids of elements to remove
2456 # @return True or False
2457 # @ingroup l2_modif_del
2458 def RemoveElements(self, IDsOfElements):
2459 return self.editor.RemoveElements(IDsOfElements)
2461 ## Removes nodes from mesh by ids
2462 # @param IDsOfNodes is a list of ids of nodes to remove
2463 # @return True or False
2464 # @ingroup l2_modif_del
2465 def RemoveNodes(self, IDsOfNodes):
2466 return self.editor.RemoveNodes(IDsOfNodes)
2468 ## Removes all orphan (free) nodes from mesh
2469 # @return number of the removed nodes
2470 # @ingroup l2_modif_del
2471 def RemoveOrphanNodes(self):
2472 return self.editor.RemoveOrphanNodes()
2474 ## Add a node to the mesh by coordinates
2475 # @return Id of the new node
2476 # @ingroup l2_modif_add
2477 def AddNode(self, x, y, z):
2478 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2479 if hasVars: self.mesh.SetParameters(Parameters)
2480 return self.editor.AddNode( x, y, z)
2482 ## Creates a 0D element on a node with given number.
2483 # @param IDOfNode the ID of node for creation of the element.
2484 # @return the Id of the new 0D element
2485 # @ingroup l2_modif_add
2486 def Add0DElement(self, IDOfNode):
2487 return self.editor.Add0DElement(IDOfNode)
2489 ## Create 0D elements on all nodes of the given elements except those
2490 # nodes on which a 0D element already exists.
2491 # @param theObject an object on whose nodes 0D elements will be created.
2492 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2493 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2494 # @param theGroupName optional name of a group to add 0D elements created
2495 # and/or found on nodes of \a theObject.
2496 # @return an object (a new group or a temporary SMESH_IDSource) holding
2497 # IDs of new and/or found 0D elements. IDs of 0D elements
2498 # can be retrieved from the returned object by calling GetIDs()
2499 # @ingroup l2_modif_add
2500 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2501 if isinstance( theObject, Mesh ):
2502 theObject = theObject.GetMesh()
2503 if isinstance( theObject, list ):
2504 theObject = self.GetIDSource( theObject, SMESH.ALL )
2505 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2507 ## Creates a ball element on a node with given ID.
2508 # @param IDOfNode the ID of node for creation of the element.
2509 # @param diameter the bal diameter.
2510 # @return the Id of the new ball element
2511 # @ingroup l2_modif_add
2512 def AddBall(self, IDOfNode, diameter):
2513 return self.editor.AddBall( IDOfNode, diameter )
2515 ## Creates a linear or quadratic edge (this is determined
2516 # by the number of given nodes).
2517 # @param IDsOfNodes the list of node IDs for creation of the element.
2518 # The order of nodes in this list should correspond to the description
2519 # of MED. \n This description is located by the following link:
2520 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2521 # @return the Id of the new edge
2522 # @ingroup l2_modif_add
2523 def AddEdge(self, IDsOfNodes):
2524 return self.editor.AddEdge(IDsOfNodes)
2526 ## Creates a linear or quadratic face (this is determined
2527 # by the number of given nodes).
2528 # @param IDsOfNodes the list of node IDs for creation of the element.
2529 # The order of nodes in this list should correspond to the description
2530 # of MED. \n This description is located by the following link:
2531 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2532 # @return the Id of the new face
2533 # @ingroup l2_modif_add
2534 def AddFace(self, IDsOfNodes):
2535 return self.editor.AddFace(IDsOfNodes)
2537 ## Adds a polygonal face to the mesh by the list of node IDs
2538 # @param IdsOfNodes the list of node IDs for creation of the element.
2539 # @return the Id of the new face
2540 # @ingroup l2_modif_add
2541 def AddPolygonalFace(self, IdsOfNodes):
2542 return self.editor.AddPolygonalFace(IdsOfNodes)
2544 ## Creates both simple and quadratic volume (this is determined
2545 # by the number of given nodes).
2546 # @param IDsOfNodes the list of node IDs for creation of the element.
2547 # The order of nodes in this list should correspond to the description
2548 # of MED. \n This description is located by the following link:
2549 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2550 # @return the Id of the new volumic element
2551 # @ingroup l2_modif_add
2552 def AddVolume(self, IDsOfNodes):
2553 return self.editor.AddVolume(IDsOfNodes)
2555 ## Creates a volume of many faces, giving nodes for each face.
2556 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2557 # @param Quantities the list of integer values, Quantities[i]
2558 # gives the quantity of nodes in face number i.
2559 # @return the Id of the new volumic element
2560 # @ingroup l2_modif_add
2561 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2562 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2564 ## Creates a volume of many faces, giving the IDs of the existing faces.
2565 # @param IdsOfFaces the list of face IDs for volume creation.
2567 # Note: The created volume will refer only to the nodes
2568 # of the given faces, not to the faces themselves.
2569 # @return the Id of the new volumic element
2570 # @ingroup l2_modif_add
2571 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2572 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2575 ## @brief Binds a node to a vertex
2576 # @param NodeID a node ID
2577 # @param Vertex a vertex or vertex ID
2578 # @return True if succeed else raises an exception
2579 # @ingroup l2_modif_add
2580 def SetNodeOnVertex(self, NodeID, Vertex):
2581 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2582 VertexID = Vertex.GetSubShapeIndices()[0]
2586 self.editor.SetNodeOnVertex(NodeID, VertexID)
2587 except SALOME.SALOME_Exception, inst:
2588 raise ValueError, inst.details.text
2592 ## @brief Stores the node position on an edge
2593 # @param NodeID a node ID
2594 # @param Edge an edge or edge ID
2595 # @param paramOnEdge a parameter on the edge where the node is located
2596 # @return True if succeed else raises an exception
2597 # @ingroup l2_modif_add
2598 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2599 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2600 EdgeID = Edge.GetSubShapeIndices()[0]
2604 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2605 except SALOME.SALOME_Exception, inst:
2606 raise ValueError, inst.details.text
2609 ## @brief Stores node position on a face
2610 # @param NodeID a node ID
2611 # @param Face a face or face ID
2612 # @param u U parameter on the face where the node is located
2613 # @param v V parameter on the face where the node is located
2614 # @return True if succeed else raises an exception
2615 # @ingroup l2_modif_add
2616 def SetNodeOnFace(self, NodeID, Face, u, v):
2617 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2618 FaceID = Face.GetSubShapeIndices()[0]
2622 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2623 except SALOME.SALOME_Exception, inst:
2624 raise ValueError, inst.details.text
2627 ## @brief Binds a node to a solid
2628 # @param NodeID a node ID
2629 # @param Solid a solid or solid ID
2630 # @return True if succeed else raises an exception
2631 # @ingroup l2_modif_add
2632 def SetNodeInVolume(self, NodeID, Solid):
2633 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2634 SolidID = Solid.GetSubShapeIndices()[0]
2638 self.editor.SetNodeInVolume(NodeID, SolidID)
2639 except SALOME.SALOME_Exception, inst:
2640 raise ValueError, inst.details.text
2643 ## @brief Bind an element to a shape
2644 # @param ElementID an element ID
2645 # @param Shape a shape or shape ID
2646 # @return True if succeed else raises an exception
2647 # @ingroup l2_modif_add
2648 def SetMeshElementOnShape(self, ElementID, Shape):
2649 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2650 ShapeID = Shape.GetSubShapeIndices()[0]
2654 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2655 except SALOME.SALOME_Exception, inst:
2656 raise ValueError, inst.details.text
2660 ## Moves the node with the given id
2661 # @param NodeID the id of the node
2662 # @param x a new X coordinate
2663 # @param y a new Y coordinate
2664 # @param z a new Z coordinate
2665 # @return True if succeed else False
2666 # @ingroup l2_modif_movenode
2667 def MoveNode(self, NodeID, x, y, z):
2668 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2669 if hasVars: self.mesh.SetParameters(Parameters)
2670 return self.editor.MoveNode(NodeID, x, y, z)
2672 ## Finds the node closest to a point and moves it to a point location
2673 # @param x the X coordinate of a point
2674 # @param y the Y coordinate of a point
2675 # @param z the Z coordinate of a point
2676 # @param NodeID if specified (>0), the node with this ID is moved,
2677 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2678 # @return the ID of a node
2679 # @ingroup l2_modif_throughp
2680 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2681 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2682 if hasVars: self.mesh.SetParameters(Parameters)
2683 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2685 ## Finds the node closest to a point
2686 # @param x the X coordinate of a point
2687 # @param y the Y coordinate of a point
2688 # @param z the Z coordinate of a point
2689 # @return the ID of a node
2690 # @ingroup l2_modif_throughp
2691 def FindNodeClosestTo(self, x, y, z):
2692 #preview = self.mesh.GetMeshEditPreviewer()
2693 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2694 return self.editor.FindNodeClosestTo(x, y, z)
2696 ## Finds the elements where a point lays IN or ON
2697 # @param x the X coordinate of a point
2698 # @param y the Y coordinate of a point
2699 # @param z the Z coordinate of a point
2700 # @param elementType type of elements to find (SMESH.ALL type
2701 # means elements of any type excluding nodes, discrete and 0D elements)
2702 # @param meshPart a part of mesh (group, sub-mesh) to search within
2703 # @return list of IDs of found elements
2704 # @ingroup l2_modif_throughp
2705 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2707 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2709 return self.editor.FindElementsByPoint(x, y, z, elementType)
2711 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2712 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2713 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2715 def GetPointState(self, x, y, z):
2716 return self.editor.GetPointState(x, y, z)
2718 ## Finds the node closest to a point and moves it to a point location
2719 # @param x the X coordinate of a point
2720 # @param y the Y coordinate of a point
2721 # @param z the Z coordinate of a point
2722 # @return the ID of a moved node
2723 # @ingroup l2_modif_throughp
2724 def MeshToPassThroughAPoint(self, x, y, z):
2725 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2727 ## Replaces two neighbour triangles sharing Node1-Node2 link
2728 # with the triangles built on the same 4 nodes but having other common link.
2729 # @param NodeID1 the ID of the first node
2730 # @param NodeID2 the ID of the second node
2731 # @return false if proper faces were not found
2732 # @ingroup l2_modif_invdiag
2733 def InverseDiag(self, NodeID1, NodeID2):
2734 return self.editor.InverseDiag(NodeID1, NodeID2)
2736 ## Replaces two neighbour triangles sharing Node1-Node2 link
2737 # with a quadrangle built on the same 4 nodes.
2738 # @param NodeID1 the ID of the first node
2739 # @param NodeID2 the ID of the second node
2740 # @return false if proper faces were not found
2741 # @ingroup l2_modif_unitetri
2742 def DeleteDiag(self, NodeID1, NodeID2):
2743 return self.editor.DeleteDiag(NodeID1, NodeID2)
2745 ## Reorients elements by ids
2746 # @param IDsOfElements if undefined reorients all mesh elements
2747 # @return True if succeed else False
2748 # @ingroup l2_modif_changori
2749 def Reorient(self, IDsOfElements=None):
2750 if IDsOfElements == None:
2751 IDsOfElements = self.GetElementsId()
2752 return self.editor.Reorient(IDsOfElements)
2754 ## Reorients all elements of the object
2755 # @param theObject mesh, submesh or group
2756 # @return True if succeed else False
2757 # @ingroup l2_modif_changori
2758 def ReorientObject(self, theObject):
2759 if ( isinstance( theObject, Mesh )):
2760 theObject = theObject.GetMesh()
2761 return self.editor.ReorientObject(theObject)
2763 ## Reorient faces contained in \a the2DObject.
2764 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2765 # @param theDirection is a desired direction of normal of \a theFace.
2766 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2767 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2768 # compared with theDirection. It can be either ID of face or a point
2769 # by which the face will be found. The point can be given as either
2770 # a GEOM vertex or a list of point coordinates.
2771 # @return number of reoriented faces
2772 # @ingroup l2_modif_changori
2773 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2775 if isinstance( the2DObject, Mesh ):
2776 the2DObject = the2DObject.GetMesh()
2777 if isinstance( the2DObject, list ):
2778 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2779 # check theDirection
2780 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2781 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2782 if isinstance( theDirection, list ):
2783 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2784 # prepare theFace and thePoint
2785 theFace = theFaceOrPoint
2786 thePoint = PointStruct(0,0,0)
2787 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2788 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2790 if isinstance( theFaceOrPoint, list ):
2791 thePoint = PointStruct( *theFaceOrPoint )
2793 if isinstance( theFaceOrPoint, PointStruct ):
2794 thePoint = theFaceOrPoint
2796 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2798 ## Fuses the neighbouring triangles into quadrangles.
2799 # @param IDsOfElements The triangles to be fused,
2800 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2801 # choose a neighbour to fuse with.
2802 # @param MaxAngle is the maximum angle between element normals at which the fusion
2803 # is still performed; theMaxAngle is mesured in radians.
2804 # Also it could be a name of variable which defines angle in degrees.
2805 # @return TRUE in case of success, FALSE otherwise.
2806 # @ingroup l2_modif_unitetri
2807 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2808 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2809 self.mesh.SetParameters(Parameters)
2810 if not IDsOfElements:
2811 IDsOfElements = self.GetElementsId()
2812 Functor = self.smeshpyD.GetFunctor(theCriterion)
2813 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2815 ## Fuses the neighbouring triangles of the object into quadrangles
2816 # @param theObject is mesh, submesh or group
2817 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2818 # choose a neighbour to fuse with.
2819 # @param MaxAngle a max angle between element normals at which the fusion
2820 # is still performed; theMaxAngle is mesured in radians.
2821 # @return TRUE in case of success, FALSE otherwise.
2822 # @ingroup l2_modif_unitetri
2823 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2824 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2825 self.mesh.SetParameters(Parameters)
2826 if isinstance( theObject, Mesh ):
2827 theObject = theObject.GetMesh()
2828 Functor = self.smeshpyD.GetFunctor(theCriterion)
2829 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2831 ## Splits quadrangles into triangles.
2833 # @param IDsOfElements the faces to be splitted.
2834 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2835 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2836 # value, then quadrangles will be split by the smallest diagonal.
2837 # @return TRUE in case of success, FALSE otherwise.
2838 # @ingroup l2_modif_cutquadr
2839 def QuadToTri (self, IDsOfElements, theCriterion = None):
2840 if IDsOfElements == []:
2841 IDsOfElements = self.GetElementsId()
2842 if theCriterion is None:
2843 theCriterion = FT_MaxElementLength2D
2844 Functor = self.smeshpyD.GetFunctor(theCriterion)
2845 return self.editor.QuadToTri(IDsOfElements, Functor)
2847 ## Splits quadrangles into triangles.
2848 # @param theObject the object from which the list of elements is taken,
2849 # this is mesh, submesh or group
2850 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2851 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2852 # value, then quadrangles will be split by the smallest diagonal.
2853 # @return TRUE in case of success, FALSE otherwise.
2854 # @ingroup l2_modif_cutquadr
2855 def QuadToTriObject (self, theObject, theCriterion = None):
2856 if ( isinstance( theObject, Mesh )):
2857 theObject = theObject.GetMesh()
2858 if theCriterion is None:
2859 theCriterion = FT_MaxElementLength2D
2860 Functor = self.smeshpyD.GetFunctor(theCriterion)
2861 return self.editor.QuadToTriObject(theObject, Functor)
2863 ## Splits quadrangles into triangles.
2864 # @param IDsOfElements the faces to be splitted
2865 # @param Diag13 is used to choose a diagonal for splitting.
2866 # @return TRUE in case of success, FALSE otherwise.
2867 # @ingroup l2_modif_cutquadr
2868 def SplitQuad (self, IDsOfElements, Diag13):
2869 if IDsOfElements == []:
2870 IDsOfElements = self.GetElementsId()
2871 return self.editor.SplitQuad(IDsOfElements, Diag13)
2873 ## Splits quadrangles into triangles.
2874 # @param theObject the object from which the list of elements is taken,
2875 # this is mesh, submesh or group
2876 # @param Diag13 is used to choose a diagonal for splitting.
2877 # @return TRUE in case of success, FALSE otherwise.
2878 # @ingroup l2_modif_cutquadr
2879 def SplitQuadObject (self, theObject, Diag13):
2880 if ( isinstance( theObject, Mesh )):
2881 theObject = theObject.GetMesh()
2882 return self.editor.SplitQuadObject(theObject, Diag13)
2884 ## Finds a better splitting of the given quadrangle.
2885 # @param IDOfQuad the ID of the quadrangle to be splitted.
2886 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2887 # choose a diagonal for splitting.
2888 # @return 1 if 1-3 diagonal is better, 2 if 2-4
2889 # diagonal is better, 0 if error occurs.
2890 # @ingroup l2_modif_cutquadr
2891 def BestSplit (self, IDOfQuad, theCriterion):
2892 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
2894 ## Splits volumic elements into tetrahedrons
2895 # @param elemIDs either list of elements or mesh or group or submesh
2896 # @param method flags passing splitting method: Hex_5Tet, Hex_6Tet, Hex_24Tet
2897 # Hex_5Tet - split the hexahedron into 5 tetrahedrons, etc
2898 # @ingroup l2_modif_cutquadr
2899 def SplitVolumesIntoTetra(self, elemIDs, method=smeshBuilder.Hex_5Tet ):
2900 if isinstance( elemIDs, Mesh ):
2901 elemIDs = elemIDs.GetMesh()
2902 if ( isinstance( elemIDs, list )):
2903 elemIDs = self.editor.MakeIDSource(elemIDs, SMESH.VOLUME)
2904 self.editor.SplitVolumesIntoTetra(elemIDs, method)
2906 ## Splits quadrangle faces near triangular facets of volumes
2908 # @ingroup l1_auxiliary
2909 def SplitQuadsNearTriangularFacets(self):
2910 faces_array = self.GetElementsByType(SMESH.FACE)
2911 for face_id in faces_array:
2912 if self.GetElemNbNodes(face_id) == 4: # quadrangle
2913 quad_nodes = self.mesh.GetElemNodes(face_id)
2914 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2915 isVolumeFound = False