1 # Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
30 ## @defgroup l2_construct Constructing meshes
31 ## @defgroup l2_algorithms Defining Algorithms
33 ## @defgroup l3_algos_basic Basic meshing algorithms
34 ## @defgroup l3_algos_proj Projection Algorithms
35 ## @defgroup l3_algos_radialp Radial Prism
36 ## @defgroup l3_algos_segmarv Segments around Vertex
37 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
40 ## @defgroup l2_hypotheses Defining hypotheses
42 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ## @defgroup l3_hypos_additi Additional Hypotheses
49 ## @defgroup l2_submeshes Constructing submeshes
50 ## @defgroup l2_compounds Building Compounds
51 ## @defgroup l2_editing Editing Meshes
54 ## @defgroup l1_meshinfo Mesh Information
55 ## @defgroup l1_controls Quality controls and Filtering
56 ## @defgroup l1_grouping Grouping elements
58 ## @defgroup l2_grps_create Creating groups
59 ## @defgroup l2_grps_edit Editing groups
60 ## @defgroup l2_grps_operon Using operations on groups
61 ## @defgroup l2_grps_delete Deleting Groups
64 ## @defgroup l1_modifying Modifying meshes
66 ## @defgroup l2_modif_add Adding nodes and elements
67 ## @defgroup l2_modif_del Removing nodes and elements
68 ## @defgroup l2_modif_edit Modifying nodes and elements
69 ## @defgroup l2_modif_renumber Renumbering nodes and elements
70 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ## @defgroup l2_modif_movenode Moving nodes
72 ## @defgroup l2_modif_throughp Mesh through point
73 ## @defgroup l2_modif_invdiag Diagonal inversion of elements
74 ## @defgroup l2_modif_unitetri Uniting triangles
75 ## @defgroup l2_modif_changori Changing orientation of elements
76 ## @defgroup l2_modif_cutquadr Cutting elements
77 ## @defgroup l2_modif_smooth Smoothing
78 ## @defgroup l2_modif_extrurev Extrusion and Revolution
79 ## @defgroup l2_modif_patterns Pattern mapping
80 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
83 ## @defgroup l1_measurements Measurements
86 from salome.geom import geomBuilder
88 import SMESH # This is necessary for back compatibility
90 from salome.smesh.smesh_algorithm import Mesh_Algorithm
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
102 def __subclasscheck__(cls, sub):
103 """Implement issubclass(sub, cls)."""
104 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
106 ## @addtogroup l1_auxiliary
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
119 ## Return list of variable values from salome notebook.
120 # The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
132 if isinstance(parameter,str):
133 # check if there is an inexistent variable name
134 if not notebook.isVariable(parameter):
135 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136 parameter = notebook.get(parameter)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
154 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
159 SMESH.PointStruct.__init__ = __initPointStruct
161 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
164 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
166 SMESH.AxisStruct.__init__ = __initAxisStruct
168 smeshPrecisionConfusion = 1.e-07
169 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
170 if abs(val1 - val2) < tol:
180 if isinstance(obj, SALOMEDS._objref_SObject):
184 ior = salome.orb.object_to_string(obj)
189 studies = salome.myStudyManager.GetOpenStudies()
190 for sname in studies:
191 s = salome.myStudyManager.GetStudyByName(sname)
193 sobj = s.FindObjectIOR(ior)
194 if not sobj: continue
195 return sobj.GetName()
196 if hasattr(obj, "GetName"):
197 # unknown CORBA object, having GetName() method
200 # unknown CORBA object, no GetName() method
203 if hasattr(obj, "GetName"):
204 # unknown non-CORBA object, having GetName() method
207 raise RuntimeError, "Null or invalid object"
209 ## Prints error message if a hypothesis was not assigned.
210 def TreatHypoStatus(status, hypName, geomName, isAlgo):
212 hypType = "algorithm"
214 hypType = "hypothesis"
216 if status == HYP_UNKNOWN_FATAL :
217 reason = "for unknown reason"
218 elif status == HYP_INCOMPATIBLE :
219 reason = "this hypothesis mismatches the algorithm"
220 elif status == HYP_NOTCONFORM :
221 reason = "a non-conform mesh would be built"
222 elif status == HYP_ALREADY_EXIST :
223 if isAlgo: return # it does not influence anything
224 reason = hypType + " of the same dimension is already assigned to this shape"
225 elif status == HYP_BAD_DIM :
226 reason = hypType + " mismatches the shape"
227 elif status == HYP_CONCURENT :
228 reason = "there are concurrent hypotheses on sub-shapes"
229 elif status == HYP_BAD_SUBSHAPE :
230 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
231 elif status == HYP_BAD_GEOMETRY:
232 reason = "geometry mismatches the expectation of the algorithm"
233 elif status == HYP_HIDDEN_ALGO:
234 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
235 elif status == HYP_HIDING_ALGO:
236 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
237 elif status == HYP_NEED_SHAPE:
238 reason = "Algorithm can't work without shape"
241 hypName = '"' + hypName + '"'
242 geomName= '"' + geomName+ '"'
243 if status < HYP_UNKNOWN_FATAL and not geomName =='""':
244 print hypName, "was assigned to", geomName,"but", reason
245 elif not geomName == '""':
246 print hypName, "was not assigned to",geomName,":", reason
248 print hypName, "was not assigned:", reason
251 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
252 def AssureGeomPublished(mesh, geom, name=''):
253 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
255 if not geom.GetStudyEntry() and \
256 mesh.smeshpyD.GetCurrentStudy():
258 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
259 if studyID != mesh.geompyD.myStudyId:
260 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
262 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
263 # for all groups SubShapeName() returns "Compound_-1"
264 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
266 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
268 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
271 ## Return the first vertex of a geometrical edge by ignoring orientation
272 def FirstVertexOnCurve(mesh, edge):
273 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
275 raise TypeError, "Given object has no vertices"
276 if len( vv ) == 1: return vv[0]
277 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
278 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
279 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
280 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
283 dist1 += abs( xyz[i] - xyz1[i] )
284 dist2 += abs( xyz[i] - xyz2[i] )
290 # end of l1_auxiliary
294 # Warning: smeshInst is a singleton
300 ## This class allows to create, load or manipulate meshes
301 # It has a set of methods to create load or copy meshes, to combine several meshes.
302 # It also has methods to get infos on meshes.
303 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
305 # MirrorType enumeration
306 POINT = SMESH_MeshEditor.POINT
307 AXIS = SMESH_MeshEditor.AXIS
308 PLANE = SMESH_MeshEditor.PLANE
310 # Smooth_Method enumeration
311 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
312 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
314 PrecisionConfusion = smeshPrecisionConfusion
316 # TopAbs_State enumeration
317 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
319 # Methods of splitting a hexahedron into tetrahedra
320 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
326 #print "==== __new__", engine, smeshInst, doLcc
328 if smeshInst is None:
329 # smesh engine is either retrieved from engine, or created
331 # Following test avoids a recursive loop
333 if smeshInst is not None:
334 # smesh engine not created: existing engine found
338 # FindOrLoadComponent called:
339 # 1. CORBA resolution of server
340 # 2. the __new__ method is called again
341 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
342 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
344 # FindOrLoadComponent not called
345 if smeshInst is None:
346 # smeshBuilder instance is created from lcc.FindOrLoadComponent
347 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
348 smeshInst = super(smeshBuilder,cls).__new__(cls)
350 # smesh engine not created: existing engine found
351 #print "==== existing ", engine, smeshInst, doLcc
353 #print "====1 ", smeshInst
356 #print "====2 ", smeshInst
361 #print "--------------- smeshbuilder __init__ ---", created
364 SMESH._objref_SMESH_Gen.__init__(self)
366 ## Dump component to the Python script
367 # This method overrides IDL function to allow default values for the parameters.
368 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
369 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
371 ## Set mode of DumpPython(), \a historical or \a snapshot.
372 # In the \a historical mode, the Python Dump script includes all commands
373 # performed by SMESH engine. In the \a snapshot mode, commands
374 # relating to objects removed from the Study are excluded from the script
375 # as well as commands not influencing the current state of meshes
376 def SetDumpPythonHistorical(self, isHistorical):
377 if isHistorical: val = "true"
379 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
381 ## Sets the current study and Geometry component
382 # @ingroup l1_auxiliary
383 def init_smesh(self,theStudy,geompyD = None):
385 self.SetCurrentStudy(theStudy,geompyD)
387 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
388 # or a mesh wrapping a CORBA mesh given as a parameter.
389 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
390 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
391 # (2) a Geometrical object for meshing or
393 # @param name the name for the new mesh.
394 # @return an instance of Mesh class.
395 # @ingroup l2_construct
396 def Mesh(self, obj=0, name=0):
397 if isinstance(obj,str):
399 return Mesh(self,self.geompyD,obj,name)
401 ## Returns a long value from enumeration
402 # @ingroup l1_controls
403 def EnumToLong(self,theItem):
406 ## Returns a string representation of the color.
407 # To be used with filters.
408 # @param c color value (SALOMEDS.Color)
409 # @ingroup l1_controls
410 def ColorToString(self,c):
412 if isinstance(c, SALOMEDS.Color):
413 val = "%s;%s;%s" % (c.R, c.G, c.B)
414 elif isinstance(c, str):
417 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
420 ## Gets PointStruct from vertex
421 # @param theVertex a GEOM object(vertex)
422 # @return SMESH.PointStruct
423 # @ingroup l1_auxiliary
424 def GetPointStruct(self,theVertex):
425 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
426 return PointStruct(x,y,z)
428 ## Gets DirStruct from vector
429 # @param theVector a GEOM object(vector)
430 # @return SMESH.DirStruct
431 # @ingroup l1_auxiliary
432 def GetDirStruct(self,theVector):
433 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
434 if(len(vertices) != 2):
435 print "Error: vector object is incorrect."
437 p1 = self.geompyD.PointCoordinates(vertices[0])
438 p2 = self.geompyD.PointCoordinates(vertices[1])
439 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
440 dirst = DirStruct(pnt)
443 ## Makes DirStruct from a triplet
444 # @param x,y,z vector components
445 # @return SMESH.DirStruct
446 # @ingroup l1_auxiliary
447 def MakeDirStruct(self,x,y,z):
448 pnt = PointStruct(x,y,z)
449 return DirStruct(pnt)
451 ## Get AxisStruct from object
452 # @param theObj a GEOM object (line or plane)
453 # @return SMESH.AxisStruct
454 # @ingroup l1_auxiliary
455 def GetAxisStruct(self,theObj):
456 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
458 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
459 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
460 vertex1 = self.geompyD.PointCoordinates(vertex1)
461 vertex2 = self.geompyD.PointCoordinates(vertex2)
462 vertex3 = self.geompyD.PointCoordinates(vertex3)
463 vertex4 = self.geompyD.PointCoordinates(vertex4)
464 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
465 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
466 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] ]
467 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
469 elif len(edges) == 1:
470 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
471 p1 = self.geompyD.PointCoordinates( vertex1 )
472 p2 = self.geompyD.PointCoordinates( vertex2 )
473 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
477 # From SMESH_Gen interface:
478 # ------------------------
480 ## Sets the given name to the object
481 # @param obj the object to rename
482 # @param name a new object name
483 # @ingroup l1_auxiliary
484 def SetName(self, obj, name):
485 if isinstance( obj, Mesh ):
487 elif isinstance( obj, Mesh_Algorithm ):
488 obj = obj.GetAlgorithm()
489 ior = salome.orb.object_to_string(obj)
490 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
492 ## Sets the current mode
493 # @ingroup l1_auxiliary
494 def SetEmbeddedMode( self,theMode ):
495 #self.SetEmbeddedMode(theMode)
496 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
498 ## Gets the current mode
499 # @ingroup l1_auxiliary
500 def IsEmbeddedMode(self):
501 #return self.IsEmbeddedMode()
502 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
504 ## Sets the current study
505 # @ingroup l1_auxiliary
506 def SetCurrentStudy( self, theStudy, geompyD = None ):
507 #self.SetCurrentStudy(theStudy)
509 from salome.geom import geomBuilder
510 geompyD = geomBuilder.geom
513 self.SetGeomEngine(geompyD)
514 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
517 notebook = salome_notebook.NoteBook( theStudy )
519 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
521 ## Gets the current study
522 # @ingroup l1_auxiliary
523 def GetCurrentStudy(self):
524 #return self.GetCurrentStudy()
525 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
527 ## Creates a Mesh object importing data from the given UNV file
528 # @return an instance of Mesh class
530 def CreateMeshesFromUNV( self,theFileName ):
531 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
532 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
535 ## Creates a Mesh object(s) importing data from the given MED file
536 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
538 def CreateMeshesFromMED( self,theFileName ):
539 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
540 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
541 return aMeshes, aStatus
543 ## Creates a Mesh object(s) importing data from the given SAUV file
544 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
546 def CreateMeshesFromSAUV( self,theFileName ):
547 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
548 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
549 return aMeshes, aStatus
551 ## Creates a Mesh object importing data from the given STL file
552 # @return an instance of Mesh class
554 def CreateMeshesFromSTL( self, theFileName ):
555 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
556 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
559 ## Creates Mesh objects importing data from the given CGNS file
560 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
562 def CreateMeshesFromCGNS( self, theFileName ):
563 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
564 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
565 return aMeshes, aStatus
567 ## Creates a Mesh object importing data from the given GMF file.
568 # GMF files must have .mesh extension for the ASCII format and .meshb for
570 # @return [ an instance of Mesh class, SMESH.ComputeError ]
572 def CreateMeshesFromGMF( self, theFileName ):
573 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
576 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
577 return Mesh(self, self.geompyD, aSmeshMesh), error
579 ## Concatenate the given meshes into one mesh.
580 # @return an instance of Mesh class
581 # @param meshes the meshes to combine into one mesh
582 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
583 # @param mergeNodesAndElements if true, equal nodes and elements aremerged
584 # @param mergeTolerance tolerance for merging nodes
585 # @param allGroups forces creation of groups of all elements
586 # @param name name of a new mesh
587 def Concatenate( self, meshes, uniteIdenticalGroups,
588 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
590 if not meshes: return None
591 for i,m in enumerate(meshes):
592 if isinstance(m, Mesh):
593 meshes[i] = m.GetMesh()
594 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
595 meshes[0].SetParameters(Parameters)
597 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
598 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
600 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
601 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
602 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
605 ## Create a mesh by copying a part of another mesh.
606 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
607 # to copy nodes or elements not contained in any mesh object,
608 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
609 # @param meshName a name of the new mesh
610 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
611 # @param toKeepIDs to preserve IDs of the copied elements or not
612 # @return an instance of Mesh class
613 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
614 if (isinstance( meshPart, Mesh )):
615 meshPart = meshPart.GetMesh()
616 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
617 return Mesh(self, self.geompyD, mesh)
619 ## From SMESH_Gen interface
620 # @return the list of integer values
621 # @ingroup l1_auxiliary
622 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
623 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
625 ## From SMESH_Gen interface. Creates a pattern
626 # @return an instance of SMESH_Pattern
628 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
629 # @ingroup l2_modif_patterns
630 def GetPattern(self):
631 return SMESH._objref_SMESH_Gen.GetPattern(self)
633 ## Sets number of segments per diagonal of boundary box of geometry by which
634 # default segment length of appropriate 1D hypotheses is defined.
635 # Default value is 10
636 # @ingroup l1_auxiliary
637 def SetBoundaryBoxSegmentation(self, nbSegments):
638 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
640 # Filtering. Auxiliary functions:
641 # ------------------------------
643 ## Creates an empty criterion
644 # @return SMESH.Filter.Criterion
645 # @ingroup l1_controls
646 def GetEmptyCriterion(self):
647 Type = self.EnumToLong(FT_Undefined)
648 Compare = self.EnumToLong(FT_Undefined)
652 UnaryOp = self.EnumToLong(FT_Undefined)
653 BinaryOp = self.EnumToLong(FT_Undefined)
656 Precision = -1 ##@1e-07
657 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
658 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
660 ## Creates a criterion by the given parameters
661 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
662 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
663 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
664 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
665 # @param Threshold the threshold value (range of ids as string, shape, numeric)
666 # @param UnaryOp FT_LogicalNOT or FT_Undefined
667 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
668 # FT_Undefined (must be for the last criterion of all criteria)
669 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
670 # FT_LyingOnGeom, FT_CoplanarFaces criteria
671 # @return SMESH.Filter.Criterion
673 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
674 # @ingroup l1_controls
675 def GetCriterion(self,elementType,
677 Compare = FT_EqualTo,
679 UnaryOp=FT_Undefined,
680 BinaryOp=FT_Undefined,
682 if not CritType in SMESH.FunctorType._items:
683 raise TypeError, "CritType should be of SMESH.FunctorType"
684 aCriterion = self.GetEmptyCriterion()
685 aCriterion.TypeOfElement = elementType
686 aCriterion.Type = self.EnumToLong(CritType)
687 aCriterion.Tolerance = Tolerance
689 aThreshold = Threshold
691 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
692 aCriterion.Compare = self.EnumToLong(Compare)
693 elif Compare == "=" or Compare == "==":
694 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
696 aCriterion.Compare = self.EnumToLong(FT_LessThan)
698 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
699 elif Compare != FT_Undefined:
700 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
703 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
704 FT_BelongToCylinder, FT_LyingOnGeom]:
705 # Checks that Threshold is GEOM object
706 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
707 aCriterion.ThresholdStr = GetName(aThreshold)
708 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
709 if not aCriterion.ThresholdID:
710 name = aCriterion.ThresholdStr
712 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
713 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
714 #raise RuntimeError, "Threshold shape must be published"
716 print "Error: The Threshold should be a shape."
718 if isinstance(UnaryOp,float):
719 aCriterion.Tolerance = UnaryOp
720 UnaryOp = FT_Undefined
722 elif CritType == FT_RangeOfIds:
723 # Checks that Threshold is string
724 if isinstance(aThreshold, str):
725 aCriterion.ThresholdStr = aThreshold
727 print "Error: The Threshold should be a string."
729 elif CritType == FT_CoplanarFaces:
730 # Checks the Threshold
731 if isinstance(aThreshold, int):
732 aCriterion.ThresholdID = str(aThreshold)
733 elif isinstance(aThreshold, str):
736 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
737 aCriterion.ThresholdID = aThreshold
740 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
741 elif CritType == FT_ConnectedElements:
742 # Checks the Threshold
743 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
744 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
745 if not aCriterion.ThresholdID:
746 name = aThreshold.GetName()
748 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
749 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
750 elif isinstance(aThreshold, int): # node id
751 aCriterion.Threshold = aThreshold
752 elif isinstance(aThreshold, list): # 3 point coordinates
753 if len( aThreshold ) < 3:
754 raise ValueError, "too few point coordinates, must be 3"
755 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
756 elif isinstance(aThreshold, str):
757 if aThreshold.isdigit():
758 aCriterion.Threshold = aThreshold # node id
760 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
763 "The Threshold should either a VERTEX, or a node ID, "\
764 "or a list of point coordinates and not '%s'"%aThreshold
765 elif CritType == FT_ElemGeomType:
766 # Checks the Threshold
768 aCriterion.Threshold = self.EnumToLong(aThreshold)
769 assert( aThreshold in SMESH.GeometryType._items )
771 if isinstance(aThreshold, int):
772 aCriterion.Threshold = aThreshold
774 print "Error: The Threshold should be an integer or SMESH.GeometryType."
778 elif CritType == FT_EntityType:
779 # Checks the Threshold
781 aCriterion.Threshold = self.EnumToLong(aThreshold)
782 assert( aThreshold in SMESH.EntityType._items )
784 if isinstance(aThreshold, int):
785 aCriterion.Threshold = aThreshold
787 print "Error: The Threshold should be an integer or SMESH.EntityType."
792 elif CritType == FT_GroupColor:
793 # Checks the Threshold
795 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
797 print "Error: The threshold value should be of SALOMEDS.Color type"
800 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
801 FT_LinearOrQuadratic, FT_BadOrientedVolume,
802 FT_BareBorderFace, FT_BareBorderVolume,
803 FT_OverConstrainedFace, FT_OverConstrainedVolume,
804 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
805 # At this point the Threshold is unnecessary
806 if aThreshold == FT_LogicalNOT:
807 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
808 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
809 aCriterion.BinaryOp = aThreshold
813 aThreshold = float(aThreshold)
814 aCriterion.Threshold = aThreshold
816 print "Error: The Threshold should be a number."
819 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
820 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
822 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
823 aCriterion.BinaryOp = self.EnumToLong(Threshold)
825 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
826 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
828 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
829 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
833 ## Creates a filter with the given parameters
834 # @param elementType the type of elements in the group
835 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
836 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
837 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
838 # @param UnaryOp FT_LogicalNOT or FT_Undefined
839 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
840 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
841 # @param mesh the mesh to initialize the filter with
842 # @return SMESH_Filter
844 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
845 # @ingroup l1_controls
846 def GetFilter(self,elementType,
847 CritType=FT_Undefined,
850 UnaryOp=FT_Undefined,
853 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
854 aFilterMgr = self.CreateFilterManager()
855 aFilter = aFilterMgr.CreateFilter()
857 aCriteria.append(aCriterion)
858 aFilter.SetCriteria(aCriteria)
860 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
861 else : aFilter.SetMesh( mesh )
862 aFilterMgr.UnRegister()
865 ## Creates a filter from criteria
866 # @param criteria a list of criteria
867 # @param binOp binary operator used when binary operator of criteria is undefined
868 # @return SMESH_Filter
870 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
871 # @ingroup l1_controls
872 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
873 for i in range( len( criteria ) - 1 ):
874 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
875 criteria[i].BinaryOp = self.EnumToLong( binOp )
876 aFilterMgr = self.CreateFilterManager()
877 aFilter = aFilterMgr.CreateFilter()
878 aFilter.SetCriteria(criteria)
879 aFilterMgr.UnRegister()
882 ## Creates a numerical functor by its type
883 # @param theCriterion FT_...; functor type
884 # @return SMESH_NumericalFunctor
885 # @ingroup l1_controls
886 def GetFunctor(self,theCriterion):
887 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
889 aFilterMgr = self.CreateFilterManager()
891 if theCriterion == FT_AspectRatio:
892 functor = aFilterMgr.CreateAspectRatio()
893 elif theCriterion == FT_AspectRatio3D:
894 functor = aFilterMgr.CreateAspectRatio3D()
895 elif theCriterion == FT_Warping:
896 functor = aFilterMgr.CreateWarping()
897 elif theCriterion == FT_MinimumAngle:
898 functor = aFilterMgr.CreateMinimumAngle()
899 elif theCriterion == FT_Taper:
900 functor = aFilterMgr.CreateTaper()
901 elif theCriterion == FT_Skew:
902 functor = aFilterMgr.CreateSkew()
903 elif theCriterion == FT_Area:
904 functor = aFilterMgr.CreateArea()
905 elif theCriterion == FT_Volume3D:
906 functor = aFilterMgr.CreateVolume3D()
907 elif theCriterion == FT_MaxElementLength2D:
908 functor = aFilterMgr.CreateMaxElementLength2D()
909 elif theCriterion == FT_MaxElementLength3D:
910 functor = aFilterMgr.CreateMaxElementLength3D()
911 elif theCriterion == FT_MultiConnection:
912 functor = aFilterMgr.CreateMultiConnection()
913 elif theCriterion == FT_MultiConnection2D:
914 functor = aFilterMgr.CreateMultiConnection2D()
915 elif theCriterion == FT_Length:
916 functor = aFilterMgr.CreateLength()
917 elif theCriterion == FT_Length2D:
918 functor = aFilterMgr.CreateLength2D()
920 print "Error: given parameter is not numerical functor type."
921 aFilterMgr.UnRegister()
924 ## Creates hypothesis
925 # @param theHType mesh hypothesis type (string)
926 # @param theLibName mesh plug-in library name
927 # @return created hypothesis instance
928 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
929 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
931 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
934 # wrap hypothesis methods
935 #print "HYPOTHESIS", theHType
936 for meth_name in dir( hyp.__class__ ):
937 if not meth_name.startswith("Get") and \
938 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
939 method = getattr ( hyp.__class__, meth_name )
941 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
945 ## Gets the mesh statistic
946 # @return dictionary "element type" - "count of elements"
947 # @ingroup l1_meshinfo
948 def GetMeshInfo(self, obj):
949 if isinstance( obj, Mesh ):
952 if hasattr(obj, "GetMeshInfo"):
953 values = obj.GetMeshInfo()
954 for i in range(SMESH.Entity_Last._v):
955 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
959 ## Get minimum distance between two objects
961 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
962 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
964 # @param src1 first source object
965 # @param src2 second source object
966 # @param id1 node/element id from the first source
967 # @param id2 node/element id from the second (or first) source
968 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
969 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
970 # @return minimum distance value
971 # @sa GetMinDistance()
972 # @ingroup l1_measurements
973 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
974 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
978 result = result.value
981 ## Get measure structure specifying minimum distance data between two objects
983 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
984 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
986 # @param src1 first source object
987 # @param src2 second source object
988 # @param id1 node/element id from the first source
989 # @param id2 node/element id from the second (or first) source
990 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
991 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
992 # @return Measure structure or None if input data is invalid
994 # @ingroup l1_measurements
995 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
996 if isinstance(src1, Mesh): src1 = src1.mesh
997 if isinstance(src2, Mesh): src2 = src2.mesh
998 if src2 is None and id2 != 0: src2 = src1
999 if not hasattr(src1, "_narrow"): return None
1000 src1 = src1._narrow(SMESH.SMESH_IDSource)
1001 if not src1: return None
1002 unRegister = genObjUnRegister()
1005 e = m.GetMeshEditor()
1007 src1 = e.MakeIDSource([id1], SMESH.FACE)
1009 src1 = e.MakeIDSource([id1], SMESH.NODE)
1010 unRegister.set( src1 )
1012 if hasattr(src2, "_narrow"):
1013 src2 = src2._narrow(SMESH.SMESH_IDSource)
1014 if src2 and id2 != 0:
1016 e = m.GetMeshEditor()
1018 src2 = e.MakeIDSource([id2], SMESH.FACE)
1020 src2 = e.MakeIDSource([id2], SMESH.NODE)
1021 unRegister.set( src2 )
1024 aMeasurements = self.CreateMeasurements()
1025 unRegister.set( aMeasurements )
1026 result = aMeasurements.MinDistance(src1, src2)
1029 ## Get bounding box of the specified object(s)
1030 # @param objects single source object or list of source objects
1031 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1032 # @sa GetBoundingBox()
1033 # @ingroup l1_measurements
1034 def BoundingBox(self, objects):
1035 result = self.GetBoundingBox(objects)
1039 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1042 ## Get measure structure specifying bounding box data of the specified object(s)
1043 # @param objects single source object or list of source objects
1044 # @return Measure structure
1046 # @ingroup l1_measurements
1047 def GetBoundingBox(self, objects):
1048 if isinstance(objects, tuple):
1049 objects = list(objects)
1050 if not isinstance(objects, list):
1054 if isinstance(o, Mesh):
1055 srclist.append(o.mesh)
1056 elif hasattr(o, "_narrow"):
1057 src = o._narrow(SMESH.SMESH_IDSource)
1058 if src: srclist.append(src)
1061 aMeasurements = self.CreateMeasurements()
1062 result = aMeasurements.BoundingBox(srclist)
1063 aMeasurements.UnRegister()
1066 ## Get sum of lengths of all 1D elements in the mesh object.
1067 # @param obj mesh, submesh or group
1068 # @return sum of lengths of all 1D elements
1069 # @ingroup l1_measurements
1070 def GetLength(self, obj):
1071 if isinstance(obj, Mesh): obj = obj.mesh
1072 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1073 aMeasurements = self.CreateMeasurements()
1074 value = aMeasurements.Length(obj)
1075 aMeasurements.UnRegister()
1078 ## Get sum of areas of all 2D elements in the mesh object.
1079 # @param obj mesh, submesh or group
1080 # @return sum of areas of all 2D elements
1081 # @ingroup l1_measurements
1082 def GetArea(self, obj):
1083 if isinstance(obj, Mesh): obj = obj.mesh
1084 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1085 aMeasurements = self.CreateMeasurements()
1086 value = aMeasurements.Area(obj)
1087 aMeasurements.UnRegister()
1090 ## Get sum of volumes of all 3D elements in the mesh object.
1091 # @param obj mesh, submesh or group
1092 # @return sum of volumes of all 3D elements
1093 # @ingroup l1_measurements
1094 def GetVolume(self, obj):
1095 if isinstance(obj, Mesh): obj = obj.mesh
1096 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1097 aMeasurements = self.CreateMeasurements()
1098 value = aMeasurements.Volume(obj)
1099 aMeasurements.UnRegister()
1102 pass # end of class smeshBuilder
1105 #Registering the new proxy for SMESH_Gen
1106 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1108 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1109 # interface to create or load meshes.
1114 # salome.salome_init()
1115 # from salome.smesh import smeshBuilder
1116 # smesh = smeshBuilder.New(theStudy)
1118 # @param study SALOME study, generally obtained by salome.myStudy.
1119 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1120 # @return smeshBuilder instance
1122 def New( study, instance=None):
1124 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1125 interface to create or load meshes.
1129 salome.salome_init()
1130 from salome.smesh import smeshBuilder
1131 smesh = smeshBuilder.New(theStudy)
1134 study SALOME study, generally obtained by salome.myStudy.
1135 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1137 smeshBuilder instance
1145 smeshInst = smeshBuilder()
1146 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1147 smeshInst.init_smesh(study)
1151 # Public class: Mesh
1152 # ==================
1154 ## This class allows defining and managing a mesh.
1155 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1156 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1157 # new nodes and elements and by changing the existing entities), to get information
1158 # about a mesh and to export a mesh into different formats.
1160 __metaclass__ = MeshMeta
1168 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1169 # sets the GUI name of this mesh to \a name.
1170 # @param smeshpyD an instance of smeshBuilder class
1171 # @param geompyD an instance of geomBuilder class
1172 # @param obj Shape to be meshed or SMESH_Mesh object
1173 # @param name Study name of the mesh
1174 # @ingroup l2_construct
1175 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1176 self.smeshpyD=smeshpyD
1177 self.geompyD=geompyD
1182 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1185 # publish geom of mesh (issue 0021122)
1186 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1188 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1189 if studyID != geompyD.myStudyId:
1190 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1193 geo_name = name + " shape"
1195 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1196 geompyD.addToStudy( self.geom, geo_name )
1197 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1199 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1202 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1204 self.smeshpyD.SetName(self.mesh, name)
1206 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1209 self.geom = self.mesh.GetShapeToMesh()
1211 self.editor = self.mesh.GetMeshEditor()
1212 self.functors = [None] * SMESH.FT_Undefined._v
1214 # set self to algoCreator's
1215 for attrName in dir(self):
1216 attr = getattr( self, attrName )
1217 if isinstance( attr, algoCreator ):
1218 #print "algoCreator ", attrName
1219 setattr( self, attrName, attr.copy( self ))
1224 ## Destructor. Clean-up resources
1227 #self.mesh.UnRegister()
1231 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1232 # @param theMesh a SMESH_Mesh object
1233 # @ingroup l2_construct
1234 def SetMesh(self, theMesh):
1235 # do not call Register() as this prevents mesh servant deletion at closing study
1236 #if self.mesh: self.mesh.UnRegister()
1239 #self.mesh.Register()
1240 self.geom = self.mesh.GetShapeToMesh()
1243 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1244 # @return a SMESH_Mesh object
1245 # @ingroup l2_construct
1249 ## Gets the name of the mesh
1250 # @return the name of the mesh as a string
1251 # @ingroup l2_construct
1253 name = GetName(self.GetMesh())
1256 ## Sets a name to the mesh
1257 # @param name a new name of the mesh
1258 # @ingroup l2_construct
1259 def SetName(self, name):
1260 self.smeshpyD.SetName(self.GetMesh(), name)
1262 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1263 # The subMesh object gives access to the IDs of nodes and elements.
1264 # @param geom a geometrical object (shape)
1265 # @param name a name for the submesh
1266 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1267 # @ingroup l2_submeshes
1268 def GetSubMesh(self, geom, name):
1269 AssureGeomPublished( self, geom, name )
1270 submesh = self.mesh.GetSubMesh( geom, name )
1273 ## Returns the shape associated to the mesh
1274 # @return a GEOM_Object
1275 # @ingroup l2_construct
1279 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1280 # @param geom the shape to be meshed (GEOM_Object)
1281 # @ingroup l2_construct
1282 def SetShape(self, geom):
1283 self.mesh = self.smeshpyD.CreateMesh(geom)
1285 ## Loads mesh from the study after opening the study
1289 ## Returns true if the hypotheses are defined well
1290 # @param theSubObject a sub-shape of a mesh shape
1291 # @return True or False
1292 # @ingroup l2_construct
1293 def IsReadyToCompute(self, theSubObject):
1294 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1296 ## Returns errors of hypotheses definition.
1297 # The list of errors is empty if everything is OK.
1298 # @param theSubObject a sub-shape of a mesh shape
1299 # @return a list of errors
1300 # @ingroup l2_construct
1301 def GetAlgoState(self, theSubObject):
1302 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1304 ## Returns a geometrical object on which the given element was built.
1305 # The returned geometrical object, if not nil, is either found in the
1306 # study or published by this method with the given name
1307 # @param theElementID the id of the mesh element
1308 # @param theGeomName the user-defined name of the geometrical object
1309 # @return GEOM::GEOM_Object instance
1310 # @ingroup l2_construct
1311 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1312 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1314 ## Returns the mesh dimension depending on the dimension of the underlying shape
1315 # or, if the mesh is not based on any shape, basing on deimension of elements
1316 # @return mesh dimension as an integer value [0,3]
1317 # @ingroup l1_auxiliary
1318 def MeshDimension(self):
1319 if self.mesh.HasShapeToMesh():
1320 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1321 if len( shells ) > 0 :
1323 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1325 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1330 if self.NbVolumes() > 0: return 3
1331 if self.NbFaces() > 0: return 2
1332 if self.NbEdges() > 0: return 1
1335 ## Evaluates size of prospective mesh on a shape
1336 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1337 # To know predicted number of e.g. edges, inquire it this way
1338 # Evaluate()[ EnumToLong( Entity_Edge )]
1339 def Evaluate(self, geom=0):
1340 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1342 geom = self.mesh.GetShapeToMesh()
1345 return self.smeshpyD.Evaluate(self.mesh, geom)
1348 ## Computes the mesh and returns the status of the computation
1349 # @param geom geomtrical shape on which mesh data should be computed
1350 # @param discardModifs if True and the mesh has been edited since
1351 # a last total re-compute and that may prevent successful partial re-compute,
1352 # then the mesh is cleaned before Compute()
1353 # @return True or False
1354 # @ingroup l2_construct
1355 def Compute(self, geom=0, discardModifs=False):
1356 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1358 geom = self.mesh.GetShapeToMesh()
1363 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1365 ok = self.smeshpyD.Compute(self.mesh, geom)
1366 except SALOME.SALOME_Exception, ex:
1367 print "Mesh computation failed, exception caught:"
1368 print " ", ex.details.text
1371 print "Mesh computation failed, exception caught:"
1372 traceback.print_exc()
1376 # Treat compute errors
1377 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1378 for err in computeErrors:
1380 if self.mesh.HasShapeToMesh():
1382 mainIOR = salome.orb.object_to_string(geom)
1383 for sname in salome.myStudyManager.GetOpenStudies():
1384 s = salome.myStudyManager.GetStudyByName(sname)
1386 mainSO = s.FindObjectIOR(mainIOR)
1387 if not mainSO: continue
1388 if err.subShapeID == 1:
1389 shapeText = ' on "%s"' % mainSO.GetName()
1390 subIt = s.NewChildIterator(mainSO)
1392 subSO = subIt.Value()
1394 obj = subSO.GetObject()
1395 if not obj: continue
1396 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1398 ids = go.GetSubShapeIndices()
1399 if len(ids) == 1 and ids[0] == err.subShapeID:
1400 shapeText = ' on "%s"' % subSO.GetName()
1403 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1405 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1407 shapeText = " on subshape #%s" % (err.subShapeID)
1409 shapeText = " on subshape #%s" % (err.subShapeID)
1411 stdErrors = ["OK", #COMPERR_OK
1412 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1413 "std::exception", #COMPERR_STD_EXCEPTION
1414 "OCC exception", #COMPERR_OCC_EXCEPTION
1415 "..", #COMPERR_SLM_EXCEPTION
1416 "Unknown exception", #COMPERR_EXCEPTION
1417 "Memory allocation problem", #COMPERR_MEMORY_PB
1418 "Algorithm failed", #COMPERR_ALGO_FAILED
1419 "Unexpected geometry", #COMPERR_BAD_SHAPE
1420 "Warning", #COMPERR_WARNING
1421 "Computation cancelled",#COMPERR_CANCELED
1422 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1424 if err.code < len(stdErrors): errText = stdErrors[err.code]
1426 errText = "code %s" % -err.code
1427 if errText: errText += ". "
1428 errText += err.comment
1429 if allReasons != "":allReasons += "\n"
1431 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1433 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1437 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1439 if err.isGlobalAlgo:
1447 reason = '%s %sD algorithm is missing' % (glob, dim)
1448 elif err.state == HYP_MISSING:
1449 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1450 % (glob, dim, name, dim))
1451 elif err.state == HYP_NOTCONFORM:
1452 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1453 elif err.state == HYP_BAD_PARAMETER:
1454 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1455 % ( glob, dim, name ))
1456 elif err.state == HYP_BAD_GEOMETRY:
1457 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1458 'geometry' % ( glob, dim, name ))
1459 elif err.state == HYP_HIDDEN_ALGO:
1460 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1461 'algorithm of upper dimension generating %sD mesh'
1462 % ( glob, dim, name, glob, dim ))
1464 reason = ("For unknown reason. "
1465 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1467 if allReasons != "":allReasons += "\n"
1468 allReasons += "- " + reason
1470 if not ok or allReasons != "":
1471 msg = '"' + GetName(self.mesh) + '"'
1472 if ok: msg += " has been computed with warnings"
1473 else: msg += " has not been computed"
1474 if allReasons != "": msg += ":"
1479 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1480 smeshgui = salome.ImportComponentGUI("SMESH")
1481 smeshgui.Init(self.mesh.GetStudyId())
1482 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1483 salome.sg.updateObjBrowser(1)
1487 ## Return submesh objects list in meshing order
1488 # @return list of list of submesh objects
1489 # @ingroup l2_construct
1490 def GetMeshOrder(self):
1491 return self.mesh.GetMeshOrder()
1493 ## Return submesh objects list in meshing order
1494 # @return list of list of submesh objects
1495 # @ingroup l2_construct
1496 def SetMeshOrder(self, submeshes):
1497 return self.mesh.SetMeshOrder(submeshes)
1499 ## Removes all nodes and elements
1500 # @ingroup l2_construct
1503 if ( salome.sg.hasDesktop() and
1504 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1505 smeshgui = salome.ImportComponentGUI("SMESH")
1506 smeshgui.Init(self.mesh.GetStudyId())
1507 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1508 salome.sg.updateObjBrowser(1)
1510 ## Removes all nodes and elements of indicated shape
1511 # @ingroup l2_construct
1512 def ClearSubMesh(self, geomId):
1513 self.mesh.ClearSubMesh(geomId)
1514 if salome.sg.hasDesktop():
1515 smeshgui = salome.ImportComponentGUI("SMESH")
1516 smeshgui.Init(self.mesh.GetStudyId())
1517 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1518 salome.sg.updateObjBrowser(1)
1520 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1521 # @param fineness [0.0,1.0] defines mesh fineness
1522 # @return True or False
1523 # @ingroup l3_algos_basic
1524 def AutomaticTetrahedralization(self, fineness=0):
1525 dim = self.MeshDimension()
1527 self.RemoveGlobalHypotheses()
1528 self.Segment().AutomaticLength(fineness)
1530 self.Triangle().LengthFromEdges()
1533 from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1534 self.Tetrahedron(NETGEN)
1536 return self.Compute()
1538 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1539 # @param fineness [0.0, 1.0] defines mesh fineness
1540 # @return True or False
1541 # @ingroup l3_algos_basic
1542 def AutomaticHexahedralization(self, fineness=0):
1543 dim = self.MeshDimension()
1544 # assign the hypotheses
1545 self.RemoveGlobalHypotheses()
1546 self.Segment().AutomaticLength(fineness)
1553 return self.Compute()
1555 ## Assigns a hypothesis
1556 # @param hyp a hypothesis to assign
1557 # @param geom a subhape of mesh geometry
1558 # @return SMESH.Hypothesis_Status
1559 # @ingroup l2_hypotheses
1560 def AddHypothesis(self, hyp, geom=0):
1561 if isinstance( hyp, Mesh_Algorithm ):
1562 hyp = hyp.GetAlgorithm()
1567 geom = self.mesh.GetShapeToMesh()
1570 if self.mesh.HasShapeToMesh():
1571 hyp_type = hyp.GetName()
1572 lib_name = hyp.GetLibName()
1573 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1574 if checkAll and geom:
1575 checkAll = geom.GetType() == 37
1576 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1578 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1579 status = self.mesh.AddHypothesis(geom, hyp)
1581 status = HYP_BAD_GEOMETRY
1582 hyp_name = GetName( hyp )
1585 geom_name = geom.GetName()
1586 isAlgo = hyp._narrow( SMESH_Algo )
1587 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1590 ## Return True if an algorithm of hypothesis is assigned to a given shape
1591 # @param hyp a hypothesis to check
1592 # @param geom a subhape of mesh geometry
1593 # @return True of False
1594 # @ingroup l2_hypotheses
1595 def IsUsedHypothesis(self, hyp, geom):
1596 if not hyp: # or not geom
1598 if isinstance( hyp, Mesh_Algorithm ):
1599 hyp = hyp.GetAlgorithm()
1601 hyps = self.GetHypothesisList(geom)
1603 if h.GetId() == hyp.GetId():
1607 ## Unassigns a hypothesis
1608 # @param hyp a hypothesis to unassign
1609 # @param geom a sub-shape of mesh geometry
1610 # @return SMESH.Hypothesis_Status
1611 # @ingroup l2_hypotheses
1612 def RemoveHypothesis(self, hyp, geom=0):
1615 if isinstance( hyp, Mesh_Algorithm ):
1616 hyp = hyp.GetAlgorithm()
1622 if self.IsUsedHypothesis( hyp, shape ):
1623 return self.mesh.RemoveHypothesis( shape, hyp )
1624 hypName = GetName( hyp )
1625 geoName = GetName( shape )
1626 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1629 ## Gets the list of hypotheses added on a geometry
1630 # @param geom a sub-shape of mesh geometry
1631 # @return the sequence of SMESH_Hypothesis
1632 # @ingroup l2_hypotheses
1633 def GetHypothesisList(self, geom):
1634 return self.mesh.GetHypothesisList( geom )
1636 ## Removes all global hypotheses
1637 # @ingroup l2_hypotheses
1638 def RemoveGlobalHypotheses(self):
1639 current_hyps = self.mesh.GetHypothesisList( self.geom )
1640 for hyp in current_hyps:
1641 self.mesh.RemoveHypothesis( self.geom, hyp )
1645 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1646 ## allowing to overwrite the file if it exists or add the exported data to its contents
1647 # @param f is the file name
1648 # @param auto_groups boolean parameter for creating/not creating
1649 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1650 # the typical use is auto_groups=false.
1651 # @param version MED format version(MED_V2_1 or MED_V2_2)
1652 # @param overwrite boolean parameter for overwriting/not overwriting the file
1653 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1654 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1655 # - 1D if all mesh nodes lie on OX coordinate axis, or
1656 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1657 # - 3D in the rest cases.
1658 # If @a autoDimension is @c False, the space dimension is always 3.
1659 # @param fields : list of GEOM fields defined on the shape to mesh.
1660 # @param geomAssocFields : each character of this string means a need to export a
1661 # corresponding field; correspondence between fields and characters is following:
1662 # - 'v' stands for _vertices_ field;
1663 # - 'e' stands for _edges_ field;
1664 # - 'f' stands for _faces_ field;
1665 # - 's' stands for _solids_ field.
1666 # @ingroup l2_impexp
1667 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1668 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1669 if meshPart or fields or geomAssocFields:
1670 unRegister = genObjUnRegister()
1671 if isinstance( meshPart, list ):
1672 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1673 unRegister.set( meshPart )
1674 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1675 fields, geomAssocFields)
1677 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1679 ## Exports the mesh in a file in SAUV format
1680 # @param f is the file name
1681 # @param auto_groups boolean parameter for creating/not creating
1682 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1683 # the typical use is auto_groups=false.
1684 # @ingroup l2_impexp
1685 def ExportSAUV(self, f, auto_groups=0):
1686 self.mesh.ExportSAUV(f, auto_groups)
1688 ## Exports the mesh in a file in DAT format
1689 # @param f the file name
1690 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1691 # @ingroup l2_impexp
1692 def ExportDAT(self, f, meshPart=None):
1694 unRegister = genObjUnRegister()
1695 if isinstance( meshPart, list ):
1696 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1697 unRegister.set( meshPart )
1698 self.mesh.ExportPartToDAT( meshPart, f )
1700 self.mesh.ExportDAT(f)
1702 ## Exports the mesh in a file in UNV format
1703 # @param f the file name
1704 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1705 # @ingroup l2_impexp
1706 def ExportUNV(self, f, meshPart=None):
1708 unRegister = genObjUnRegister()
1709 if isinstance( meshPart, list ):
1710 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1711 unRegister.set( meshPart )
1712 self.mesh.ExportPartToUNV( meshPart, f )
1714 self.mesh.ExportUNV(f)
1716 ## Export the mesh in a file in STL format
1717 # @param f the file name
1718 # @param ascii defines the file encoding
1719 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1720 # @ingroup l2_impexp
1721 def ExportSTL(self, f, ascii=1, meshPart=None):
1723 unRegister = genObjUnRegister()
1724 if isinstance( meshPart, list ):
1725 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1726 unRegister.set( meshPart )
1727 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1729 self.mesh.ExportSTL(f, ascii)
1731 ## Exports the mesh in a file in CGNS format
1732 # @param f is the file name
1733 # @param overwrite boolean parameter for overwriting/not overwriting the file
1734 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1735 # @ingroup l2_impexp
1736 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1737 unRegister = genObjUnRegister()
1738 if isinstance( meshPart, list ):
1739 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1740 unRegister.set( meshPart )
1741 if isinstance( meshPart, Mesh ):
1742 meshPart = meshPart.mesh
1744 meshPart = self.mesh
1745 self.mesh.ExportCGNS(meshPart, f, overwrite)
1747 ## Exports the mesh in a file in GMF format.
1748 # GMF files must have .mesh extension for the ASCII format and .meshb for
1749 # the bynary format. Other extensions are not allowed.
1750 # @param f is the file name
1751 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1752 # @ingroup l2_impexp
1753 def ExportGMF(self, f, meshPart=None):
1754 unRegister = genObjUnRegister()
1755 if isinstance( meshPart, list ):
1756 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1757 unRegister.set( meshPart )
1758 if isinstance( meshPart, Mesh ):
1759 meshPart = meshPart.mesh
1761 meshPart = self.mesh
1762 self.mesh.ExportGMF(meshPart, f, True)
1764 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1765 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1766 ## allowing to overwrite the file if it exists or add the exported data to its contents
1767 # @param f the file name
1768 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1769 # @param opt boolean parameter for creating/not creating
1770 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1771 # @param overwrite boolean parameter for overwriting/not overwriting the file
1772 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1773 # - 1D if all mesh nodes lie on OX coordinate axis, or
1774 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1775 # - 3D in the rest cases.
1777 # If @a autoDimension is @c False, the space dimension is always 3.
1778 # @ingroup l2_impexp
1779 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1780 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1782 # Operations with groups:
1783 # ----------------------
1785 ## Creates an empty mesh group
1786 # @param elementType the type of elements in the group
1787 # @param name the name of the mesh group
1788 # @return SMESH_Group
1789 # @ingroup l2_grps_create
1790 def CreateEmptyGroup(self, elementType, name):
1791 return self.mesh.CreateGroup(elementType, name)
1793 ## Creates a mesh group based on the geometric object \a grp
1794 # and gives a \a name, \n if this parameter is not defined
1795 # the name is the same as the geometric group name \n
1796 # Note: Works like GroupOnGeom().
1797 # @param grp a geometric group, a vertex, an edge, a face or a solid
1798 # @param name the name of the mesh group
1799 # @return SMESH_GroupOnGeom
1800 # @ingroup l2_grps_create
1801 def Group(self, grp, name=""):
1802 return self.GroupOnGeom(grp, name)
1804 ## Creates a mesh group based on the geometrical object \a grp
1805 # and gives a \a name, \n if this parameter is not defined
1806 # the name is the same as the geometrical group name
1807 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1808 # @param name the name of the mesh group
1809 # @param typ the type of elements in the group. If not set, it is
1810 # automatically detected by the type of the geometry
1811 # @return SMESH_GroupOnGeom
1812 # @ingroup l2_grps_create
1813 def GroupOnGeom(self, grp, name="", typ=None):
1814 AssureGeomPublished( self, grp, name )
1816 name = grp.GetName()
1818 typ = self._groupTypeFromShape( grp )
1819 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1821 ## Pivate method to get a type of group on geometry
1822 def _groupTypeFromShape( self, shape ):
1823 tgeo = str(shape.GetShapeType())
1824 if tgeo == "VERTEX":
1826 elif tgeo == "EDGE":
1828 elif tgeo == "FACE" or tgeo == "SHELL":
1830 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1832 elif tgeo == "COMPOUND":
1833 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1835 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1836 return self._groupTypeFromShape( sub[0] )
1839 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1842 ## Creates a mesh group with given \a name based on the \a filter which
1843 ## is a special type of group dynamically updating it's contents during
1844 ## mesh modification
1845 # @param typ the type of elements in the group
1846 # @param name the name of the mesh group
1847 # @param filter the filter defining group contents
1848 # @return SMESH_GroupOnFilter
1849 # @ingroup l2_grps_create
1850 def GroupOnFilter(self, typ, name, filter):
1851 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1853 ## Creates a mesh group by the given ids of elements
1854 # @param groupName the name of the mesh group
1855 # @param elementType the type of elements in the group
1856 # @param elemIDs the list of ids
1857 # @return SMESH_Group
1858 # @ingroup l2_grps_create
1859 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1860 group = self.mesh.CreateGroup(elementType, groupName)
1864 ## Creates a mesh group by the given conditions
1865 # @param groupName the name of the mesh group
1866 # @param elementType the type of elements in the group
1867 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1868 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1869 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1870 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1871 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1872 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1873 # @return SMESH_Group
1874 # @ingroup l2_grps_create
1878 CritType=FT_Undefined,
1881 UnaryOp=FT_Undefined,
1883 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1884 group = self.MakeGroupByCriterion(groupName, aCriterion)
1887 ## Creates a mesh group by the given criterion
1888 # @param groupName the name of the mesh group
1889 # @param Criterion the instance of Criterion class
1890 # @return SMESH_Group
1891 # @ingroup l2_grps_create
1892 def MakeGroupByCriterion(self, groupName, Criterion):
1893 aFilterMgr = self.smeshpyD.CreateFilterManager()
1894 aFilter = aFilterMgr.CreateFilter()
1896 aCriteria.append(Criterion)
1897 aFilter.SetCriteria(aCriteria)
1898 group = self.MakeGroupByFilter(groupName, aFilter)
1899 aFilterMgr.UnRegister()
1902 ## Creates a mesh group by the given criteria (list of criteria)
1903 # @param groupName the name of the mesh group
1904 # @param theCriteria the list of criteria
1905 # @return SMESH_Group
1906 # @ingroup l2_grps_create
1907 def MakeGroupByCriteria(self, groupName, theCriteria):
1908 aFilterMgr = self.smeshpyD.CreateFilterManager()
1909 aFilter = aFilterMgr.CreateFilter()
1910 aFilter.SetCriteria(theCriteria)
1911 group = self.MakeGroupByFilter(groupName, aFilter)
1912 aFilterMgr.UnRegister()
1915 ## Creates a mesh group by the given filter
1916 # @param groupName the name of the mesh group
1917 # @param theFilter the instance of Filter class
1918 # @return SMESH_Group
1919 # @ingroup l2_grps_create
1920 def MakeGroupByFilter(self, groupName, theFilter):
1921 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1922 theFilter.SetMesh( self.mesh )
1923 group.AddFrom( theFilter )
1927 # @ingroup l2_grps_delete
1928 def RemoveGroup(self, group):
1929 self.mesh.RemoveGroup(group)
1931 ## Removes a group with its contents
1932 # @ingroup l2_grps_delete
1933 def RemoveGroupWithContents(self, group):
1934 self.mesh.RemoveGroupWithContents(group)
1936 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1937 # @return a sequence of SMESH_GroupBase
1938 # @ingroup l2_grps_create
1939 def GetGroups(self):
1940 return self.mesh.GetGroups()
1942 ## Gets the number of groups existing in the mesh
1943 # @return the quantity of groups as an integer value
1944 # @ingroup l2_grps_create
1946 return self.mesh.NbGroups()
1948 ## Gets the list of names of groups existing in the mesh
1949 # @return list of strings
1950 # @ingroup l2_grps_create
1951 def GetGroupNames(self):
1952 groups = self.GetGroups()
1954 for group in groups:
1955 names.append(group.GetName())
1958 ## Produces a union of two groups
1959 # A new group is created. All mesh elements that are
1960 # present in the initial groups are added to the new one
1961 # @return an instance of SMESH_Group
1962 # @ingroup l2_grps_operon
1963 def UnionGroups(self, group1, group2, name):
1964 return self.mesh.UnionGroups(group1, group2, name)
1966 ## Produces a union list of groups
1967 # New group is created. All mesh elements that are present in
1968 # initial groups are added to the new one
1969 # @return an instance of SMESH_Group
1970 # @ingroup l2_grps_operon
1971 def UnionListOfGroups(self, groups, name):
1972 return self.mesh.UnionListOfGroups(groups, name)
1974 ## Prodices an intersection of two groups
1975 # A new group is created. All mesh elements that are common
1976 # for the two initial groups are added to the new one.
1977 # @return an instance of SMESH_Group
1978 # @ingroup l2_grps_operon
1979 def IntersectGroups(self, group1, group2, name):
1980 return self.mesh.IntersectGroups(group1, group2, name)
1982 ## Produces an intersection of groups
1983 # New group is created. All mesh elements that are present in all
1984 # initial groups simultaneously are added to the new one
1985 # @return an instance of SMESH_Group
1986 # @ingroup l2_grps_operon
1987 def IntersectListOfGroups(self, groups, name):
1988 return self.mesh.IntersectListOfGroups(groups, name)
1990 ## Produces a cut of two groups
1991 # A new group is created. All mesh elements that are present in
1992 # the main group but are not present in the tool group are added to the new one
1993 # @return an instance of SMESH_Group
1994 # @ingroup l2_grps_operon
1995 def CutGroups(self, main_group, tool_group, name):
1996 return self.mesh.CutGroups(main_group, tool_group, name)
1998 ## Produces a cut of groups
1999 # A new group is created. All mesh elements that are present in main groups
2000 # but do not present in tool groups are added to the new one
2001 # @return an instance of SMESH_Group
2002 # @ingroup l2_grps_operon
2003 def CutListOfGroups(self, main_groups, tool_groups, name):
2004 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2006 ## Produces a group of elements of specified type using list of existing groups
2007 # A new group is created. System
2008 # 1) extracts all nodes on which groups elements are built
2009 # 2) combines all elements of specified dimension laying on these nodes
2010 # @return an instance of SMESH_Group
2011 # @ingroup l2_grps_operon
2012 def CreateDimGroup(self, groups, elem_type, name):
2013 return self.mesh.CreateDimGroup(groups, elem_type, name)
2016 ## Convert group on geom into standalone group
2017 # @ingroup l2_grps_delete
2018 def ConvertToStandalone(self, group):
2019 return self.mesh.ConvertToStandalone(group)
2021 # Get some info about mesh:
2022 # ------------------------
2024 ## Returns the log of nodes and elements added or removed
2025 # since the previous clear of the log.
2026 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2027 # @return list of log_block structures:
2032 # @ingroup l1_auxiliary
2033 def GetLog(self, clearAfterGet):
2034 return self.mesh.GetLog(clearAfterGet)
2036 ## Clears the log of nodes and elements added or removed since the previous
2037 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2038 # @ingroup l1_auxiliary
2040 self.mesh.ClearLog()
2042 ## Toggles auto color mode on the object.
2043 # @param theAutoColor the flag which toggles auto color mode.
2044 # @ingroup l1_auxiliary
2045 def SetAutoColor(self, theAutoColor):
2046 self.mesh.SetAutoColor(theAutoColor)
2048 ## Gets flag of object auto color mode.
2049 # @return True or False
2050 # @ingroup l1_auxiliary
2051 def GetAutoColor(self):
2052 return self.mesh.GetAutoColor()
2054 ## Gets the internal ID
2055 # @return integer value, which is the internal Id of the mesh
2056 # @ingroup l1_auxiliary
2058 return self.mesh.GetId()
2061 # @return integer value, which is the study Id of the mesh
2062 # @ingroup l1_auxiliary
2063 def GetStudyId(self):
2064 return self.mesh.GetStudyId()
2066 ## Checks the group names for duplications.
2067 # Consider the maximum group name length stored in MED file.
2068 # @return True or False
2069 # @ingroup l1_auxiliary
2070 def HasDuplicatedGroupNamesMED(self):
2071 return self.mesh.HasDuplicatedGroupNamesMED()
2073 ## Obtains the mesh editor tool
2074 # @return an instance of SMESH_MeshEditor
2075 # @ingroup l1_modifying
2076 def GetMeshEditor(self):
2079 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2080 # can be passed as argument to a method accepting mesh, group or sub-mesh
2081 # @return an instance of SMESH_IDSource
2082 # @ingroup l1_auxiliary
2083 def GetIDSource(self, ids, elemType):
2084 return self.editor.MakeIDSource(ids, elemType)
2087 # Get informations about mesh contents:
2088 # ------------------------------------
2090 ## Gets the mesh stattistic
2091 # @return dictionary type element - count of elements
2092 # @ingroup l1_meshinfo
2093 def GetMeshInfo(self, obj = None):
2094 if not obj: obj = self.mesh
2095 return self.smeshpyD.GetMeshInfo(obj)
2097 ## Returns the number of nodes in the mesh
2098 # @return an integer value
2099 # @ingroup l1_meshinfo
2101 return self.mesh.NbNodes()
2103 ## Returns the number of elements in the mesh
2104 # @return an integer value
2105 # @ingroup l1_meshinfo
2106 def NbElements(self):
2107 return self.mesh.NbElements()
2109 ## Returns the number of 0d elements in the mesh
2110 # @return an integer value
2111 # @ingroup l1_meshinfo
2112 def Nb0DElements(self):
2113 return self.mesh.Nb0DElements()
2115 ## Returns the number of ball discrete elements in the mesh
2116 # @return an integer value
2117 # @ingroup l1_meshinfo
2119 return self.mesh.NbBalls()
2121 ## Returns the number of edges in the mesh
2122 # @return an integer value
2123 # @ingroup l1_meshinfo
2125 return self.mesh.NbEdges()
2127 ## Returns the number of edges with the given order in the mesh
2128 # @param elementOrder the order of elements:
2129 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2130 # @return an integer value
2131 # @ingroup l1_meshinfo
2132 def NbEdgesOfOrder(self, elementOrder):
2133 return self.mesh.NbEdgesOfOrder(elementOrder)
2135 ## Returns the number of faces in the mesh
2136 # @return an integer value
2137 # @ingroup l1_meshinfo
2139 return self.mesh.NbFaces()
2141 ## Returns the number of faces with the given order in the mesh
2142 # @param elementOrder the order of elements:
2143 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2144 # @return an integer value
2145 # @ingroup l1_meshinfo
2146 def NbFacesOfOrder(self, elementOrder):
2147 return self.mesh.NbFacesOfOrder(elementOrder)
2149 ## Returns the number of triangles in the mesh
2150 # @return an integer value
2151 # @ingroup l1_meshinfo
2152 def NbTriangles(self):
2153 return self.mesh.NbTriangles()
2155 ## Returns the number of triangles with the given order in the mesh
2156 # @param elementOrder is the order of elements:
2157 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2158 # @return an integer value
2159 # @ingroup l1_meshinfo
2160 def NbTrianglesOfOrder(self, elementOrder):
2161 return self.mesh.NbTrianglesOfOrder(elementOrder)
2163 ## Returns the number of biquadratic triangles in the mesh
2164 # @return an integer value
2165 # @ingroup l1_meshinfo
2166 def NbBiQuadTriangles(self):
2167 return self.mesh.NbBiQuadTriangles()
2169 ## Returns the number of quadrangles in the mesh
2170 # @return an integer value
2171 # @ingroup l1_meshinfo
2172 def NbQuadrangles(self):
2173 return self.mesh.NbQuadrangles()
2175 ## Returns the number of quadrangles with the given order in the mesh
2176 # @param elementOrder the order of elements:
2177 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2178 # @return an integer value
2179 # @ingroup l1_meshinfo
2180 def NbQuadranglesOfOrder(self, elementOrder):
2181 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2183 ## Returns the number of biquadratic quadrangles in the mesh
2184 # @return an integer value
2185 # @ingroup l1_meshinfo
2186 def NbBiQuadQuadrangles(self):
2187 return self.mesh.NbBiQuadQuadrangles()
2189 ## Returns the number of polygons in the mesh
2190 # @return an integer value
2191 # @ingroup l1_meshinfo
2192 def NbPolygons(self):
2193 return self.mesh.NbPolygons()
2195 ## Returns the number of volumes in the mesh
2196 # @return an integer value
2197 # @ingroup l1_meshinfo
2198 def NbVolumes(self):
2199 return self.mesh.NbVolumes()
2201 ## Returns the number of volumes with the given order in the mesh
2202 # @param elementOrder the order of elements:
2203 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2204 # @return an integer value
2205 # @ingroup l1_meshinfo
2206 def NbVolumesOfOrder(self, elementOrder):
2207 return self.mesh.NbVolumesOfOrder(elementOrder)
2209 ## Returns the number of tetrahedrons in the mesh
2210 # @return an integer value
2211 # @ingroup l1_meshinfo
2213 return self.mesh.NbTetras()
2215 ## Returns the number of tetrahedrons with the given order in the mesh
2216 # @param elementOrder the order of elements:
2217 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2218 # @return an integer value
2219 # @ingroup l1_meshinfo
2220 def NbTetrasOfOrder(self, elementOrder):
2221 return self.mesh.NbTetrasOfOrder(elementOrder)
2223 ## Returns the number of hexahedrons in the mesh
2224 # @return an integer value
2225 # @ingroup l1_meshinfo
2227 return self.mesh.NbHexas()
2229 ## Returns the number of hexahedrons with the given order in the mesh
2230 # @param elementOrder the order of elements:
2231 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2232 # @return an integer value
2233 # @ingroup l1_meshinfo
2234 def NbHexasOfOrder(self, elementOrder):
2235 return self.mesh.NbHexasOfOrder(elementOrder)
2237 ## Returns the number of triquadratic hexahedrons in the mesh
2238 # @return an integer value
2239 # @ingroup l1_meshinfo
2240 def NbTriQuadraticHexas(self):
2241 return self.mesh.NbTriQuadraticHexas()
2243 ## Returns the number of pyramids in the mesh
2244 # @return an integer value
2245 # @ingroup l1_meshinfo
2246 def NbPyramids(self):
2247 return self.mesh.NbPyramids()
2249 ## Returns the number of pyramids with the given order in the mesh
2250 # @param elementOrder the order of elements:
2251 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2252 # @return an integer value
2253 # @ingroup l1_meshinfo
2254 def NbPyramidsOfOrder(self, elementOrder):
2255 return self.mesh.NbPyramidsOfOrder(elementOrder)
2257 ## Returns the number of prisms in the mesh
2258 # @return an integer value
2259 # @ingroup l1_meshinfo
2261 return self.mesh.NbPrisms()
2263 ## Returns the number of prisms with the given order in the mesh
2264 # @param elementOrder the order of elements:
2265 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2266 # @return an integer value
2267 # @ingroup l1_meshinfo
2268 def NbPrismsOfOrder(self, elementOrder):
2269 return self.mesh.NbPrismsOfOrder(elementOrder)
2271 ## Returns the number of hexagonal prisms in the mesh
2272 # @return an integer value
2273 # @ingroup l1_meshinfo
2274 def NbHexagonalPrisms(self):
2275 return self.mesh.NbHexagonalPrisms()
2277 ## Returns the number of polyhedrons in the mesh
2278 # @return an integer value
2279 # @ingroup l1_meshinfo
2280 def NbPolyhedrons(self):
2281 return self.mesh.NbPolyhedrons()
2283 ## Returns the number of submeshes in the mesh
2284 # @return an integer value
2285 # @ingroup l1_meshinfo
2286 def NbSubMesh(self):
2287 return self.mesh.NbSubMesh()
2289 ## Returns the list of mesh elements IDs
2290 # @return the list of integer values
2291 # @ingroup l1_meshinfo
2292 def GetElementsId(self):
2293 return self.mesh.GetElementsId()
2295 ## Returns the list of IDs of mesh elements with the given type
2296 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2297 # @return list of integer values
2298 # @ingroup l1_meshinfo
2299 def GetElementsByType(self, elementType):
2300 return self.mesh.GetElementsByType(elementType)
2302 ## Returns the list of mesh nodes IDs
2303 # @return the list of integer values
2304 # @ingroup l1_meshinfo
2305 def GetNodesId(self):
2306 return self.mesh.GetNodesId()
2308 # Get the information about mesh elements:
2309 # ------------------------------------
2311 ## Returns the type of mesh element
2312 # @return the value from SMESH::ElementType enumeration
2313 # @ingroup l1_meshinfo
2314 def GetElementType(self, id, iselem):
2315 return self.mesh.GetElementType(id, iselem)
2317 ## Returns the geometric type of mesh element
2318 # @return the value from SMESH::EntityType enumeration
2319 # @ingroup l1_meshinfo
2320 def GetElementGeomType(self, id):
2321 return self.mesh.GetElementGeomType(id)
2323 ## Returns the shape type of mesh element
2324 # @return the value from SMESH::GeometryType enumeration
2325 # @ingroup l1_meshinfo
2326 def GetElementShape(self, id):
2327 return self.mesh.GetElementShape(id)
2329 ## Returns the list of submesh elements IDs
2330 # @param Shape a geom object(sub-shape) IOR
2331 # Shape must be the sub-shape of a ShapeToMesh()
2332 # @return the list of integer values
2333 # @ingroup l1_meshinfo
2334 def GetSubMeshElementsId(self, Shape):
2335 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2336 ShapeID = Shape.GetSubShapeIndices()[0]
2339 return self.mesh.GetSubMeshElementsId(ShapeID)
2341 ## Returns the list of submesh nodes IDs
2342 # @param Shape a geom object(sub-shape) IOR
2343 # Shape must be the sub-shape of a ShapeToMesh()
2344 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2345 # @return the list of integer values
2346 # @ingroup l1_meshinfo
2347 def GetSubMeshNodesId(self, Shape, all):
2348 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2349 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2352 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2354 ## Returns type of elements on given shape
2355 # @param Shape a geom object(sub-shape) IOR
2356 # Shape must be a sub-shape of a ShapeToMesh()
2357 # @return element type
2358 # @ingroup l1_meshinfo
2359 def GetSubMeshElementType(self, Shape):
2360 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2361 ShapeID = Shape.GetSubShapeIndices()[0]
2364 return self.mesh.GetSubMeshElementType(ShapeID)
2366 ## Gets the mesh description
2367 # @return string value
2368 # @ingroup l1_meshinfo
2370 return self.mesh.Dump()
2373 # Get the information about nodes and elements of a mesh by its IDs:
2374 # -----------------------------------------------------------
2376 ## Gets XYZ coordinates of a node
2377 # \n If there is no nodes for the given ID - returns an empty list
2378 # @return a list of double precision values
2379 # @ingroup l1_meshinfo
2380 def GetNodeXYZ(self, id):
2381 return self.mesh.GetNodeXYZ(id)
2383 ## Returns list of IDs of inverse elements for the given node
2384 # \n If there is no node for the given ID - returns an empty list
2385 # @return a list of integer values
2386 # @ingroup l1_meshinfo
2387 def GetNodeInverseElements(self, id):
2388 return self.mesh.GetNodeInverseElements(id)
2390 ## @brief Returns the position of a node on the shape
2391 # @return SMESH::NodePosition
2392 # @ingroup l1_meshinfo
2393 def GetNodePosition(self,NodeID):
2394 return self.mesh.GetNodePosition(NodeID)
2396 ## @brief Returns the position of an element on the shape
2397 # @return SMESH::ElementPosition
2398 # @ingroup l1_meshinfo
2399 def GetElementPosition(self,ElemID):
2400 return self.mesh.GetElementPosition(ElemID)
2402 ## If the given element is a node, returns the ID of shape
2403 # \n If there is no node for the given ID - returns -1
2404 # @return an integer value
2405 # @ingroup l1_meshinfo
2406 def GetShapeID(self, id):
2407 return self.mesh.GetShapeID(id)
2409 ## Returns the ID of the result shape after
2410 # FindShape() from SMESH_MeshEditor for the given element
2411 # \n If there is no element for the given ID - returns -1
2412 # @return an integer value
2413 # @ingroup l1_meshinfo
2414 def GetShapeIDForElem(self,id):
2415 return self.mesh.GetShapeIDForElem(id)
2417 ## Returns the number of nodes for the given element
2418 # \n If there is no element for the given ID - returns -1
2419 # @return an integer value
2420 # @ingroup l1_meshinfo
2421 def GetElemNbNodes(self, id):
2422 return self.mesh.GetElemNbNodes(id)
2424 ## Returns the node ID the given (zero based) index for the given element
2425 # \n If there is no element for the given ID - returns -1
2426 # \n If there is no node for the given index - returns -2
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2429 def GetElemNode(self, id, index):
2430 return self.mesh.GetElemNode(id, index)
2432 ## Returns the IDs of nodes of the given element
2433 # @return a list of integer values
2434 # @ingroup l1_meshinfo
2435 def GetElemNodes(self, id):
2436 return self.mesh.GetElemNodes(id)
2438 ## Returns true if the given node is the medium node in the given quadratic element
2439 # @ingroup l1_meshinfo
2440 def IsMediumNode(self, elementID, nodeID):
2441 return self.mesh.IsMediumNode(elementID, nodeID)
2443 ## Returns true if the given node is the medium node in one of quadratic elements
2444 # @ingroup l1_meshinfo
2445 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2446 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2448 ## Returns the number of edges for the given element
2449 # @ingroup l1_meshinfo
2450 def ElemNbEdges(self, id):
2451 return self.mesh.ElemNbEdges(id)
2453 ## Returns the number of faces for the given element
2454 # @ingroup l1_meshinfo
2455 def ElemNbFaces(self, id):
2456 return self.mesh.ElemNbFaces(id)
2458 ## Returns nodes of given face (counted from zero) for given volumic element.
2459 # @ingroup l1_meshinfo
2460 def GetElemFaceNodes(self,elemId, faceIndex):
2461 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2463 ## Returns three components of normal of given mesh face
2464 # (or an empty array in KO case)
2465 # @ingroup l1_meshinfo
2466 def GetFaceNormal(self, faceId, normalized=False):
2467 return self.mesh.GetFaceNormal(faceId,normalized)
2469 ## Returns an element based on all given nodes.
2470 # @ingroup l1_meshinfo
2471 def FindElementByNodes(self,nodes):
2472 return self.mesh.FindElementByNodes(nodes)
2474 ## Returns true if the given element is a polygon
2475 # @ingroup l1_meshinfo
2476 def IsPoly(self, id):
2477 return self.mesh.IsPoly(id)
2479 ## Returns true if the given element is quadratic
2480 # @ingroup l1_meshinfo
2481 def IsQuadratic(self, id):
2482 return self.mesh.IsQuadratic(id)
2484 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2485 # @ingroup l1_meshinfo
2486 def GetBallDiameter(self, id):
2487 return self.mesh.GetBallDiameter(id)
2489 ## Returns XYZ coordinates of the barycenter of the given element
2490 # \n If there is no element for the given ID - returns an empty list
2491 # @return a list of three double values
2492 # @ingroup l1_meshinfo
2493 def BaryCenter(self, id):
2494 return self.mesh.BaryCenter(id)
2496 ## Passes mesh elements through the given filter and return IDs of fitting elements
2497 # @param theFilter SMESH_Filter
2498 # @return a list of ids
2499 # @ingroup l1_controls
2500 def GetIdsFromFilter(self, theFilter):
2501 theFilter.SetMesh( self.mesh )
2502 return theFilter.GetIDs()
2504 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2505 # Returns a list of special structures (borders).
2506 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2507 # @ingroup l1_controls
2508 def GetFreeBorders(self):
2509 aFilterMgr = self.smeshpyD.CreateFilterManager()
2510 aPredicate = aFilterMgr.CreateFreeEdges()
2511 aPredicate.SetMesh(self.mesh)
2512 aBorders = aPredicate.GetBorders()
2513 aFilterMgr.UnRegister()
2517 # Get mesh measurements information:
2518 # ------------------------------------
2520 ## Get minimum distance between two nodes, elements or distance to the origin
2521 # @param id1 first node/element id
2522 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2523 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2524 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2525 # @return minimum distance value
2526 # @sa GetMinDistance()
2527 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2528 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2529 return aMeasure.value
2531 ## Get measure structure specifying minimum distance data between two objects
2532 # @param id1 first node/element id
2533 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2534 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2535 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2536 # @return Measure structure
2538 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2540 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2542 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2545 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2547 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2552 aMeasurements = self.smeshpyD.CreateMeasurements()
2553 aMeasure = aMeasurements.MinDistance(id1, id2)
2554 genObjUnRegister([aMeasurements,id1, id2])
2557 ## Get bounding box of the specified object(s)
2558 # @param objects single source object or list of source objects or list of nodes/elements IDs
2559 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2560 # @c False specifies that @a objects are nodes
2561 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2562 # @sa GetBoundingBox()
2563 def BoundingBox(self, objects=None, isElem=False):
2564 result = self.GetBoundingBox(objects, isElem)
2568 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2571 ## Get measure structure specifying bounding box data of the specified object(s)
2572 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2573 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2574 # @c False specifies that @a objects are nodes
2575 # @return Measure structure
2577 def GetBoundingBox(self, IDs=None, isElem=False):
2580 elif isinstance(IDs, tuple):
2582 if not isinstance(IDs, list):
2584 if len(IDs) > 0 and isinstance(IDs[0], int):
2587 unRegister = genObjUnRegister()
2589 if isinstance(o, Mesh):
2590 srclist.append(o.mesh)
2591 elif hasattr(o, "_narrow"):
2592 src = o._narrow(SMESH.SMESH_IDSource)
2593 if src: srclist.append(src)
2595 elif isinstance(o, list):
2597 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2599 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2600 unRegister.set( srclist[-1] )
2603 aMeasurements = self.smeshpyD.CreateMeasurements()
2604 unRegister.set( aMeasurements )
2605 aMeasure = aMeasurements.BoundingBox(srclist)
2608 # Mesh edition (SMESH_MeshEditor functionality):
2609 # ---------------------------------------------
2611 ## Removes the elements from the mesh by ids
2612 # @param IDsOfElements is a list of ids of elements to remove
2613 # @return True or False
2614 # @ingroup l2_modif_del
2615 def RemoveElements(self, IDsOfElements):
2616 return self.editor.RemoveElements(IDsOfElements)
2618 ## Removes nodes from mesh by ids
2619 # @param IDsOfNodes is a list of ids of nodes to remove
2620 # @return True or False
2621 # @ingroup l2_modif_del
2622 def RemoveNodes(self, IDsOfNodes):
2623 return self.editor.RemoveNodes(IDsOfNodes)
2625 ## Removes all orphan (free) nodes from mesh
2626 # @return number of the removed nodes
2627 # @ingroup l2_modif_del
2628 def RemoveOrphanNodes(self):
2629 return self.editor.RemoveOrphanNodes()
2631 ## Add a node to the mesh by coordinates
2632 # @return Id of the new node
2633 # @ingroup l2_modif_add
2634 def AddNode(self, x, y, z):
2635 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2636 if hasVars: self.mesh.SetParameters(Parameters)
2637 return self.editor.AddNode( x, y, z)
2639 ## Creates a 0D element on a node with given number.
2640 # @param IDOfNode the ID of node for creation of the element.
2641 # @return the Id of the new 0D element
2642 # @ingroup l2_modif_add
2643 def Add0DElement(self, IDOfNode):
2644 return self.editor.Add0DElement(IDOfNode)
2646 ## Create 0D elements on all nodes of the given elements except those
2647 # nodes on which a 0D element already exists.
2648 # @param theObject an object on whose nodes 0D elements will be created.
2649 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2650 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2651 # @param theGroupName optional name of a group to add 0D elements created
2652 # and/or found on nodes of \a theObject.
2653 # @return an object (a new group or a temporary SMESH_IDSource) holding
2654 # IDs of new and/or found 0D elements. IDs of 0D elements
2655 # can be retrieved from the returned object by calling GetIDs()
2656 # @ingroup l2_modif_add
2657 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2658 unRegister = genObjUnRegister()
2659 if isinstance( theObject, Mesh ):
2660 theObject = theObject.GetMesh()
2661 if isinstance( theObject, list ):
2662 theObject = self.GetIDSource( theObject, SMESH.ALL )
2663 unRegister.set( theObject )
2664 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2666 ## Creates a ball element on a node with given ID.
2667 # @param IDOfNode the ID of node for creation of the element.
2668 # @param diameter the bal diameter.
2669 # @return the Id of the new ball element
2670 # @ingroup l2_modif_add
2671 def AddBall(self, IDOfNode, diameter):
2672 return self.editor.AddBall( IDOfNode, diameter )
2674 ## Creates a linear or quadratic edge (this is determined
2675 # by the number of given nodes).
2676 # @param IDsOfNodes the list of node IDs for creation of the element.
2677 # The order of nodes in this list should correspond to the description
2678 # of MED. \n This description is located by the following link:
2679 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2680 # @return the Id of the new edge
2681 # @ingroup l2_modif_add
2682 def AddEdge(self, IDsOfNodes):
2683 return self.editor.AddEdge(IDsOfNodes)
2685 ## Creates a linear or quadratic face (this is determined
2686 # by the number of given nodes).
2687 # @param IDsOfNodes the list of node IDs for creation of the element.
2688 # The order of nodes in this list should correspond to the description
2689 # of MED. \n This description is located by the following link:
2690 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2691 # @return the Id of the new face
2692 # @ingroup l2_modif_add
2693 def AddFace(self, IDsOfNodes):
2694 return self.editor.AddFace(IDsOfNodes)
2696 ## Adds a polygonal face to the mesh by the list of node IDs
2697 # @param IdsOfNodes the list of node IDs for creation of the element.
2698 # @return the Id of the new face
2699 # @ingroup l2_modif_add
2700 def AddPolygonalFace(self, IdsOfNodes):
2701 return self.editor.AddPolygonalFace(IdsOfNodes)
2703 ## Creates both simple and quadratic volume (this is determined
2704 # by the number of given nodes).
2705 # @param IDsOfNodes the list of node IDs for creation of the element.
2706 # The order of nodes in this list should correspond to the description
2707 # of MED. \n This description is located by the following link:
2708 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2709 # @return the Id of the new volumic element
2710 # @ingroup l2_modif_add
2711 def AddVolume(self, IDsOfNodes):
2712 return self.editor.AddVolume(IDsOfNodes)
2714 ## Creates a volume of many faces, giving nodes for each face.
2715 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2716 # @param Quantities the list of integer values, Quantities[i]
2717 # gives the quantity of nodes in face number i.
2718 # @return the Id of the new volumic element
2719 # @ingroup l2_modif_add
2720 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2721 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2723 ## Creates a volume of many faces, giving the IDs of the existing faces.
2724 # @param IdsOfFaces the list of face IDs for volume creation.
2726 # Note: The created volume will refer only to the nodes
2727 # of the given faces, not to the faces themselves.
2728 # @return the Id of the new volumic element
2729 # @ingroup l2_modif_add
2730 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2731 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2734 ## @brief Binds a node to a vertex
2735 # @param NodeID a node ID
2736 # @param Vertex a vertex or vertex ID
2737 # @return True if succeed else raises an exception
2738 # @ingroup l2_modif_add
2739 def SetNodeOnVertex(self, NodeID, Vertex):
2740 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2741 VertexID = Vertex.GetSubShapeIndices()[0]
2745 self.editor.SetNodeOnVertex(NodeID, VertexID)
2746 except SALOME.SALOME_Exception, inst:
2747 raise ValueError, inst.details.text
2751 ## @brief Stores the node position on an edge
2752 # @param NodeID a node ID
2753 # @param Edge an edge or edge ID
2754 # @param paramOnEdge a parameter on the edge where the node is located
2755 # @return True if succeed else raises an exception
2756 # @ingroup l2_modif_add
2757 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2758 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2759 EdgeID = Edge.GetSubShapeIndices()[0]
2763 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2764 except SALOME.SALOME_Exception, inst:
2765 raise ValueError, inst.details.text
2768 ## @brief Stores node position on a face
2769 # @param NodeID a node ID
2770 # @param Face a face or face ID
2771 # @param u U parameter on the face where the node is located
2772 # @param v V parameter on the face where the node is located
2773 # @return True if succeed else raises an exception
2774 # @ingroup l2_modif_add
2775 def SetNodeOnFace(self, NodeID, Face, u, v):
2776 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2777 FaceID = Face.GetSubShapeIndices()[0]
2781 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2782 except SALOME.SALOME_Exception, inst:
2783 raise ValueError, inst.details.text
2786 ## @brief Binds a node to a solid
2787 # @param NodeID a node ID
2788 # @param Solid a solid or solid ID
2789 # @return True if succeed else raises an exception
2790 # @ingroup l2_modif_add
2791 def SetNodeInVolume(self, NodeID, Solid):
2792 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2793 SolidID = Solid.GetSubShapeIndices()[0]
2797 self.editor.SetNodeInVolume(NodeID, SolidID)
2798 except SALOME.SALOME_Exception, inst:
2799 raise ValueError, inst.details.text
2802 ## @brief Bind an element to a shape
2803 # @param ElementID an element ID
2804 # @param Shape a shape or shape ID
2805 # @return True if succeed else raises an exception
2806 # @ingroup l2_modif_add
2807 def SetMeshElementOnShape(self, ElementID, Shape):
2808 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2809 ShapeID = Shape.GetSubShapeIndices()[0]
2813 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2814 except SALOME.SALOME_Exception, inst:
2815 raise ValueError, inst.details.text
2819 ## Moves the node with the given id
2820 # @param NodeID the id of the node
2821 # @param x a new X coordinate
2822 # @param y a new Y coordinate
2823 # @param z a new Z coordinate
2824 # @return True if succeed else False
2825 # @ingroup l2_modif_movenode
2826 def MoveNode(self, NodeID, x, y, z):
2827 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2828 if hasVars: self.mesh.SetParameters(Parameters)
2829 return self.editor.MoveNode(NodeID, x, y, z)
2831 ## Finds the node closest to a point and moves it to a point location
2832 # @param x the X coordinate of a point
2833 # @param y the Y coordinate of a point
2834 # @param z the Z coordinate of a point
2835 # @param NodeID if specified (>0), the node with this ID is moved,
2836 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2837 # @return the ID of a node
2838 # @ingroup l2_modif_throughp
2839 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2840 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2841 if hasVars: self.mesh.SetParameters(Parameters)
2842 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2844 ## Finds the node closest to a point
2845 # @param x the X coordinate of a point
2846 # @param y the Y coordinate of a point
2847 # @param z the Z coordinate of a point
2848 # @return the ID of a node
2849 # @ingroup l2_modif_throughp
2850 def FindNodeClosestTo(self, x, y, z):
2851 #preview = self.mesh.GetMeshEditPreviewer()
2852 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2853 return self.editor.FindNodeClosestTo(x, y, z)
2855 ## Finds the elements where a point lays IN or ON
2856 # @param x the X coordinate of a point
2857 # @param y the Y coordinate of a point
2858 # @param z the Z coordinate of a point
2859 # @param elementType type of elements to find (SMESH.ALL type
2860 # means elements of any type excluding nodes, discrete and 0D elements)
2861 # @param meshPart a part of mesh (group, sub-mesh) to search within
2862 # @return list of IDs of found elements
2863 # @ingroup l2_modif_throughp
2864 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2866 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2868 return self.editor.FindElementsByPoint(x, y, z, elementType)
2870 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2871 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2872 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2874 def GetPointState(self, x, y, z):
2875 return self.editor.GetPointState(x, y, z)
2877 ## Finds the node closest to a point and moves it to a point location
2878 # @param x the X coordinate of a point
2879 # @param y the Y coordinate of a point
2880 # @param z the Z coordinate of a point
2881 # @return the ID of a moved node
2882 # @ingroup l2_modif_throughp
2883 def MeshToPassThroughAPoint(self, x, y, z):
2884 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2886 ## Replaces two neighbour triangles sharing Node1-Node2 link
2887 # with the triangles built on the same 4 nodes but having other common link.
2888 # @param NodeID1 the ID of the first node
2889 # @param NodeID2 the ID of the second node
2890 # @return false if proper faces were not found
2891 # @ingroup l2_modif_invdiag
2892 def InverseDiag(self, NodeID1, NodeID2):
2893 return self.editor.InverseDiag(NodeID1, NodeID2)
2895 ## Replaces two neighbour triangles sharing Node1-Node2 link
2896 # with a quadrangle built on the same 4 nodes.
2897 # @param NodeID1 the ID of the first node
2898 # @param NodeID2 the ID of the second node
2899 # @return false if proper faces were not found
2900 # @ingroup l2_modif_unitetri
2901 def DeleteDiag(self, NodeID1, NodeID2):
2902 return self.editor.DeleteDiag(NodeID1, NodeID2)
2904 ## Reorients elements by ids
2905 # @param IDsOfElements if undefined reorients all mesh elements
2906 # @return True if succeed else False
2907 # @ingroup l2_modif_changori
2908 def Reorient(self, IDsOfElements=None):
2909 if IDsOfElements == None:
2910 IDsOfElements = self.GetElementsId()
2911 return self.editor.Reorient(IDsOfElements)