1 # Copyright (C) 2007-2016 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_segmarv Segments around Vertex
36 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
39 ## @defgroup l2_hypotheses Defining hypotheses
41 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
42 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
43 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
44 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
45 ## @defgroup l3_hypos_additi Additional Hypotheses
48 ## @defgroup l2_submeshes Constructing submeshes
49 ## @defgroup l2_compounds Building Compounds
50 ## @defgroup l2_editing Editing Meshes
53 ## @defgroup l1_meshinfo Mesh Information
54 ## @defgroup l1_controls Quality controls and Filtering
55 ## @defgroup l1_grouping Grouping elements
57 ## @defgroup l2_grps_create Creating groups
58 ## @defgroup l2_grps_edit Editing groups
59 ## @defgroup l2_grps_operon Using operations on groups
60 ## @defgroup l2_grps_delete Deleting Groups
63 ## @defgroup l1_modifying Modifying meshes
65 ## @defgroup l2_modif_add Adding nodes and elements
66 ## @defgroup l2_modif_del Removing nodes and elements
67 ## @defgroup l2_modif_edit Modifying nodes and elements
68 ## @defgroup l2_modif_renumber Renumbering nodes and elements
69 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
70 ## @defgroup l2_modif_movenode Moving nodes
71 ## @defgroup l2_modif_throughp Mesh through point
72 ## @defgroup l2_modif_unitetri Uniting triangles
73 ## @defgroup l2_modif_cutquadr Cutting elements
74 ## @defgroup l2_modif_changori Changing orientation of elements
75 ## @defgroup l2_modif_smooth Smoothing
76 ## @defgroup l2_modif_extrurev Extrusion and Revolution
77 ## @defgroup l2_modif_patterns Pattern mapping
78 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
81 ## @defgroup l1_measurements Measurements
84 from salome.geom import geomBuilder
86 import SMESH # This is necessary for back compatibility
88 from salome.smesh.smesh_algorithm import Mesh_Algorithm
95 def __instancecheck__(cls, inst):
96 """Implement isinstance(inst, cls)."""
97 return any(cls.__subclasscheck__(c)
98 for c in {type(inst), inst.__class__})
100 def __subclasscheck__(cls, sub):
101 """Implement issubclass(sub, cls)."""
102 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
104 ## @addtogroup l1_auxiliary
107 ## Converts an angle from degrees to radians
108 def DegreesToRadians(AngleInDegrees):
110 return AngleInDegrees * pi / 180.0
112 import salome_notebook
113 notebook = salome_notebook.notebook
114 # Salome notebook variable separator
117 ## Return list of variable values from salome notebook.
118 # The last argument, if is callable, is used to modify values got from notebook
119 def ParseParameters(*args):
124 if args and callable( args[-1] ):
125 args, varModifFun = args[:-1], args[-1]
126 for parameter in args:
128 Parameters += str(parameter) + var_separator
130 if isinstance(parameter,str):
131 # check if there is an inexistent variable name
132 if not notebook.isVariable(parameter):
133 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
134 parameter = notebook.get(parameter)
137 parameter = varModifFun(parameter)
140 Result.append(parameter)
143 Parameters = Parameters[:-1]
144 Result.append( Parameters )
145 Result.append( hasVariables )
148 # Parse parameters converting variables to radians
149 def ParseAngles(*args):
150 return ParseParameters( *( args + (DegreesToRadians, )))
152 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
153 # Parameters are stored in PointStruct.parameters attribute
154 def __initPointStruct(point,*args):
155 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
157 SMESH.PointStruct.__init__ = __initPointStruct
159 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
160 # Parameters are stored in AxisStruct.parameters attribute
161 def __initAxisStruct(ax,*args):
164 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
165 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
167 SMESH.AxisStruct.__init__ = __initAxisStruct
169 smeshPrecisionConfusion = 1.e-07
170 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
171 if abs(val1 - val2) < tol:
181 if isinstance(obj, SALOMEDS._objref_SObject):
185 ior = salome.orb.object_to_string(obj)
190 studies = salome.myStudyManager.GetOpenStudies()
191 for sname in studies:
192 s = salome.myStudyManager.GetStudyByName(sname)
194 sobj = s.FindObjectIOR(ior)
195 if not sobj: continue
196 return sobj.GetName()
197 if hasattr(obj, "GetName"):
198 # unknown CORBA object, having GetName() method
201 # unknown CORBA object, no GetName() method
204 if hasattr(obj, "GetName"):
205 # unknown non-CORBA object, having GetName() method
208 raise RuntimeError, "Null or invalid object"
210 ## Prints error message if a hypothesis was not assigned.
211 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
213 hypType = "algorithm"
215 hypType = "hypothesis"
218 if hasattr( status, "__getitem__" ):
219 status,reason = status[0],status[1]
220 if status == HYP_UNKNOWN_FATAL :
221 reason = "for unknown reason"
222 elif status == HYP_INCOMPATIBLE :
223 reason = "this hypothesis mismatches the algorithm"
224 elif status == HYP_NOTCONFORM :
225 reason = "a non-conform mesh would be built"
226 elif status == HYP_ALREADY_EXIST :
227 if isAlgo: return # it does not influence anything
228 reason = hypType + " of the same dimension is already assigned to this shape"
229 elif status == HYP_BAD_DIM :
230 reason = hypType + " mismatches the shape"
231 elif status == HYP_CONCURENT :
232 reason = "there are concurrent hypotheses on sub-shapes"
233 elif status == HYP_BAD_SUBSHAPE :
234 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
235 elif status == HYP_BAD_GEOMETRY:
236 reason = "the algorithm is not applicable to this geometry"
237 elif status == HYP_HIDDEN_ALGO:
238 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
239 elif status == HYP_HIDING_ALGO:
240 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
241 elif status == HYP_NEED_SHAPE:
242 reason = "algorithm can't work without shape"
243 elif status == HYP_INCOMPAT_HYPS:
249 where = '"%s"' % geomName
251 meshName = GetName( mesh )
252 if meshName and meshName != NO_NAME:
253 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
254 if status < HYP_UNKNOWN_FATAL and where:
255 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
257 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
259 print '"%s" was not assigned : %s' %( hypName, reason )
262 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
263 def AssureGeomPublished(mesh, geom, name=''):
264 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
266 if not geom.GetStudyEntry() and \
267 mesh.smeshpyD.GetCurrentStudy():
269 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
270 if studyID != mesh.geompyD.myStudyId:
271 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
273 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
274 # for all groups SubShapeName() returns "Compound_-1"
275 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
277 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
279 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
282 ## Return the first vertex of a geometrical edge by ignoring orientation
283 def FirstVertexOnCurve(mesh, edge):
284 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
286 raise TypeError, "Given object has no vertices"
287 if len( vv ) == 1: return vv[0]
288 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
289 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
290 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
291 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
294 dist1 += abs( xyz[i] - xyz1[i] )
295 dist2 += abs( xyz[i] - xyz2[i] )
301 # end of l1_auxiliary
305 # Warning: smeshInst is a singleton
311 ## This class allows to create, load or manipulate meshes.
312 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
313 # It also has methods to get infos and measure meshes.
314 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
316 # MirrorType enumeration
317 POINT = SMESH_MeshEditor.POINT
318 AXIS = SMESH_MeshEditor.AXIS
319 PLANE = SMESH_MeshEditor.PLANE
321 # Smooth_Method enumeration
322 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
323 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
325 PrecisionConfusion = smeshPrecisionConfusion
327 # TopAbs_State enumeration
328 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
330 # Methods of splitting a hexahedron into tetrahedra
331 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
337 #print "==== __new__", engine, smeshInst, doLcc
339 if smeshInst is None:
340 # smesh engine is either retrieved from engine, or created
342 # Following test avoids a recursive loop
344 if smeshInst is not None:
345 # smesh engine not created: existing engine found
349 # FindOrLoadComponent called:
350 # 1. CORBA resolution of server
351 # 2. the __new__ method is called again
352 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
353 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
355 # FindOrLoadComponent not called
356 if smeshInst is None:
357 # smeshBuilder instance is created from lcc.FindOrLoadComponent
358 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
359 smeshInst = super(smeshBuilder,cls).__new__(cls)
361 # smesh engine not created: existing engine found
362 #print "==== existing ", engine, smeshInst, doLcc
364 #print "====1 ", smeshInst
367 #print "====2 ", smeshInst
372 #print "--------------- smeshbuilder __init__ ---", created
375 SMESH._objref_SMESH_Gen.__init__(self)
377 ## Dump component to the Python script
378 # This method overrides IDL function to allow default values for the parameters.
379 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
380 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
382 ## Set mode of DumpPython(), \a historical or \a snapshot.
383 # In the \a historical mode, the Python Dump script includes all commands
384 # performed by SMESH engine. In the \a snapshot mode, commands
385 # relating to objects removed from the Study are excluded from the script
386 # as well as commands not influencing the current state of meshes
387 def SetDumpPythonHistorical(self, isHistorical):
388 if isHistorical: val = "true"
390 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
392 ## Sets the current study and Geometry component
393 # @ingroup l1_auxiliary
394 def init_smesh(self,theStudy,geompyD = None):
396 self.SetCurrentStudy(theStudy,geompyD)
399 notebook.myStudy = theStudy
401 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
402 # or a mesh wrapping a CORBA mesh given as a parameter.
403 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
404 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
405 # (2) a Geometrical object for meshing or
407 # @param name the name for the new mesh.
408 # @return an instance of Mesh class.
409 # @ingroup l2_construct
410 def Mesh(self, obj=0, name=0):
411 if isinstance(obj,str):
413 return Mesh(self,self.geompyD,obj,name)
415 ## Returns a long value from enumeration
416 # @ingroup l1_controls
417 def EnumToLong(self,theItem):
420 ## Returns a string representation of the color.
421 # To be used with filters.
422 # @param c color value (SALOMEDS.Color)
423 # @ingroup l1_controls
424 def ColorToString(self,c):
426 if isinstance(c, SALOMEDS.Color):
427 val = "%s;%s;%s" % (c.R, c.G, c.B)
428 elif isinstance(c, str):
431 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
434 ## Gets PointStruct from vertex
435 # @param theVertex a GEOM object(vertex)
436 # @return SMESH.PointStruct
437 # @ingroup l1_auxiliary
438 def GetPointStruct(self,theVertex):
439 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
440 return PointStruct(x,y,z)
442 ## Gets DirStruct from vector
443 # @param theVector a GEOM object(vector)
444 # @return SMESH.DirStruct
445 # @ingroup l1_auxiliary
446 def GetDirStruct(self,theVector):
447 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
448 if(len(vertices) != 2):
449 print "Error: vector object is incorrect."
451 p1 = self.geompyD.PointCoordinates(vertices[0])
452 p2 = self.geompyD.PointCoordinates(vertices[1])
453 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
454 dirst = DirStruct(pnt)
457 ## Makes DirStruct from a triplet
458 # @param x,y,z vector components
459 # @return SMESH.DirStruct
460 # @ingroup l1_auxiliary
461 def MakeDirStruct(self,x,y,z):
462 pnt = PointStruct(x,y,z)
463 return DirStruct(pnt)
465 ## Get AxisStruct from object
466 # @param theObj a GEOM object (line or plane)
467 # @return SMESH.AxisStruct
468 # @ingroup l1_auxiliary
469 def GetAxisStruct(self,theObj):
471 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
474 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
475 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
476 vertex1 = self.geompyD.PointCoordinates(vertex1)
477 vertex2 = self.geompyD.PointCoordinates(vertex2)
478 vertex3 = self.geompyD.PointCoordinates(vertex3)
479 vertex4 = self.geompyD.PointCoordinates(vertex4)
480 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
481 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
482 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] ]
483 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
484 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
485 elif len(edges) == 1:
486 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
487 p1 = self.geompyD.PointCoordinates( vertex1 )
488 p2 = self.geompyD.PointCoordinates( vertex2 )
489 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
490 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
491 elif theObj.GetShapeType() == GEOM.VERTEX:
492 x,y,z = self.geompyD.PointCoordinates( theObj )
493 axis = AxisStruct( x,y,z, 1,0,0,)
494 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
497 # From SMESH_Gen interface:
498 # ------------------------
500 ## Sets the given name to the object
501 # @param obj the object to rename
502 # @param name a new object name
503 # @ingroup l1_auxiliary
504 def SetName(self, obj, name):
505 if isinstance( obj, Mesh ):
507 elif isinstance( obj, Mesh_Algorithm ):
508 obj = obj.GetAlgorithm()
509 ior = salome.orb.object_to_string(obj)
510 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
512 ## Sets the current mode
513 # @ingroup l1_auxiliary
514 def SetEmbeddedMode( self,theMode ):
515 #self.SetEmbeddedMode(theMode)
516 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
518 ## Gets the current mode
519 # @ingroup l1_auxiliary
520 def IsEmbeddedMode(self):
521 #return self.IsEmbeddedMode()
522 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
524 ## Sets the current study. Calling SetCurrentStudy( None ) allows to
525 # switch OFF automatic pubilishing in the Study of mesh objects.
526 # @ingroup l1_auxiliary
527 def SetCurrentStudy( self, theStudy, geompyD = None ):
528 #self.SetCurrentStudy(theStudy)
530 from salome.geom import geomBuilder
531 geompyD = geomBuilder.geom
534 self.SetGeomEngine(geompyD)
535 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
538 notebook = salome_notebook.NoteBook( theStudy )
540 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
542 sb = theStudy.NewBuilder()
543 sc = theStudy.FindComponent("SMESH")
544 if sc: sb.LoadWith(sc, self)
548 ## Gets the current study
549 # @ingroup l1_auxiliary
550 def GetCurrentStudy(self):
551 #return self.GetCurrentStudy()
552 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
554 ## Creates a Mesh object importing data from the given UNV file
555 # @return an instance of Mesh class
557 def CreateMeshesFromUNV( self,theFileName ):
558 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
559 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
562 ## Creates a Mesh object(s) importing data from the given MED file
563 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
565 def CreateMeshesFromMED( self,theFileName ):
566 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
567 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
568 return aMeshes, aStatus
570 ## Creates a Mesh object(s) importing data from the given SAUV file
571 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
573 def CreateMeshesFromSAUV( self,theFileName ):
574 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
575 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
576 return aMeshes, aStatus
578 ## Creates a Mesh object importing data from the given STL file
579 # @return an instance of Mesh class
581 def CreateMeshesFromSTL( self, theFileName ):
582 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
583 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
586 ## Creates Mesh objects importing data from the given CGNS file
587 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
589 def CreateMeshesFromCGNS( self, theFileName ):
590 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
591 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
592 return aMeshes, aStatus
594 ## Creates a Mesh object importing data from the given GMF file.
595 # GMF files must have .mesh extension for the ASCII format and .meshb for
597 # @return [ an instance of Mesh class, SMESH.ComputeError ]
599 def CreateMeshesFromGMF( self, theFileName ):
600 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
603 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
604 return Mesh(self, self.geompyD, aSmeshMesh), error
606 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
607 # present in the new mesh.
608 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
609 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
610 # @param mergeNodesAndElements if true, equal nodes and elements are merged
611 # @param mergeTolerance tolerance for merging nodes
612 # @param allGroups forces creation of groups corresponding to every input mesh
613 # @param name name of a new mesh
614 # @return an instance of Mesh class
615 # @ingroup l2_compounds
616 def Concatenate( self, meshes, uniteIdenticalGroups,
617 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
619 if not meshes: return None
620 for i,m in enumerate(meshes):
621 if isinstance(m, Mesh):
622 meshes[i] = m.GetMesh()
623 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
624 meshes[0].SetParameters(Parameters)
626 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
627 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
629 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
630 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
631 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
634 ## Create a mesh by copying a part of another mesh.
635 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
636 # to copy nodes or elements not contained in any mesh object,
637 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
638 # @param meshName a name of the new mesh
639 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
640 # @param toKeepIDs to preserve order of the copied elements or not
641 # @return an instance of Mesh class
642 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
643 if (isinstance( meshPart, Mesh )):
644 meshPart = meshPart.GetMesh()
645 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
646 return Mesh(self, self.geompyD, mesh)
648 ## From SMESH_Gen interface
649 # @return the list of integer values
650 # @ingroup l1_auxiliary
651 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
652 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
654 ## From SMESH_Gen interface. Creates a pattern
655 # @return an instance of SMESH_Pattern
657 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
658 # @ingroup l2_modif_patterns
659 def GetPattern(self):
660 return SMESH._objref_SMESH_Gen.GetPattern(self)
662 ## Sets number of segments per diagonal of boundary box of geometry by which
663 # default segment length of appropriate 1D hypotheses is defined.
664 # Default value is 10
665 # @ingroup l1_auxiliary
666 def SetBoundaryBoxSegmentation(self, nbSegments):
667 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
669 # Filtering. Auxiliary functions:
670 # ------------------------------
672 ## Creates an empty criterion
673 # @return SMESH.Filter.Criterion
674 # @ingroup l1_controls
675 def GetEmptyCriterion(self):
676 Type = self.EnumToLong(FT_Undefined)
677 Compare = self.EnumToLong(FT_Undefined)
681 UnaryOp = self.EnumToLong(FT_Undefined)
682 BinaryOp = self.EnumToLong(FT_Undefined)
685 Precision = -1 ##@1e-07
686 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
687 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
689 ## Creates a criterion by the given parameters
690 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
691 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
692 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
693 # Type SMESH.FunctorType._items in the Python Console to see all values.
694 # Note that the items starting from FT_LessThan are not suitable for CritType.
695 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
696 # @param Threshold the threshold value (range of ids as string, shape, numeric)
697 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
698 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
700 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
701 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
702 # @return SMESH.Filter.Criterion
704 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
705 # @ingroup l1_controls
706 def GetCriterion(self,elementType,
708 Compare = FT_EqualTo,
710 UnaryOp=FT_Undefined,
711 BinaryOp=FT_Undefined,
713 if not CritType in SMESH.FunctorType._items:
714 raise TypeError, "CritType should be of SMESH.FunctorType"
715 aCriterion = self.GetEmptyCriterion()
716 aCriterion.TypeOfElement = elementType
717 aCriterion.Type = self.EnumToLong(CritType)
718 aCriterion.Tolerance = Tolerance
720 aThreshold = Threshold
722 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
723 aCriterion.Compare = self.EnumToLong(Compare)
724 elif Compare == "=" or Compare == "==":
725 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
727 aCriterion.Compare = self.EnumToLong(FT_LessThan)
729 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
730 elif Compare != FT_Undefined:
731 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
734 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
735 FT_BelongToCylinder, FT_LyingOnGeom]:
736 # Check that Threshold is GEOM object
737 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
738 aCriterion.ThresholdStr = GetName(aThreshold)
739 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
740 if not aCriterion.ThresholdID:
741 name = aCriterion.ThresholdStr
743 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
744 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
745 # or a name of GEOM object
746 elif isinstance( aThreshold, str ):
747 aCriterion.ThresholdStr = aThreshold
749 raise TypeError, "The Threshold should be a shape."
750 if isinstance(UnaryOp,float):
751 aCriterion.Tolerance = UnaryOp
752 UnaryOp = FT_Undefined
754 elif CritType == FT_BelongToMeshGroup:
755 # Check that Threshold is a group
756 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
757 if aThreshold.GetType() != elementType:
758 raise ValueError, "Group type mismatches Element type"
759 aCriterion.ThresholdStr = aThreshold.GetName()
760 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
761 study = self.GetCurrentStudy()
763 so = study.FindObjectIOR( aCriterion.ThresholdID )
767 aCriterion.ThresholdID = entry
769 raise TypeError, "The Threshold should be a Mesh Group"
770 elif CritType == FT_RangeOfIds:
771 # Check that Threshold is string
772 if isinstance(aThreshold, str):
773 aCriterion.ThresholdStr = aThreshold
775 raise TypeError, "The Threshold should be a string."
776 elif CritType == FT_CoplanarFaces:
777 # Check the Threshold
778 if isinstance(aThreshold, int):
779 aCriterion.ThresholdID = str(aThreshold)
780 elif isinstance(aThreshold, str):
783 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
784 aCriterion.ThresholdID = aThreshold
787 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
788 elif CritType == FT_ConnectedElements:
789 # Check the Threshold
790 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
791 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
792 if not aCriterion.ThresholdID:
793 name = aThreshold.GetName()
795 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
796 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
797 elif isinstance(aThreshold, int): # node id
798 aCriterion.Threshold = aThreshold
799 elif isinstance(aThreshold, list): # 3 point coordinates
800 if len( aThreshold ) < 3:
801 raise ValueError, "too few point coordinates, must be 3"
802 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
803 elif isinstance(aThreshold, str):
804 if aThreshold.isdigit():
805 aCriterion.Threshold = aThreshold # node id
807 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
810 "The Threshold should either a VERTEX, or a node ID, "\
811 "or a list of point coordinates and not '%s'"%aThreshold
812 elif CritType == FT_ElemGeomType:
813 # Check the Threshold
815 aCriterion.Threshold = self.EnumToLong(aThreshold)
816 assert( aThreshold in SMESH.GeometryType._items )
818 if isinstance(aThreshold, int):
819 aCriterion.Threshold = aThreshold
821 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
824 elif CritType == FT_EntityType:
825 # Check the Threshold
827 aCriterion.Threshold = self.EnumToLong(aThreshold)
828 assert( aThreshold in SMESH.EntityType._items )
830 if isinstance(aThreshold, int):
831 aCriterion.Threshold = aThreshold
833 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
837 elif CritType == FT_GroupColor:
838 # Check the Threshold
840 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
842 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
844 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
845 FT_LinearOrQuadratic, FT_BadOrientedVolume,
846 FT_BareBorderFace, FT_BareBorderVolume,
847 FT_OverConstrainedFace, FT_OverConstrainedVolume,
848 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
849 # At this point the Threshold is unnecessary
850 if aThreshold == FT_LogicalNOT:
851 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
852 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
853 aCriterion.BinaryOp = aThreshold
857 aThreshold = float(aThreshold)
858 aCriterion.Threshold = aThreshold
860 raise TypeError, "The Threshold should be a number."
863 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
864 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
866 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
867 aCriterion.BinaryOp = self.EnumToLong(Threshold)
869 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
870 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
872 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
873 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
877 ## Creates a filter with the given parameters
878 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
879 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
880 # Type SMESH.FunctorType._items in the Python Console to see all values.
881 # Note that the items starting from FT_LessThan are not suitable for CritType.
882 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
883 # @param Threshold the threshold value (range of ids as string, shape, numeric)
884 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
885 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
886 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
887 # @param mesh the mesh to initialize the filter with
888 # @return SMESH_Filter
890 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
891 # @ingroup l1_controls
892 def GetFilter(self,elementType,
893 CritType=FT_Undefined,
896 UnaryOp=FT_Undefined,
899 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
900 aFilterMgr = self.CreateFilterManager()
901 aFilter = aFilterMgr.CreateFilter()
903 aCriteria.append(aCriterion)
904 aFilter.SetCriteria(aCriteria)
906 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
907 else : aFilter.SetMesh( mesh )
908 aFilterMgr.UnRegister()
911 ## Creates a filter from criteria
912 # @param criteria a list of criteria
913 # @param binOp binary operator used when binary operator of criteria is undefined
914 # @return SMESH_Filter
916 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
917 # @ingroup l1_controls
918 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
919 for i in range( len( criteria ) - 1 ):
920 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
921 criteria[i].BinaryOp = self.EnumToLong( binOp )
922 aFilterMgr = self.CreateFilterManager()
923 aFilter = aFilterMgr.CreateFilter()
924 aFilter.SetCriteria(criteria)
925 aFilterMgr.UnRegister()
928 ## Creates a numerical functor by its type
929 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
930 # Type SMESH.FunctorType._items in the Python Console to see all items.
931 # Note that not all items correspond to numerical functors.
932 # @return SMESH_NumericalFunctor
933 # @ingroup l1_controls
934 def GetFunctor(self,theCriterion):
935 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
937 aFilterMgr = self.CreateFilterManager()
939 if theCriterion == FT_AspectRatio:
940 functor = aFilterMgr.CreateAspectRatio()
941 elif theCriterion == FT_AspectRatio3D:
942 functor = aFilterMgr.CreateAspectRatio3D()
943 elif theCriterion == FT_Warping:
944 functor = aFilterMgr.CreateWarping()
945 elif theCriterion == FT_MinimumAngle:
946 functor = aFilterMgr.CreateMinimumAngle()
947 elif theCriterion == FT_Taper:
948 functor = aFilterMgr.CreateTaper()
949 elif theCriterion == FT_Skew:
950 functor = aFilterMgr.CreateSkew()
951 elif theCriterion == FT_Area:
952 functor = aFilterMgr.CreateArea()
953 elif theCriterion == FT_Volume3D:
954 functor = aFilterMgr.CreateVolume3D()
955 elif theCriterion == FT_MaxElementLength2D:
956 functor = aFilterMgr.CreateMaxElementLength2D()
957 elif theCriterion == FT_MaxElementLength3D:
958 functor = aFilterMgr.CreateMaxElementLength3D()
959 elif theCriterion == FT_MultiConnection:
960 functor = aFilterMgr.CreateMultiConnection()
961 elif theCriterion == FT_MultiConnection2D:
962 functor = aFilterMgr.CreateMultiConnection2D()
963 elif theCriterion == FT_Length:
964 functor = aFilterMgr.CreateLength()
965 elif theCriterion == FT_Length2D:
966 functor = aFilterMgr.CreateLength2D()
968 print "Error: given parameter is not numerical functor type."
969 aFilterMgr.UnRegister()
972 ## Creates hypothesis
973 # @param theHType mesh hypothesis type (string)
974 # @param theLibName mesh plug-in library name
975 # @return created hypothesis instance
976 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
977 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
979 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
982 # wrap hypothesis methods
983 #print "HYPOTHESIS", theHType
984 for meth_name in dir( hyp.__class__ ):
985 if not meth_name.startswith("Get") and \
986 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
987 method = getattr ( hyp.__class__, meth_name )
989 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
993 ## Gets the mesh statistic
994 # @return dictionary "element type" - "count of elements"
995 # @ingroup l1_meshinfo
996 def GetMeshInfo(self, obj):
997 if isinstance( obj, Mesh ):
1000 if hasattr(obj, "GetMeshInfo"):
1001 values = obj.GetMeshInfo()
1002 for i in range(SMESH.Entity_Last._v):
1003 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1007 ## Get minimum distance between two objects
1009 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1010 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1012 # @param src1 first source object
1013 # @param src2 second source object
1014 # @param id1 node/element id from the first source
1015 # @param id2 node/element id from the second (or first) source
1016 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1017 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1018 # @return minimum distance value
1019 # @sa GetMinDistance()
1020 # @ingroup l1_measurements
1021 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1022 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1026 result = result.value
1029 ## Get measure structure specifying minimum distance data between two objects
1031 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1032 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1034 # @param src1 first source object
1035 # @param src2 second source object
1036 # @param id1 node/element id from the first source
1037 # @param id2 node/element id from the second (or first) source
1038 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1039 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1040 # @return Measure structure or None if input data is invalid
1042 # @ingroup l1_measurements
1043 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1044 if isinstance(src1, Mesh): src1 = src1.mesh
1045 if isinstance(src2, Mesh): src2 = src2.mesh
1046 if src2 is None and id2 != 0: src2 = src1
1047 if not hasattr(src1, "_narrow"): return None
1048 src1 = src1._narrow(SMESH.SMESH_IDSource)
1049 if not src1: return None
1050 unRegister = genObjUnRegister()
1053 e = m.GetMeshEditor()
1055 src1 = e.MakeIDSource([id1], SMESH.FACE)
1057 src1 = e.MakeIDSource([id1], SMESH.NODE)
1058 unRegister.set( src1 )
1060 if hasattr(src2, "_narrow"):
1061 src2 = src2._narrow(SMESH.SMESH_IDSource)
1062 if src2 and id2 != 0:
1064 e = m.GetMeshEditor()
1066 src2 = e.MakeIDSource([id2], SMESH.FACE)
1068 src2 = e.MakeIDSource([id2], SMESH.NODE)
1069 unRegister.set( src2 )
1072 aMeasurements = self.CreateMeasurements()
1073 unRegister.set( aMeasurements )
1074 result = aMeasurements.MinDistance(src1, src2)
1077 ## Get bounding box of the specified object(s)
1078 # @param objects single source object or list of source objects
1079 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1080 # @sa GetBoundingBox()
1081 # @ingroup l1_measurements
1082 def BoundingBox(self, objects):
1083 result = self.GetBoundingBox(objects)
1087 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1090 ## Get measure structure specifying bounding box data of the specified object(s)
1091 # @param objects single source object or list of source objects
1092 # @return Measure structure
1094 # @ingroup l1_measurements
1095 def GetBoundingBox(self, objects):
1096 if isinstance(objects, tuple):
1097 objects = list(objects)
1098 if not isinstance(objects, list):
1102 if isinstance(o, Mesh):
1103 srclist.append(o.mesh)
1104 elif hasattr(o, "_narrow"):
1105 src = o._narrow(SMESH.SMESH_IDSource)
1106 if src: srclist.append(src)
1109 aMeasurements = self.CreateMeasurements()
1110 result = aMeasurements.BoundingBox(srclist)
1111 aMeasurements.UnRegister()
1114 ## Get sum of lengths of all 1D elements in the mesh object.
1115 # @param obj mesh, submesh or group
1116 # @return sum of lengths of all 1D elements
1117 # @ingroup l1_measurements
1118 def GetLength(self, obj):
1119 if isinstance(obj, Mesh): obj = obj.mesh
1120 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1121 aMeasurements = self.CreateMeasurements()
1122 value = aMeasurements.Length(obj)
1123 aMeasurements.UnRegister()
1126 ## Get sum of areas of all 2D elements in the mesh object.
1127 # @param obj mesh, submesh or group
1128 # @return sum of areas of all 2D elements
1129 # @ingroup l1_measurements
1130 def GetArea(self, obj):
1131 if isinstance(obj, Mesh): obj = obj.mesh
1132 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1133 aMeasurements = self.CreateMeasurements()
1134 value = aMeasurements.Area(obj)
1135 aMeasurements.UnRegister()
1138 ## Get sum of volumes of all 3D elements in the mesh object.
1139 # @param obj mesh, submesh or group
1140 # @return sum of volumes of all 3D elements
1141 # @ingroup l1_measurements
1142 def GetVolume(self, obj):
1143 if isinstance(obj, Mesh): obj = obj.mesh
1144 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1145 aMeasurements = self.CreateMeasurements()
1146 value = aMeasurements.Volume(obj)
1147 aMeasurements.UnRegister()
1150 pass # end of class smeshBuilder
1153 #Registering the new proxy for SMESH_Gen
1154 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1156 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1157 # interface to create or load meshes.
1162 # salome.salome_init()
1163 # from salome.smesh import smeshBuilder
1164 # smesh = smeshBuilder.New(salome.myStudy)
1166 # @param study SALOME study, generally obtained by salome.myStudy.
1167 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1168 # @return smeshBuilder instance
1170 def New( study, instance=None):
1172 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1173 interface to create or load meshes.
1177 salome.salome_init()
1178 from salome.smesh import smeshBuilder
1179 smesh = smeshBuilder.New(salome.myStudy)
1182 study SALOME study, generally obtained by salome.myStudy.
1183 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1185 smeshBuilder instance
1193 smeshInst = smeshBuilder()
1194 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1195 smeshInst.init_smesh(study)
1199 # Public class: Mesh
1200 # ==================
1202 ## This class allows defining and managing a mesh.
1203 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1204 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1205 # new nodes and elements and by changing the existing entities), to get information
1206 # about a mesh and to export a mesh into different formats.
1208 __metaclass__ = MeshMeta
1216 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1217 # sets the GUI name of this mesh to \a name.
1218 # @param smeshpyD an instance of smeshBuilder class
1219 # @param geompyD an instance of geomBuilder class
1220 # @param obj Shape to be meshed or SMESH_Mesh object
1221 # @param name Study name of the mesh
1222 # @ingroup l2_construct
1223 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1224 self.smeshpyD=smeshpyD
1225 self.geompyD=geompyD
1230 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1233 # publish geom of mesh (issue 0021122)
1234 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1236 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1237 if studyID != geompyD.myStudyId:
1238 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1241 geo_name = name + " shape"
1243 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1244 geompyD.addToStudy( self.geom, geo_name )
1245 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1247 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1250 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1252 self.smeshpyD.SetName(self.mesh, name)
1254 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1257 self.geom = self.mesh.GetShapeToMesh()
1259 self.editor = self.mesh.GetMeshEditor()
1260 self.functors = [None] * SMESH.FT_Undefined._v
1262 # set self to algoCreator's
1263 for attrName in dir(self):
1264 attr = getattr( self, attrName )
1265 if isinstance( attr, algoCreator ):
1266 setattr( self, attrName, attr.copy( self ))
1271 ## Destructor. Clean-up resources
1274 #self.mesh.UnRegister()
1278 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1279 # @param theMesh a SMESH_Mesh object
1280 # @ingroup l2_construct
1281 def SetMesh(self, theMesh):
1282 # do not call Register() as this prevents mesh servant deletion at closing study
1283 #if self.mesh: self.mesh.UnRegister()
1286 #self.mesh.Register()
1287 self.geom = self.mesh.GetShapeToMesh()
1290 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1291 # @return a SMESH_Mesh object
1292 # @ingroup l2_construct
1296 ## Gets the name of the mesh
1297 # @return the name of the mesh as a string
1298 # @ingroup l2_construct
1300 name = GetName(self.GetMesh())
1303 ## Sets a name to the mesh
1304 # @param name a new name of the mesh
1305 # @ingroup l2_construct
1306 def SetName(self, name):
1307 self.smeshpyD.SetName(self.GetMesh(), name)
1309 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1310 # The subMesh object gives access to the IDs of nodes and elements.
1311 # @param geom a geometrical object (shape)
1312 # @param name a name for the submesh
1313 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1314 # @ingroup l2_submeshes
1315 def GetSubMesh(self, geom, name):
1316 AssureGeomPublished( self, geom, name )
1317 submesh = self.mesh.GetSubMesh( geom, name )
1320 ## Returns the shape associated to the mesh
1321 # @return a GEOM_Object
1322 # @ingroup l2_construct
1326 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1327 # @param geom the shape to be meshed (GEOM_Object)
1328 # @ingroup l2_construct
1329 def SetShape(self, geom):
1330 self.mesh = self.smeshpyD.CreateMesh(geom)
1332 ## Loads mesh from the study after opening the study
1336 ## Returns true if the hypotheses are defined well
1337 # @param theSubObject a sub-shape of a mesh shape
1338 # @return True or False
1339 # @ingroup l2_construct
1340 def IsReadyToCompute(self, theSubObject):
1341 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1343 ## Returns errors of hypotheses definition.
1344 # The list of errors is empty if everything is OK.
1345 # @param theSubObject a sub-shape of a mesh shape
1346 # @return a list of errors
1347 # @ingroup l2_construct
1348 def GetAlgoState(self, theSubObject):
1349 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1351 ## Returns a geometrical object on which the given element was built.
1352 # The returned geometrical object, if not nil, is either found in the
1353 # study or published by this method with the given name
1354 # @param theElementID the id of the mesh element
1355 # @param theGeomName the user-defined name of the geometrical object
1356 # @return GEOM::GEOM_Object instance
1357 # @ingroup l2_construct
1358 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1359 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1361 ## Returns the mesh dimension depending on the dimension of the underlying shape
1362 # or, if the mesh is not based on any shape, basing on deimension of elements
1363 # @return mesh dimension as an integer value [0,3]
1364 # @ingroup l1_auxiliary
1365 def MeshDimension(self):
1366 if self.mesh.HasShapeToMesh():
1367 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1368 if len( shells ) > 0 :
1370 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1372 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1377 if self.NbVolumes() > 0: return 3
1378 if self.NbFaces() > 0: return 2
1379 if self.NbEdges() > 0: return 1
1382 ## Evaluates size of prospective mesh on a shape
1383 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1384 # To know predicted number of e.g. edges, inquire it this way
1385 # Evaluate()[ EnumToLong( Entity_Edge )]
1386 def Evaluate(self, geom=0):
1387 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1389 geom = self.mesh.GetShapeToMesh()
1392 return self.smeshpyD.Evaluate(self.mesh, geom)
1395 ## Computes the mesh and returns the status of the computation
1396 # @param geom geomtrical shape on which mesh data should be computed
1397 # @param discardModifs if True and the mesh has been edited since
1398 # a last total re-compute and that may prevent successful partial re-compute,
1399 # then the mesh is cleaned before Compute()
1400 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1401 # @return True or False
1402 # @ingroup l2_construct
1403 def Compute(self, geom=0, discardModifs=False, refresh=False):
1404 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1406 geom = self.mesh.GetShapeToMesh()
1411 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1413 ok = self.smeshpyD.Compute(self.mesh, geom)
1414 except SALOME.SALOME_Exception, ex:
1415 print "Mesh computation failed, exception caught:"
1416 print " ", ex.details.text
1419 print "Mesh computation failed, exception caught:"
1420 traceback.print_exc()
1424 # Treat compute errors
1425 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1427 for err in computeErrors:
1428 if self.mesh.HasShapeToMesh():
1429 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1431 stdErrors = ["OK", #COMPERR_OK
1432 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1433 "std::exception", #COMPERR_STD_EXCEPTION
1434 "OCC exception", #COMPERR_OCC_EXCEPTION
1435 "..", #COMPERR_SLM_EXCEPTION
1436 "Unknown exception", #COMPERR_EXCEPTION
1437 "Memory allocation problem", #COMPERR_MEMORY_PB
1438 "Algorithm failed", #COMPERR_ALGO_FAILED
1439 "Unexpected geometry", #COMPERR_BAD_SHAPE
1440 "Warning", #COMPERR_WARNING
1441 "Computation cancelled",#COMPERR_CANCELED
1442 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1444 if err.code < len(stdErrors): errText = stdErrors[err.code]
1446 errText = "code %s" % -err.code
1447 if errText: errText += ". "
1448 errText += err.comment
1449 if allReasons != "":allReasons += "\n"
1451 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1453 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1457 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1459 if err.isGlobalAlgo:
1467 reason = '%s %sD algorithm is missing' % (glob, dim)
1468 elif err.state == HYP_MISSING:
1469 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1470 % (glob, dim, name, dim))
1471 elif err.state == HYP_NOTCONFORM:
1472 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1473 elif err.state == HYP_BAD_PARAMETER:
1474 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1475 % ( glob, dim, name ))
1476 elif err.state == HYP_BAD_GEOMETRY:
1477 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1478 'geometry' % ( glob, dim, name ))
1479 elif err.state == HYP_HIDDEN_ALGO:
1480 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1481 'algorithm of upper dimension generating %sD mesh'
1482 % ( glob, dim, name, glob, dim ))
1484 reason = ("For unknown reason. "
1485 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1487 if allReasons != "":allReasons += "\n"
1488 allReasons += "- " + reason
1490 if not ok or allReasons != "":
1491 msg = '"' + GetName(self.mesh) + '"'
1492 if ok: msg += " has been computed with warnings"
1493 else: msg += " has not been computed"
1494 if allReasons != "": msg += ":"
1499 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1500 smeshgui = salome.ImportComponentGUI("SMESH")
1501 smeshgui.Init(self.mesh.GetStudyId())
1502 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1503 if refresh: salome.sg.updateObjBrowser(1)
1507 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1508 def GetComputeErrors(self, shape=0 ):
1510 shape = self.mesh.GetShapeToMesh()
1511 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1513 ## Return a name of a sub-shape by its ID
1514 # @param subShapeID a unique ID of a sub-shape
1515 # @return a string describing the sub-shape; possible variants:
1516 # - "Face_12" (published sub-shape)
1517 # - FACE #3 (not published sub-shape)
1518 # - sub-shape #3 (invalid sub-shape ID)
1519 # - #3 (error in this function)
1520 def GetSubShapeName(self, subShapeID ):
1521 if not self.mesh.HasShapeToMesh():
1525 mainIOR = salome.orb.object_to_string( self.GetShape() )
1526 for sname in salome.myStudyManager.GetOpenStudies():
1527 s = salome.myStudyManager.GetStudyByName(sname)
1529 mainSO = s.FindObjectIOR(mainIOR)
1530 if not mainSO: continue
1532 shapeText = '"%s"' % mainSO.GetName()
1533 subIt = s.NewChildIterator(mainSO)
1535 subSO = subIt.Value()
1537 obj = subSO.GetObject()
1538 if not obj: continue
1539 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1542 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1545 if ids == subShapeID:
1546 shapeText = '"%s"' % subSO.GetName()
1549 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1551 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1553 shapeText = 'sub-shape #%s' % (subShapeID)
1555 shapeText = "#%s" % (subShapeID)
1558 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1559 # error of an algorithm
1560 # @param publish if @c True, the returned groups will be published in the study
1561 # @return a list of GEOM groups each named after a failed algorithm
1562 def GetFailedShapes(self, publish=False):
1565 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1566 for err in computeErrors:
1567 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1568 if not shape: continue
1569 if err.algoName in algo2shapes:
1570 algo2shapes[ err.algoName ].append( shape )
1572 algo2shapes[ err.algoName ] = [ shape ]
1576 for algoName, shapes in algo2shapes.items():
1578 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1579 otherTypeShapes = []
1581 group = self.geompyD.CreateGroup( self.geom, groupType )
1582 for shape in shapes:
1583 if shape.GetShapeType() == shapes[0].GetShapeType():
1584 sameTypeShapes.append( shape )
1586 otherTypeShapes.append( shape )
1587 self.geompyD.UnionList( group, sameTypeShapes )
1589 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1591 group.SetName( algoName )
1592 groups.append( group )
1593 shapes = otherTypeShapes
1596 for group in groups:
1597 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1600 ## Return sub-mesh objects list in meshing order
1601 # @return list of lists of sub-meshes
1602 # @ingroup l2_construct
1603 def GetMeshOrder(self):
1604 return self.mesh.GetMeshOrder()
1606 ## Set order in which concurrent sub-meshes sould be meshed
1607 # @param submeshes list of lists of sub-meshes
1608 # @ingroup l2_construct
1609 def SetMeshOrder(self, submeshes):
1610 return self.mesh.SetMeshOrder(submeshes)
1612 ## Removes all nodes and elements
1613 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1614 # @ingroup l2_construct
1615 def Clear(self, refresh=False):
1617 if ( salome.sg.hasDesktop() and
1618 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1619 smeshgui = salome.ImportComponentGUI("SMESH")
1620 smeshgui.Init(self.mesh.GetStudyId())
1621 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1622 if refresh: salome.sg.updateObjBrowser(1)
1624 ## Removes all nodes and elements of indicated shape
1625 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1626 # @param geomId the ID of a sub-shape to remove elements on
1627 # @ingroup l2_construct
1628 def ClearSubMesh(self, geomId, refresh=False):
1629 self.mesh.ClearSubMesh(geomId)
1630 if salome.sg.hasDesktop():
1631 smeshgui = salome.ImportComponentGUI("SMESH")
1632 smeshgui.Init(self.mesh.GetStudyId())
1633 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1634 if refresh: salome.sg.updateObjBrowser(1)
1636 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1637 # @param fineness [0.0,1.0] defines mesh fineness
1638 # @return True or False
1639 # @ingroup l3_algos_basic
1640 def AutomaticTetrahedralization(self, fineness=0):
1641 dim = self.MeshDimension()
1643 self.RemoveGlobalHypotheses()
1644 self.Segment().AutomaticLength(fineness)
1646 self.Triangle().LengthFromEdges()
1651 return self.Compute()
1653 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1654 # @param fineness [0.0, 1.0] defines mesh fineness
1655 # @return True or False
1656 # @ingroup l3_algos_basic
1657 def AutomaticHexahedralization(self, fineness=0):
1658 dim = self.MeshDimension()
1659 # assign the hypotheses
1660 self.RemoveGlobalHypotheses()
1661 self.Segment().AutomaticLength(fineness)
1668 return self.Compute()
1670 ## Assigns a hypothesis
1671 # @param hyp a hypothesis to assign
1672 # @param geom a subhape of mesh geometry
1673 # @return SMESH.Hypothesis_Status
1674 # @ingroup l2_hypotheses
1675 def AddHypothesis(self, hyp, geom=0):
1676 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1677 hyp, geom = geom, hyp
1678 if isinstance( hyp, Mesh_Algorithm ):
1679 hyp = hyp.GetAlgorithm()
1684 geom = self.mesh.GetShapeToMesh()
1687 if self.mesh.HasShapeToMesh():
1688 hyp_type = hyp.GetName()
1689 lib_name = hyp.GetLibName()
1690 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1691 # if checkAll and geom:
1692 # checkAll = geom.GetType() == 37
1694 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1696 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1697 status = self.mesh.AddHypothesis(geom, hyp)
1699 status = HYP_BAD_GEOMETRY,""
1700 hyp_name = GetName( hyp )
1703 geom_name = geom.GetName()
1704 isAlgo = hyp._narrow( SMESH_Algo )
1705 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1708 ## Return True if an algorithm of hypothesis is assigned to a given shape
1709 # @param hyp a hypothesis to check
1710 # @param geom a subhape of mesh geometry
1711 # @return True of False
1712 # @ingroup l2_hypotheses
1713 def IsUsedHypothesis(self, hyp, geom):
1714 if not hyp: # or not geom
1716 if isinstance( hyp, Mesh_Algorithm ):
1717 hyp = hyp.GetAlgorithm()
1719 hyps = self.GetHypothesisList(geom)
1721 if h.GetId() == hyp.GetId():
1725 ## Unassigns a hypothesis
1726 # @param hyp a hypothesis to unassign
1727 # @param geom a sub-shape of mesh geometry
1728 # @return SMESH.Hypothesis_Status
1729 # @ingroup l2_hypotheses
1730 def RemoveHypothesis(self, hyp, geom=0):
1733 if isinstance( hyp, Mesh_Algorithm ):
1734 hyp = hyp.GetAlgorithm()
1740 if self.IsUsedHypothesis( hyp, shape ):
1741 return self.mesh.RemoveHypothesis( shape, hyp )
1742 hypName = GetName( hyp )
1743 geoName = GetName( shape )
1744 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1747 ## Gets the list of hypotheses added on a geometry
1748 # @param geom a sub-shape of mesh geometry
1749 # @return the sequence of SMESH_Hypothesis
1750 # @ingroup l2_hypotheses
1751 def GetHypothesisList(self, geom):
1752 return self.mesh.GetHypothesisList( geom )
1754 ## Removes all global hypotheses
1755 # @ingroup l2_hypotheses
1756 def RemoveGlobalHypotheses(self):
1757 current_hyps = self.mesh.GetHypothesisList( self.geom )
1758 for hyp in current_hyps:
1759 self.mesh.RemoveHypothesis( self.geom, hyp )
1763 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1764 ## allowing to overwrite the file if it exists or add the exported data to its contents
1765 # @param f is the file name
1766 # @param auto_groups boolean parameter for creating/not creating
1767 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1768 # the typical use is auto_groups=false.
1769 # @param version MED format version(MED_V2_1 or MED_V2_2)
1770 # @param overwrite boolean parameter for overwriting/not overwriting the file
1771 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
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.
1776 # If @a autoDimension is @c False, the space dimension is always 3.
1777 # @param fields : list of GEOM fields defined on the shape to mesh.
1778 # @param geomAssocFields : each character of this string means a need to export a
1779 # corresponding field; correspondence between fields and characters is following:
1780 # - 'v' stands for _vertices_ field;
1781 # - 'e' stands for _edges_ field;
1782 # - 'f' stands for _faces_ field;
1783 # - 's' stands for _solids_ field.
1784 # @ingroup l2_impexp
1785 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1786 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1787 if meshPart or fields or geomAssocFields:
1788 unRegister = genObjUnRegister()
1789 if isinstance( meshPart, list ):
1790 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1791 unRegister.set( meshPart )
1792 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1793 fields, geomAssocFields)
1795 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1797 ## Exports the mesh in a file in SAUV format
1798 # @param f is the file name
1799 # @param auto_groups boolean parameter for creating/not creating
1800 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1801 # the typical use is auto_groups=false.
1802 # @ingroup l2_impexp
1803 def ExportSAUV(self, f, auto_groups=0):
1804 self.mesh.ExportSAUV(f, auto_groups)
1806 ## Exports the mesh in a file in DAT format
1807 # @param f the file name
1808 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1809 # @ingroup l2_impexp
1810 def ExportDAT(self, f, meshPart=None):
1812 unRegister = genObjUnRegister()
1813 if isinstance( meshPart, list ):
1814 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1815 unRegister.set( meshPart )
1816 self.mesh.ExportPartToDAT( meshPart, f )
1818 self.mesh.ExportDAT(f)
1820 ## Exports the mesh in a file in UNV format
1821 # @param f the file name
1822 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1823 # @ingroup l2_impexp
1824 def ExportUNV(self, f, meshPart=None):
1826 unRegister = genObjUnRegister()
1827 if isinstance( meshPart, list ):
1828 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1829 unRegister.set( meshPart )
1830 self.mesh.ExportPartToUNV( meshPart, f )
1832 self.mesh.ExportUNV(f)
1834 ## Export the mesh in a file in STL format
1835 # @param f the file name
1836 # @param ascii defines the file encoding
1837 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1838 # @ingroup l2_impexp
1839 def ExportSTL(self, f, ascii=1, meshPart=None):
1841 unRegister = genObjUnRegister()
1842 if isinstance( meshPart, list ):
1843 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1844 unRegister.set( meshPart )
1845 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1847 self.mesh.ExportSTL(f, ascii)
1849 ## Exports the mesh in a file in CGNS format
1850 # @param f is the file name
1851 # @param overwrite boolean parameter for overwriting/not overwriting the file
1852 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1853 # @ingroup l2_impexp
1854 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1855 unRegister = genObjUnRegister()
1856 if isinstance( meshPart, list ):
1857 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1858 unRegister.set( meshPart )
1859 if isinstance( meshPart, Mesh ):
1860 meshPart = meshPart.mesh
1862 meshPart = self.mesh
1863 self.mesh.ExportCGNS(meshPart, f, overwrite)
1865 ## Exports the mesh in a file in GMF format.
1866 # GMF files must have .mesh extension for the ASCII format and .meshb for
1867 # the bynary format. Other extensions are not allowed.
1868 # @param f is the file name
1869 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1870 # @ingroup l2_impexp
1871 def ExportGMF(self, f, meshPart=None):
1872 unRegister = genObjUnRegister()
1873 if isinstance( meshPart, list ):
1874 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1875 unRegister.set( meshPart )
1876 if isinstance( meshPart, Mesh ):
1877 meshPart = meshPart.mesh
1879 meshPart = self.mesh
1880 self.mesh.ExportGMF(meshPart, f, True)
1882 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1883 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1884 ## allowing to overwrite the file if it exists or add the exported data to its contents
1885 # @param f the file name
1886 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1887 # @param opt boolean parameter for creating/not creating
1888 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1889 # @param overwrite boolean parameter for overwriting/not overwriting the file
1890 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1891 # - 1D if all mesh nodes lie on OX coordinate axis, or
1892 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1893 # - 3D in the rest cases.
1895 # If @a autoDimension is @c False, the space dimension is always 3.
1896 # @ingroup l2_impexp
1897 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1898 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1900 # Operations with groups:
1901 # ----------------------
1903 ## Creates an empty mesh group
1904 # @param elementType the type of elements in the group; either of
1905 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1906 # @param name the name of the mesh group
1907 # @return SMESH_Group
1908 # @ingroup l2_grps_create
1909 def CreateEmptyGroup(self, elementType, name):
1910 return self.mesh.CreateGroup(elementType, name)
1912 ## Creates a mesh group based on the geometric object \a grp
1913 # and gives a \a name, \n if this parameter is not defined
1914 # the name is the same as the geometric group name \n
1915 # Note: Works like GroupOnGeom().
1916 # @param grp a geometric group, a vertex, an edge, a face or a solid
1917 # @param name the name of the mesh group
1918 # @return SMESH_GroupOnGeom
1919 # @ingroup l2_grps_create
1920 def Group(self, grp, name=""):
1921 return self.GroupOnGeom(grp, name)
1923 ## Creates a mesh group based on the geometrical object \a grp
1924 # and gives a \a name, \n if this parameter is not defined
1925 # the name is the same as the geometrical group name
1926 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1927 # @param name the name of the mesh group
1928 # @param typ the type of elements in the group; either of
1929 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1930 # automatically detected by the type of the geometry
1931 # @return SMESH_GroupOnGeom
1932 # @ingroup l2_grps_create
1933 def GroupOnGeom(self, grp, name="", typ=None):
1934 AssureGeomPublished( self, grp, name )
1936 name = grp.GetName()
1938 typ = self._groupTypeFromShape( grp )
1939 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1941 ## Pivate method to get a type of group on geometry
1942 def _groupTypeFromShape( self, shape ):
1943 tgeo = str(shape.GetShapeType())
1944 if tgeo == "VERTEX":
1946 elif tgeo == "EDGE":
1948 elif tgeo == "FACE" or tgeo == "SHELL":
1950 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1952 elif tgeo == "COMPOUND":
1953 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1955 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1956 return self._groupTypeFromShape( sub[0] )
1959 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1962 ## Creates a mesh group with given \a name based on the \a filter which
1963 ## is a special type of group dynamically updating it's contents during
1964 ## mesh modification
1965 # @param typ the type of elements in the group; either of
1966 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1967 # @param name the name of the mesh group
1968 # @param filter the filter defining group contents
1969 # @return SMESH_GroupOnFilter
1970 # @ingroup l2_grps_create
1971 def GroupOnFilter(self, typ, name, filter):
1972 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1974 ## Creates a mesh group by the given ids of elements
1975 # @param groupName the name of the mesh group
1976 # @param elementType the type of elements in the group; either of
1977 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1978 # @param elemIDs either the list of ids, group, sub-mesh, or filter
1979 # @return SMESH_Group
1980 # @ingroup l2_grps_create
1981 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1982 group = self.mesh.CreateGroup(elementType, groupName)
1983 if hasattr( elemIDs, "GetIDs" ):
1984 if hasattr( elemIDs, "SetMesh" ):
1985 elemIDs.SetMesh( self.GetMesh() )
1986 group.AddFrom( elemIDs )
1991 ## Creates a mesh group by the given conditions
1992 # @param groupName the name of the mesh group
1993 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1994 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
1995 # Type SMESH.FunctorType._items in the Python Console to see all values.
1996 # Note that the items starting from FT_LessThan are not suitable for CritType.
1997 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1998 # @param Threshold the threshold value (range of ids as string, shape, numeric)
1999 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2000 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2001 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2002 # @return SMESH_GroupOnFilter
2003 # @ingroup l2_grps_create
2007 CritType=FT_Undefined,
2010 UnaryOp=FT_Undefined,
2012 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2013 group = self.MakeGroupByCriterion(groupName, aCriterion)
2016 ## Creates a mesh group by the given criterion
2017 # @param groupName the name of the mesh group
2018 # @param Criterion the instance of Criterion class
2019 # @return SMESH_GroupOnFilter
2020 # @ingroup l2_grps_create
2021 def MakeGroupByCriterion(self, groupName, Criterion):
2022 return self.MakeGroupByCriteria( groupName, [Criterion] )
2024 ## Creates a mesh group by the given criteria (list of criteria)
2025 # @param groupName the name of the mesh group
2026 # @param theCriteria the list of criteria
2027 # @param binOp binary operator used when binary operator of criteria is undefined
2028 # @return SMESH_GroupOnFilter
2029 # @ingroup l2_grps_create
2030 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2031 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2032 group = self.MakeGroupByFilter(groupName, aFilter)
2035 ## Creates a mesh group by the given filter
2036 # @param groupName the name of the mesh group
2037 # @param theFilter the instance of Filter class
2038 # @return SMESH_GroupOnFilter
2039 # @ingroup l2_grps_create
2040 def MakeGroupByFilter(self, groupName, theFilter):
2041 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2042 #theFilter.SetMesh( self.mesh )
2043 #group.AddFrom( theFilter )
2044 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2048 # @ingroup l2_grps_delete
2049 def RemoveGroup(self, group):
2050 self.mesh.RemoveGroup(group)
2052 ## Removes a group with its contents
2053 # @ingroup l2_grps_delete
2054 def RemoveGroupWithContents(self, group):
2055 self.mesh.RemoveGroupWithContents(group)
2057 ## Gets the list of groups existing in the mesh in the order
2058 # of creation (starting from the oldest one)
2059 # @param elemType type of elements the groups contain; either of
2060 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2061 # by default groups of elements of all types are returned
2062 # @return a sequence of SMESH_GroupBase
2063 # @ingroup l2_grps_create
2064 def GetGroups(self, elemType = SMESH.ALL):
2065 groups = self.mesh.GetGroups()
2066 if elemType == SMESH.ALL:
2070 if g.GetType() == elemType:
2071 typedGroups.append( g )
2076 ## Gets the number of groups existing in the mesh
2077 # @return the quantity of groups as an integer value
2078 # @ingroup l2_grps_create
2080 return self.mesh.NbGroups()
2082 ## Gets the list of names of groups existing in the mesh
2083 # @return list of strings
2084 # @ingroup l2_grps_create
2085 def GetGroupNames(self):
2086 groups = self.GetGroups()
2088 for group in groups:
2089 names.append(group.GetName())
2092 ## Finds groups by name and type
2093 # @param name name of the group of interest
2094 # @param elemType type of elements the groups contain; either of
2095 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2096 # by default one group of any type of elements is returned
2097 # if elemType == SMESH.ALL then all groups of any type are returned
2098 # @return a list of SMESH_GroupBase's
2099 # @ingroup l2_grps_create
2100 def GetGroupByName(self, name, elemType = None):
2102 for group in self.GetGroups():
2103 if group.GetName() == name:
2104 if elemType is None:
2106 if ( elemType == SMESH.ALL or
2107 group.GetType() == elemType ):
2108 groups.append( group )
2111 ## Produces a union of two groups.
2112 # A new group is created. All mesh elements that are
2113 # present in the initial groups are added to the new one
2114 # @return an instance of SMESH_Group
2115 # @ingroup l2_grps_operon
2116 def UnionGroups(self, group1, group2, name):
2117 return self.mesh.UnionGroups(group1, group2, name)
2119 ## Produces a union list of groups.
2120 # New group is created. All mesh elements that are present in
2121 # initial groups are added to the new one
2122 # @return an instance of SMESH_Group
2123 # @ingroup l2_grps_operon
2124 def UnionListOfGroups(self, groups, name):
2125 return self.mesh.UnionListOfGroups(groups, name)
2127 ## Prodices an intersection of two groups.
2128 # A new group is created. All mesh elements that are common
2129 # for the two initial groups are added to the new one.
2130 # @return an instance of SMESH_Group
2131 # @ingroup l2_grps_operon
2132 def IntersectGroups(self, group1, group2, name):
2133 return self.mesh.IntersectGroups(group1, group2, name)
2135 ## Produces an intersection of groups.
2136 # New group is created. All mesh elements that are present in all
2137 # initial groups simultaneously are added to the new one
2138 # @return an instance of SMESH_Group
2139 # @ingroup l2_grps_operon
2140 def IntersectListOfGroups(self, groups, name):
2141 return self.mesh.IntersectListOfGroups(groups, name)
2143 ## Produces a cut of two groups.
2144 # A new group is created. All mesh elements that are present in
2145 # the main group but are not present in the tool group are added to the new one
2146 # @return an instance of SMESH_Group
2147 # @ingroup l2_grps_operon
2148 def CutGroups(self, main_group, tool_group, name):
2149 return self.mesh.CutGroups(main_group, tool_group, name)
2151 ## Produces a cut of groups.
2152 # A new group is created. All mesh elements that are present in main groups
2153 # but do not present in tool groups are added to the new one
2154 # @return an instance of SMESH_Group
2155 # @ingroup l2_grps_operon
2156 def CutListOfGroups(self, main_groups, tool_groups, name):
2157 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2160 # Create a standalone group of entities basing on nodes of other groups.
2161 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2162 # \param elemType - a type of elements to include to the new group; either of
2163 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2164 # \param name - a name of the new group.
2165 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2166 # basing on number of element nodes common with reference \a groups.
2167 # Meaning of possible values are:
2168 # - SMESH.ALL_NODES - include if all nodes are common,
2169 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2170 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2171 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2172 # \param underlyingOnly - if \c True (default), an element is included to the
2173 # new group provided that it is based on nodes of an element of \a groups;
2174 # in this case the reference \a groups are supposed to be of higher dimension
2175 # than \a elemType, which can be useful for example to get all faces lying on
2176 # volumes of the reference \a groups.
2177 # @return an instance of SMESH_Group
2178 # @ingroup l2_grps_operon
2179 def CreateDimGroup(self, groups, elemType, name,
2180 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2181 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2183 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2186 ## Convert group on geom into standalone group
2187 # @ingroup l2_grps_edit
2188 def ConvertToStandalone(self, group):
2189 return self.mesh.ConvertToStandalone(group)
2191 # Get some info about mesh:
2192 # ------------------------
2194 ## Returns the log of nodes and elements added or removed
2195 # since the previous clear of the log.
2196 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2197 # @return list of log_block structures:
2202 # @ingroup l1_auxiliary
2203 def GetLog(self, clearAfterGet):
2204 return self.mesh.GetLog(clearAfterGet)
2206 ## Clears the log of nodes and elements added or removed since the previous
2207 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2208 # @ingroup l1_auxiliary
2210 self.mesh.ClearLog()
2212 ## Toggles auto color mode on the object.
2213 # @param theAutoColor the flag which toggles auto color mode.
2214 # @ingroup l1_auxiliary
2215 def SetAutoColor(self, theAutoColor):
2216 self.mesh.SetAutoColor(theAutoColor)
2218 ## Gets flag of object auto color mode.
2219 # @return True or False
2220 # @ingroup l1_auxiliary
2221 def GetAutoColor(self):
2222 return self.mesh.GetAutoColor()
2224 ## Gets the internal ID
2225 # @return integer value, which is the internal Id of the mesh
2226 # @ingroup l1_auxiliary
2228 return self.mesh.GetId()
2231 # @return integer value, which is the study Id of the mesh
2232 # @ingroup l1_auxiliary
2233 def GetStudyId(self):
2234 return self.mesh.GetStudyId()
2236 ## Checks the group names for duplications.
2237 # Consider the maximum group name length stored in MED file.
2238 # @return True or False
2239 # @ingroup l1_auxiliary
2240 def HasDuplicatedGroupNamesMED(self):
2241 return self.mesh.HasDuplicatedGroupNamesMED()
2243 ## Obtains the mesh editor tool
2244 # @return an instance of SMESH_MeshEditor
2245 # @ingroup l1_modifying
2246 def GetMeshEditor(self):
2249 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2250 # can be passed as argument to a method accepting mesh, group or sub-mesh
2251 # @param ids list of IDs
2252 # @param elemType type of elements; this parameter is used to distinguish
2253 # IDs of nodes from IDs of elements; by default ids are treated as
2254 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2255 # @return an instance of SMESH_IDSource
2256 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2257 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2258 # mesh.DoSomething( idSrc )
2259 # idSrc.UnRegister()
2260 # @ingroup l1_auxiliary
2261 def GetIDSource(self, ids, elemType = SMESH.ALL):
2262 return self.editor.MakeIDSource(ids, elemType)
2265 # Get informations about mesh contents:
2266 # ------------------------------------
2268 ## Gets the mesh stattistic
2269 # @return dictionary type element - count of elements
2270 # @ingroup l1_meshinfo
2271 def GetMeshInfo(self, obj = None):
2272 if not obj: obj = self.mesh
2273 return self.smeshpyD.GetMeshInfo(obj)
2275 ## Returns the number of nodes in the mesh
2276 # @return an integer value
2277 # @ingroup l1_meshinfo
2279 return self.mesh.NbNodes()
2281 ## Returns the number of elements in the mesh
2282 # @return an integer value
2283 # @ingroup l1_meshinfo
2284 def NbElements(self):
2285 return self.mesh.NbElements()
2287 ## Returns the number of 0d elements in the mesh
2288 # @return an integer value
2289 # @ingroup l1_meshinfo
2290 def Nb0DElements(self):
2291 return self.mesh.Nb0DElements()
2293 ## Returns the number of ball discrete elements in the mesh
2294 # @return an integer value
2295 # @ingroup l1_meshinfo
2297 return self.mesh.NbBalls()
2299 ## Returns the number of edges in the mesh
2300 # @return an integer value
2301 # @ingroup l1_meshinfo
2303 return self.mesh.NbEdges()
2305 ## Returns the number of edges with the given order in the mesh
2306 # @param elementOrder the order of elements:
2307 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2308 # @return an integer value
2309 # @ingroup l1_meshinfo
2310 def NbEdgesOfOrder(self, elementOrder):
2311 return self.mesh.NbEdgesOfOrder(elementOrder)
2313 ## Returns the number of faces in the mesh
2314 # @return an integer value
2315 # @ingroup l1_meshinfo
2317 return self.mesh.NbFaces()
2319 ## Returns the number of faces with the given order in the mesh
2320 # @param elementOrder the order of elements:
2321 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2322 # @return an integer value
2323 # @ingroup l1_meshinfo
2324 def NbFacesOfOrder(self, elementOrder):
2325 return self.mesh.NbFacesOfOrder(elementOrder)
2327 ## Returns the number of triangles in the mesh
2328 # @return an integer value
2329 # @ingroup l1_meshinfo
2330 def NbTriangles(self):
2331 return self.mesh.NbTriangles()
2333 ## Returns the number of triangles with the given order in the mesh
2334 # @param elementOrder is the order of elements:
2335 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2336 # @return an integer value
2337 # @ingroup l1_meshinfo
2338 def NbTrianglesOfOrder(self, elementOrder):
2339 return self.mesh.NbTrianglesOfOrder(elementOrder)
2341 ## Returns the number of biquadratic triangles in the mesh
2342 # @return an integer value
2343 # @ingroup l1_meshinfo
2344 def NbBiQuadTriangles(self):
2345 return self.mesh.NbBiQuadTriangles()
2347 ## Returns the number of quadrangles in the mesh
2348 # @return an integer value
2349 # @ingroup l1_meshinfo
2350 def NbQuadrangles(self):
2351 return self.mesh.NbQuadrangles()
2353 ## Returns the number of quadrangles with the given order in the mesh
2354 # @param elementOrder the order of elements:
2355 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2356 # @return an integer value
2357 # @ingroup l1_meshinfo
2358 def NbQuadranglesOfOrder(self, elementOrder):
2359 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2361 ## Returns the number of biquadratic quadrangles in the mesh
2362 # @return an integer value
2363 # @ingroup l1_meshinfo
2364 def NbBiQuadQuadrangles(self):
2365 return self.mesh.NbBiQuadQuadrangles()
2367 ## Returns the number of polygons of given order in the mesh
2368 # @param elementOrder the order of elements:
2369 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2370 # @return an integer value
2371 # @ingroup l1_meshinfo
2372 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2373 return self.mesh.NbPolygonsOfOrder(elementOrder)
2375 ## Returns the number of volumes in the mesh
2376 # @return an integer value
2377 # @ingroup l1_meshinfo
2378 def NbVolumes(self):
2379 return self.mesh.NbVolumes()
2381 ## Returns the number of volumes with the given order in the mesh
2382 # @param elementOrder the order of elements:
2383 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2384 # @return an integer value
2385 # @ingroup l1_meshinfo
2386 def NbVolumesOfOrder(self, elementOrder):
2387 return self.mesh.NbVolumesOfOrder(elementOrder)
2389 ## Returns the number of tetrahedrons in the mesh
2390 # @return an integer value
2391 # @ingroup l1_meshinfo
2393 return self.mesh.NbTetras()
2395 ## Returns the number of tetrahedrons with the given order in the mesh
2396 # @param elementOrder the order of elements:
2397 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2398 # @return an integer value
2399 # @ingroup l1_meshinfo
2400 def NbTetrasOfOrder(self, elementOrder):
2401 return self.mesh.NbTetrasOfOrder(elementOrder)
2403 ## Returns the number of hexahedrons in the mesh
2404 # @return an integer value
2405 # @ingroup l1_meshinfo
2407 return self.mesh.NbHexas()
2409 ## Returns the number of hexahedrons with the given order in the mesh
2410 # @param elementOrder the order of elements:
2411 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2412 # @return an integer value
2413 # @ingroup l1_meshinfo
2414 def NbHexasOfOrder(self, elementOrder):
2415 return self.mesh.NbHexasOfOrder(elementOrder)
2417 ## Returns the number of triquadratic hexahedrons in the mesh
2418 # @return an integer value
2419 # @ingroup l1_meshinfo
2420 def NbTriQuadraticHexas(self):
2421 return self.mesh.NbTriQuadraticHexas()
2423 ## Returns the number of pyramids in the mesh
2424 # @return an integer value
2425 # @ingroup l1_meshinfo
2426 def NbPyramids(self):
2427 return self.mesh.NbPyramids()
2429 ## Returns the number of pyramids with the given order in the mesh
2430 # @param elementOrder the order of elements:
2431 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2432 # @return an integer value
2433 # @ingroup l1_meshinfo
2434 def NbPyramidsOfOrder(self, elementOrder):
2435 return self.mesh.NbPyramidsOfOrder(elementOrder)
2437 ## Returns the number of prisms in the mesh
2438 # @return an integer value
2439 # @ingroup l1_meshinfo
2441 return self.mesh.NbPrisms()
2443 ## Returns the number of prisms with the given order in the mesh
2444 # @param elementOrder the order of elements:
2445 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2446 # @return an integer value
2447 # @ingroup l1_meshinfo
2448 def NbPrismsOfOrder(self, elementOrder):
2449 return self.mesh.NbPrismsOfOrder(elementOrder)
2451 ## Returns the number of hexagonal prisms in the mesh
2452 # @return an integer value
2453 # @ingroup l1_meshinfo
2454 def NbHexagonalPrisms(self):
2455 return self.mesh.NbHexagonalPrisms()
2457 ## Returns the number of polyhedrons in the mesh
2458 # @return an integer value
2459 # @ingroup l1_meshinfo
2460 def NbPolyhedrons(self):
2461 return self.mesh.NbPolyhedrons()
2463 ## Returns the number of submeshes in the mesh
2464 # @return an integer value
2465 # @ingroup l1_meshinfo
2466 def NbSubMesh(self):
2467 return self.mesh.NbSubMesh()
2469 ## Returns the list of mesh elements IDs
2470 # @return the list of integer values
2471 # @ingroup l1_meshinfo
2472 def GetElementsId(self):
2473 return self.mesh.GetElementsId()
2475 ## Returns the list of IDs of mesh elements with the given type
2476 # @param elementType the required type of elements, either of
2477 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2478 # @return list of integer values
2479 # @ingroup l1_meshinfo
2480 def GetElementsByType(self, elementType):
2481 return self.mesh.GetElementsByType(elementType)
2483 ## Returns the list of mesh nodes IDs
2484 # @return the list of integer values
2485 # @ingroup l1_meshinfo
2486 def GetNodesId(self):
2487 return self.mesh.GetNodesId()
2489 # Get the information about mesh elements:
2490 # ------------------------------------
2492 ## Returns the type of mesh element
2493 # @return the value from SMESH::ElementType enumeration
2494 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2495 # @ingroup l1_meshinfo
2496 def GetElementType(self, id, iselem=True):
2497 return self.mesh.GetElementType(id, iselem)
2499 ## Returns the geometric type of mesh element
2500 # @return the value from SMESH::EntityType enumeration
2501 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2502 # @ingroup l1_meshinfo
2503 def GetElementGeomType(self, id):
2504 return self.mesh.GetElementGeomType(id)
2506 ## Returns the shape type of mesh element
2507 # @return the value from SMESH::GeometryType enumeration.
2508 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2509 # @ingroup l1_meshinfo
2510 def GetElementShape(self, id):
2511 return self.mesh.GetElementShape(id)
2513 ## Returns the list of submesh elements IDs
2514 # @param Shape a geom object(sub-shape) IOR
2515 # Shape must be the sub-shape of a ShapeToMesh()
2516 # @return the list of integer values
2517 # @ingroup l1_meshinfo
2518 def GetSubMeshElementsId(self, Shape):
2519 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2520 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2523 return self.mesh.GetSubMeshElementsId(ShapeID)
2525 ## Returns the list of submesh nodes IDs
2526 # @param Shape a geom object(sub-shape) IOR
2527 # Shape must be the sub-shape of a ShapeToMesh()
2528 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2529 # @return the list of integer values
2530 # @ingroup l1_meshinfo
2531 def GetSubMeshNodesId(self, Shape, all):
2532 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2533 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2536 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2538 ## Returns type of elements on given shape
2539 # @param Shape a geom object(sub-shape) IOR
2540 # Shape must be a sub-shape of a ShapeToMesh()
2541 # @return element type
2542 # @ingroup l1_meshinfo
2543 def GetSubMeshElementType(self, Shape):
2544 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2545 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2548 return self.mesh.GetSubMeshElementType(ShapeID)
2550 ## Gets the mesh description
2551 # @return string value
2552 # @ingroup l1_meshinfo
2554 return self.mesh.Dump()
2557 # Get the information about nodes and elements of a mesh by its IDs:
2558 # -----------------------------------------------------------
2560 ## Gets XYZ coordinates of a node
2561 # \n If there is no nodes for the given ID - returns an empty list
2562 # @return a list of double precision values
2563 # @ingroup l1_meshinfo
2564 def GetNodeXYZ(self, id):
2565 return self.mesh.GetNodeXYZ(id)
2567 ## Returns list of IDs of inverse elements for the given node
2568 # \n If there is no node for the given ID - returns an empty list
2569 # @return a list of integer values
2570 # @ingroup l1_meshinfo
2571 def GetNodeInverseElements(self, id):
2572 return self.mesh.GetNodeInverseElements(id)
2574 ## @brief Returns the position of a node on the shape
2575 # @return SMESH::NodePosition
2576 # @ingroup l1_meshinfo
2577 def GetNodePosition(self,NodeID):
2578 return self.mesh.GetNodePosition(NodeID)
2580 ## @brief Returns the position of an element on the shape
2581 # @return SMESH::ElementPosition
2582 # @ingroup l1_meshinfo
2583 def GetElementPosition(self,ElemID):
2584 return self.mesh.GetElementPosition(ElemID)
2586 ## Returns the ID of the shape, on which the given node was generated.
2587 # @return an integer value > 0 or -1 if there is no node for the given
2588 # ID or the node is not assigned to any geometry
2589 # @ingroup l1_meshinfo
2590 def GetShapeID(self, id):
2591 return self.mesh.GetShapeID(id)
2593 ## Returns the ID of the shape, on which the given element was generated.
2594 # @return an integer value > 0 or -1 if there is no element for the given
2595 # ID or the element is not assigned to any geometry
2596 # @ingroup l1_meshinfo
2597 def GetShapeIDForElem(self,id):
2598 return self.mesh.GetShapeIDForElem(id)
2600 ## Returns the number of nodes of the given element
2601 # @return an integer value > 0 or -1 if there is no element for the given ID
2602 # @ingroup l1_meshinfo
2603 def GetElemNbNodes(self, id):
2604 return self.mesh.GetElemNbNodes(id)
2606 ## Returns the node ID the given (zero based) index for the given element
2607 # \n If there is no element for the given ID - returns -1
2608 # \n If there is no node for the given index - returns -2
2609 # @return an integer value
2610 # @ingroup l1_meshinfo
2611 def GetElemNode(self, id, index):
2612 return self.mesh.GetElemNode(id, index)
2614 ## Returns the IDs of nodes of the given element
2615 # @return a list of integer values
2616 # @ingroup l1_meshinfo
2617 def GetElemNodes(self, id):
2618 return self.mesh.GetElemNodes(id)
2620 ## Returns true if the given node is the medium node in the given quadratic element
2621 # @ingroup l1_meshinfo
2622 def IsMediumNode(self, elementID, nodeID):
2623 return self.mesh.IsMediumNode(elementID, nodeID)
2625 ## Returns true if the given node is the medium node in one of quadratic elements
2626 # @param nodeID ID of the node
2627 # @param elementType the type of elements to check a state of the node, either of
2628 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2629 # @ingroup l1_meshinfo
2630 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2631 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2633 ## Returns the number of edges for the given element
2634 # @ingroup l1_meshinfo
2635 def ElemNbEdges(self, id):
2636 return self.mesh.ElemNbEdges(id)
2638 ## Returns the number of faces for the given element
2639 # @ingroup l1_meshinfo
2640 def ElemNbFaces(self, id):
2641 return self.mesh.ElemNbFaces(id)
2643 ## Returns nodes of given face (counted from zero) for given volumic element.
2644 # @ingroup l1_meshinfo
2645 def GetElemFaceNodes(self,elemId, faceIndex):
2646 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2648 ## Returns three components of normal of given mesh face
2649 # (or an empty array in KO case)
2650 # @ingroup l1_meshinfo
2651 def GetFaceNormal(self, faceId, normalized=False):
2652 return self.mesh.GetFaceNormal(faceId,normalized)
2654 ## Returns an element based on all given nodes.
2655 # @ingroup l1_meshinfo
2656 def FindElementByNodes(self,nodes):
2657 return self.mesh.FindElementByNodes(nodes)
2659 ## Returns true if the given element is a polygon
2660 # @ingroup l1_meshinfo
2661 def IsPoly(self, id):
2662 return self.mesh.IsPoly(id)
2664 ## Returns true if the given element is quadratic
2665 # @ingroup l1_meshinfo
2666 def IsQuadratic(self, id):
2667 return self.mesh.IsQuadratic(id)
2669 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2670 # @ingroup l1_meshinfo
2671 def GetBallDiameter(self, id):
2672 return self.mesh.GetBallDiameter(id)
2674 ## Returns XYZ coordinates of the barycenter of the given element
2675 # \n If there is no element for the given ID - returns an empty list
2676 # @return a list of three double values
2677 # @ingroup l1_meshinfo
2678 def BaryCenter(self, id):
2679 return self.mesh.BaryCenter(id)
2681 ## Passes mesh elements through the given filter and return IDs of fitting elements
2682 # @param theFilter SMESH_Filter
2683 # @return a list of ids
2684 # @ingroup l1_controls
2685 def GetIdsFromFilter(self, theFilter):
2686 theFilter.SetMesh( self.mesh )
2687 return theFilter.GetIDs()
2689 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2690 # Returns a list of special structures (borders).
2691 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2692 # @ingroup l1_controls
2693 def GetFreeBorders(self):
2694 aFilterMgr = self.smeshpyD.CreateFilterManager()
2695 aPredicate = aFilterMgr.CreateFreeEdges()
2696 aPredicate.SetMesh(self.mesh)
2697 aBorders = aPredicate.GetBorders()
2698 aFilterMgr.UnRegister()
2702 # Get mesh measurements information:
2703 # ------------------------------------
2705 ## Get minimum distance between two nodes, elements or distance to the origin
2706 # @param id1 first node/element id
2707 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2708 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2709 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2710 # @return minimum distance value
2711 # @sa GetMinDistance()
2712 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2713 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2714 return aMeasure.value
2716 ## Get measure structure specifying minimum distance data between two objects
2717 # @param id1 first node/element id
2718 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2719 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2720 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2721 # @return Measure structure
2723 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2725 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2727 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2730 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2732 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2737 aMeasurements = self.smeshpyD.CreateMeasurements()
2738 aMeasure = aMeasurements.MinDistance(id1, id2)
2739 genObjUnRegister([aMeasurements,id1, id2])
2742 ## Get bounding box of the specified object(s)
2743 # @param objects single source object or list of source objects or list of nodes/elements IDs
2744 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2745 # @c False specifies that @a objects are nodes
2746 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2747 # @sa GetBoundingBox()
2748 def BoundingBox(self, objects=None, isElem=False):
2749 result = self.GetBoundingBox(objects, isElem)
2753 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2756 ## Get measure structure specifying bounding box data of the specified object(s)
2757 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2758 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2759 # @c False specifies that @a objects are nodes
2760 # @return Measure structure
2762 def GetBoundingBox(self, IDs=None, isElem=False):
2765 elif isinstance(IDs, tuple):
2767 if not isinstance(IDs, list):
2769 if len(IDs) > 0 and isinstance(IDs[0], int):
2772 unRegister = genObjUnRegister()
2774 if isinstance(o, Mesh):
2775 srclist.append(o.mesh)
2776 elif hasattr(o, "_narrow"):
2777 src = o._narrow(SMESH.SMESH_IDSource)
2778 if src: srclist.append(src)
2780 elif isinstance(o, list):
2782 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2784 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2785 unRegister.set( srclist[-1] )
2788 aMeasurements = self.smeshpyD.CreateMeasurements()
2789 unRegister.set( aMeasurements )
2790 aMeasure = aMeasurements.BoundingBox(srclist)
2793 # Mesh edition (SMESH_MeshEditor functionality):
2794 # ---------------------------------------------
2796 ## Removes the elements from the mesh by ids
2797 # @param IDsOfElements is a list of ids of elements to remove
2798 # @return True or False
2799 # @ingroup l2_modif_del
2800 def RemoveElements(self, IDsOfElements):
2801 return self.editor.RemoveElements(IDsOfElements)
2803 ## Removes nodes from mesh by ids
2804 # @param IDsOfNodes is a list of ids of nodes to remove
2805 # @return True or False
2806 # @ingroup l2_modif_del
2807 def RemoveNodes(self, IDsOfNodes):
2808 return self.editor.RemoveNodes(IDsOfNodes)
2810 ## Removes all orphan (free) nodes from mesh
2811 # @return number of the removed nodes
2812 # @ingroup l2_modif_del
2813 def RemoveOrphanNodes(self):
2814 return self.editor.RemoveOrphanNodes()
2816 ## Add a node to the mesh by coordinates
2817 # @return Id of the new node
2818 # @ingroup l2_modif_add
2819 def AddNode(self, x, y, z):
2820 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2821 if hasVars: self.mesh.SetParameters(Parameters)
2822 return self.editor.AddNode( x, y, z)
2824 ## Creates a 0D element on a node with given number.
2825 # @param IDOfNode the ID of node for creation of the element.
2826 # @return the Id of the new 0D element
2827 # @ingroup l2_modif_add
2828 def Add0DElement(self, IDOfNode):
2829 return self.editor.Add0DElement(IDOfNode)
2831 ## Create 0D elements on all nodes of the given elements except those
2832 # nodes on which a 0D element already exists.
2833 # @param theObject an object on whose nodes 0D elements will be created.
2834 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2835 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2836 # @param theGroupName optional name of a group to add 0D elements created
2837 # and/or found on nodes of \a theObject.
2838 # @return an object (a new group or a temporary SMESH_IDSource) holding
2839 # IDs of new and/or found 0D elements. IDs of 0D elements
2840 # can be retrieved from the returned object by calling GetIDs()
2841 # @ingroup l2_modif_add
2842 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2843 unRegister = genObjUnRegister()
2844 if isinstance( theObject, Mesh ):
2845 theObject = theObject.GetMesh()
2846 if isinstance( theObject, list ):
2847 theObject = self.GetIDSource( theObject, SMESH.ALL )
2848 unRegister.set( theObject )
2849 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2851 ## Creates a ball element on a node with given ID.
2852 # @param IDOfNode the ID of node for creation of the element.
2853 # @param diameter the bal diameter.
2854 # @return the Id of the new ball element
2855 # @ingroup l2_modif_add
2856 def AddBall(self, IDOfNode, diameter):
2857 return self.editor.AddBall( IDOfNode, diameter )
2859 ## Creates a linear or quadratic edge (this is determined
2860 # by the number of given nodes).
2861 # @param IDsOfNodes the list of node IDs for creation of the element.
2862 # The order of nodes in this list should correspond to the description
2863 # of MED. \n This description is located by the following link:
2864 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2865 # @return the Id of the new edge
2866 # @ingroup l2_modif_add
2867 def AddEdge(self, IDsOfNodes):
2868 return self.editor.AddEdge(IDsOfNodes)
2870 ## Creates a linear or quadratic face (this is determined
2871 # by the number of given nodes).
2872 # @param IDsOfNodes the list of node IDs for creation of the element.
2873 # The order of nodes in this list should correspond to the description
2874 # of MED. \n This description is located by the following link:
2875 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2876 # @return the Id of the new face
2877 # @ingroup l2_modif_add
2878 def AddFace(self, IDsOfNodes):
2879 return self.editor.AddFace(IDsOfNodes)
2881 ## Adds a polygonal face to the mesh by the list of node IDs
2882 # @param IdsOfNodes the list of node IDs for creation of the element.
2883 # @return the Id of the new face
2884 # @ingroup l2_modif_add
2885 def AddPolygonalFace(self, IdsOfNodes):
2886 return self.editor.AddPolygonalFace(IdsOfNodes)
2888 ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2889 # @param IdsOfNodes the list of node IDs for creation of the element;
2890 # corner nodes follow first.
2891 # @return the Id of the new face
2892 # @ingroup l2_modif_add
2893 def AddQuadPolygonalFace(self, IdsOfNodes):
2894 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2896 ## Creates both simple and quadratic volume (this is determined
2897 # by the number of given nodes).
2898 # @param IDsOfNodes the list of node IDs for creation of the element.
2899 # The order of nodes in this list should correspond to the description
2900 # of MED. \n This description is located by the following link:
2901 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2902 # @return the Id of the new volumic element
2903 # @ingroup l2_modif_add
2904 def AddVolume(self, IDsOfNodes):
2905 return self.editor.AddVolume(IDsOfNodes)
2907 ## Creates a volume of many faces, giving nodes for each face.
2908 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2909 # @param Quantities the list of integer values, Quantities[i]
2910 # gives the quantity of nodes in face number i.
2911 # @return the Id of the new volumic element
2912 # @ingroup l2_modif_add
2913 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2914 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2916 ## Creates a volume of many faces, giving the IDs of the existing faces.
2917 # @param IdsOfFaces the list of face IDs for volume creation.
2919 # Note: The created volume will refer only to the nodes
2920 # of the given faces, not to the faces themselves.
2921 # @return the Id of the new volumic element
2922 # @ingroup l2_modif_add
2923 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2924 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2927 ## @brief Binds a node to a vertex
2928 # @param NodeID a node ID
2929 # @param Vertex a vertex or vertex ID
2930 # @return True if succeed else raises an exception
2931 # @ingroup l2_modif_add
2932 def SetNodeOnVertex(self, NodeID, Vertex):
2933 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2934 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2938 self.editor.SetNodeOnVertex(NodeID, VertexID)
2939 except SALOME.SALOME_Exception, inst:
2940 raise ValueError, inst.details.text
2944 ## @brief Stores the node position on an edge
2945 # @param NodeID a node ID
2946 # @param Edge an edge or edge ID
2947 # @param paramOnEdge a parameter on the edge where the node is located
2948 # @return True if succeed else raises an exception
2949 # @ingroup l2_modif_add
2950 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2951 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2952 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2956 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2957 except SALOME.SALOME_Exception, inst:
2958 raise ValueError, inst.details.text
2961 ## @brief Stores node position on a face
2962 # @param NodeID a node ID
2963 # @param Face a face or face ID
2964 # @param u U parameter on the face where the node is located
2965 # @param v V parameter on the face where the node is located
2966 # @return True if succeed else raises an exception
2967 # @ingroup l2_modif_add
2968 def SetNodeOnFace(self, NodeID, Face, u, v):
2969 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2970 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
2974 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2975 except SALOME.SALOME_Exception, inst:
2976 raise ValueError, inst.details.text
2979 ## @brief Binds a node to a solid
2980 # @param NodeID a node ID
2981 # @param Solid a solid or solid ID
2982 # @return True if succeed else raises an exception
2983 # @ingroup l2_modif_add
2984 def SetNodeInVolume(self, NodeID, Solid):
2985 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2986 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
2990 self.editor.SetNodeInVolume(NodeID, SolidID)
2991 except SALOME.SALOME_Exception, inst:
2992 raise ValueError, inst.details.text
2995 ## @brief Bind an element to a shape
2996 # @param ElementID an element ID
2997 # @param Shape a shape or shape ID
2998 # @return True if succeed else raises an exception
2999 # @ingroup l2_modif_add
3000 def SetMeshElementOnShape(self, ElementID, Shape):
3001 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3002 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3006 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3007 except SALOME.SALOME_Exception, inst:
3008 raise ValueError, inst.details.text
3012 ## Moves the node with the given id
3013 # @param NodeID the id of the node
3014 # @param x a new X coordinate
3015 # @param y a new Y coordinate
3016 # @param z a new Z coordinate
3017 # @return True if succeed else False
3018 # @ingroup l2_modif_movenode
3019 def MoveNode(self, NodeID, x, y, z):
3020 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3021 if hasVars: self.mesh.SetParameters(Parameters)
3022 return self.editor.MoveNode(NodeID, x, y, z)
3024 ## Finds the node closest to a point and moves it to a point location
3025 # @param x the X coordinate of a point
3026 # @param y the Y coordinate of a point
3027 # @param z the Z coordinate of a point
3028 # @param NodeID if specified (>0), the node with this ID is moved,
3029 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3030 # @return the ID of a node
3031 # @ingroup l2_modif_throughp
3032 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3033 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3034 if hasVars: self.mesh.SetParameters(Parameters)
3035 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3037 ## Finds the node closest to a point
3038 # @param x the X coordinate of a point
3039 # @param y the Y coordinate of a point
3040 # @param z the Z coordinate of a point
3041 # @return the ID of a node
3042 # @ingroup l2_modif_throughp
3043 def FindNodeClosestTo(self, x, y, z):
3044 #preview = self.mesh.GetMeshEditPreviewer()
3045 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3046 return self.editor.FindNodeClosestTo(x, y, z)
3048 ## Finds the elements where a point lays IN or ON
3049 # @param x the X coordinate of a point
3050 # @param y the Y coordinate of a point
3051 # @param z the Z coordinate of a point
3052 # @param elementType type of elements to find; either of
3053 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3054 # means elements of any type excluding nodes, discrete and 0D elements.
3055 # @param meshPart a part of mesh (group, sub-mesh) to search within
3056 # @return list of IDs of found elements
3057 # @ingroup l2_modif_throughp
3058 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3060 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3062 return self.editor.FindElementsByPoint(x, y, z, elementType)
3064 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3065 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3066 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3067 def GetPointState(self, x, y, z):
3068 return self.editor.GetPointState(x, y, z)
3070 ## Finds the node closest to a point and moves it to a point location
3071 # @param x the X coordinate of a point
3072 # @param y the Y coordinate of a point
3073 # @param z the Z coordinate of a point
3074 # @return the ID of a moved node
3075 # @ingroup l2_modif_throughp
3076 def MeshToPassThroughAPoint(self, x, y, z):
3077 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3079 ## Replaces two neighbour triangles sharing Node1-Node2 link
3080 # with the triangles built on the same 4 nodes but having other common link.
3081 # @param NodeID1 the ID of the first node
3082 # @param NodeID2 the ID of the second node
3083 # @return false if proper faces were not found
3084 # @ingroup l2_modif_cutquadr
3085 def InverseDiag(self, NodeID1, NodeID2):
3086 return self.editor.InverseDiag(NodeID1, NodeID2)
3088 ## Replaces two neighbour triangles sharing Node1-Node2 link
3089 # with a quadrangle built on the same 4 nodes.
3090 # @param NodeID1 the ID of the first node
3091 # @param NodeID2 the ID of the second node
3092 # @return false if proper faces were not found
3093 # @ingroup l2_modif_unitetri
3094 def DeleteDiag(self, NodeID1, NodeID2):
3095 return self.editor.DeleteDiag(NodeID1, NodeID2)
3097 ## Reorients elements by ids
3098 # @param IDsOfElements if undefined reorients all mesh elements
3099 # @return True if succeed else False
3100 # @ingroup l2_modif_changori
3101 def Reorient(self, IDsOfElements=None):
3102 if IDsOfElements == None:
3103 IDsOfElements = self.GetElementsId()
3104 return self.editor.Reorient(IDsOfElements)
3106 ## Reorients all elements of the object
3107 # @param theObject mesh, submesh or group
3108 # @return True if succeed else False
3109 # @ingroup l2_modif_changori
3110 def ReorientObject(self, theObject):
3111 if ( isinstance( theObject, Mesh )):
3112 theObject = theObject.GetMesh()
3113 return self.editor.ReorientObject(theObject)
3115 ## Reorient faces contained in \a the2DObject.
3116 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3117 # @param theDirection is a desired direction of normal of \a theFace.
3118 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3119 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3120 # compared with theDirection. It can be either ID of face or a point
3121 # by which the face will be found. The point can be given as either
3122 # a GEOM vertex or a list of point coordinates.
3123 # @return number of reoriented faces
3124 # @ingroup l2_modif_changori
3125 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3126 unRegister = genObjUnRegister()
3128 if isinstance( the2DObject, Mesh ):
3129 the2DObject = the2DObject.GetMesh()
3130 if isinstance( the2DObject, list ):
3131 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3132 unRegister.set( the2DObject )
3133 # check theDirection
3134 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3135 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3136 if isinstance( theDirection, list ):
3137 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3138 # prepare theFace and thePoint
3139 theFace = theFaceOrPoint
3140 thePoint = PointStruct(0,0,0)
3141 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3142 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3144 if isinstance( theFaceOrPoint, list ):
3145 thePoint = PointStruct( *theFaceOrPoint )
3147 if isinstance( theFaceOrPoint, PointStruct ):
3148 thePoint = theFaceOrPoint
3150 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3152 ## Reorient faces according to adjacent volumes.
3153 # @param the2DObject is a mesh, sub-mesh, group or list of
3154 # either IDs of faces or face groups.
3155 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3156 # @param theOutsideNormal to orient faces to have their normals
3157 # pointing either \a outside or \a inside the adjacent volumes.
3158 # @return number of reoriented faces.
3159 # @ingroup l2_modif_changori
3160 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3161 unRegister = genObjUnRegister()
3163 if not isinstance( the2DObject, list ):
3164 the2DObject = [ the2DObject ]
3165 elif the2DObject and isinstance( the2DObject[0], int ):
3166 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3167 unRegister.set( the2DObject )
3168 the2DObject = [ the2DObject ]
3169 for i,obj2D in enumerate( the2DObject ):
3170 if isinstance( obj2D, Mesh ):
3171 the2DObject[i] = obj2D.GetMesh()
3172 if isinstance( obj2D, list ):
3173 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3174 unRegister.set( the2DObject[i] )
3176 if isinstance( the3DObject, Mesh ):
3177 the3DObject = the3DObject.GetMesh()
3178 if isinstance( the3DObject, list ):
3179 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3180 unRegister.set( the3DObject )
3181 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3183 ## Fuses the neighbouring triangles into quadrangles.
3184 # @param IDsOfElements The triangles to be fused.
3185 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3186 # applied to possible quadrangles to choose a neighbour to fuse with.
3187 # Type SMESH.FunctorType._items in the Python Console to see all items.
3188 # Note that not all items correspond to numerical functors.
3189 # @param MaxAngle is the maximum angle between element normals at which the fusion
3190 # is still performed; theMaxAngle is mesured in radians.
3191 # Also it could be a name of variable which defines angle in degrees.
3192 # @return TRUE in case of success, FALSE otherwise.
3193 # @ingroup l2_modif_unitetri
3194 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3195 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3196 self.mesh.SetParameters(Parameters)
3197 if not IDsOfElements:
3198 IDsOfElements = self.GetElementsId()
3199 Functor = self.smeshpyD.GetFunctor(theCriterion)
3200 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3202 ## Fuses the neighbouring triangles of the object into quadrangles
3203 # @param theObject is mesh, submesh or group
3204 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3205 # applied to possible quadrangles to choose a neighbour to fuse with.
3206 # Type SMESH.FunctorType._items in the Python Console to see all items.
3207 # Note that not all items correspond to numerical functors.
3208 # @param MaxAngle a max angle between element normals at which the fusion
3209 # is still performed; theMaxAngle is mesured in radians.
3210 # @return TRUE in case of success, FALSE otherwise.
3211 # @ingroup l2_modif_unitetri
3212 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3213 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3214 self.mesh.SetParameters(Parameters)
3215 if isinstance( theObject, Mesh ):
3216 theObject = theObject.GetMesh()
3217 Functor = self.smeshpyD.GetFunctor(theCriterion)
3218 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3220 ## Splits quadrangles into triangles.
3221 # @param IDsOfElements the faces to be splitted.
3222 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3223 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3224 # value, then quadrangles will be split by the smallest diagonal.
3225 # Type SMESH.FunctorType._items in the Python Console to see all items.
3226 # Note that not all items correspond to numerical functors.
3227 # @return TRUE in case of success, FALSE otherwise.
3228 # @ingroup l2_modif_cutquadr
3229 def QuadToTri (self, IDsOfElements, theCriterion = None):
3230 if IDsOfElements == []:
3231 IDsOfElements = self.GetElementsId()
3232 if theCriterion is None:
3233 theCriterion = FT_MaxElementLength2D
3234 Functor = self.smeshpyD.GetFunctor(theCriterion)
3235 return self.editor.QuadToTri(IDsOfElements, Functor)
3237 ## Splits quadrangles into triangles.
3238 # @param theObject the object from which the list of elements is taken,
3239 # this is mesh, submesh or group
3240 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3241 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3242 # value, then quadrangles will be split by the smallest diagonal.
3243 # Type SMESH.FunctorType._items in the Python Console to see all items.
3244 # Note that not all items correspond to numerical functors.
3245 # @return TRUE in case of success, FALSE otherwise.
3246 # @ingroup l2_modif_cutquadr
3247 def QuadToTriObject (self, theObject, theCriterion = None):
3248 if ( isinstance( theObject, Mesh )):
3249 theObject = theObject.GetMesh()
3250 if theCriterion is None:
3251 theCriterion = FT_MaxElementLength2D
3252 Functor = self.smeshpyD.GetFunctor(theCriterion)
3253 return self.editor.QuadToTriObject(theObject, Functor)
3255 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3257 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3258 # group or a list of face IDs. By default all quadrangles are split
3259 # @ingroup l2_modif_cutquadr
3260 def QuadTo4Tri (self, theElements=[]):
3261 unRegister = genObjUnRegister()
3262 if isinstance( theElements, Mesh ):
3263 theElements = theElements.mesh
3264 elif not theElements:
3265 theElements = self.mesh
3266 elif isinstance( theElements, list ):
3267 theElements = self.GetIDSource( theElements, SMESH.FACE )
3268 unRegister.set( theElements )
3269 return self.editor.QuadTo4Tri( theElements )
3271 ## Splits quadrangles into triangles.
3272 # @param IDsOfElements the faces to be splitted
3273 # @param Diag13 is used to choose a diagonal for splitting.
3274 # @return TRUE in case of success, FALSE otherwise.
3275 # @ingroup l2_modif_cutquadr
3276 def SplitQuad (self, IDsOfElements, Diag13):
3277 if IDsOfElements == []:
3278 IDsOfElements = self.GetElementsId()
3279 return self.editor.SplitQuad(IDsOfElements, Diag13)
3281 ## Splits quadrangles into triangles.
3282 # @param theObject the object from which the list of elements is taken,
3283 # this is mesh, submesh or group
3284 # @param Diag13 is used to choose a diagonal for splitting.
3285 # @return TRUE in case of success, FALSE otherwise.
3286 # @ingroup l2_modif_cutquadr
3287 def SplitQuadObject (self, theObject, Diag13):
3288 if ( isinstance( theObject, Mesh )):
3289 theObject = theObject.GetMesh()
3290 return self.editor.SplitQuadObject(theObject, Diag13)
3292 ## Finds a better splitting of the given quadrangle.
3293 # @param IDOfQuad the ID of the quadrangle to be splitted.
3294 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3295 # choose a diagonal for splitting.
3296 # Type SMESH.FunctorType._items in the Python Console to see all items.
3297 # Note that not all items correspond to numerical functors.
3298 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3299 # diagonal is better, 0 if error occurs.
3300 # @ingroup l2_modif_cutquadr
3301 def BestSplit (self, IDOfQuad, theCriterion):
3302 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3304 ## Splits volumic elements into tetrahedrons
3305 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3306 # @param method flags passing splitting method:
3307 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3308 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3309 # @ingroup l2_modif_cutquadr
3310 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3311 unRegister = genObjUnRegister()
3312 if isinstance( elems, Mesh ):
3313 elems = elems.GetMesh()
3314 if ( isinstance( elems, list )):
3315 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3316 unRegister.set( elems )
3317 self.editor.SplitVolumesIntoTetra(elems, method)
3320 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3321 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3322 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3323 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3324 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3325 # will be split in order to keep the mesh conformal.
3326 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3327 # if None (default), all bi-quadratic elements will be split
3328 # @ingroup l2_modif_cutquadr
3329 def SplitBiQuadraticIntoLinear(self, elems=None):
3330 unRegister = genObjUnRegister()
3331 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3332 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3333 unRegister.set( elems )
3335 elems = [ self.GetMesh() ]
3336 if isinstance( elems, Mesh ):
3337 elems = [ elems.GetMesh() ]
3338 if not isinstance( elems, list ):
3340 self.editor.SplitBiQuadraticIntoLinear( elems )
3342 ## Splits hexahedra into prisms
3343 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3344 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3345 # gives a normal vector defining facets to split into triangles.
3346 # @a startHexPoint can be either a triple of coordinates or a vertex.
3347 # @param facetNormal a normal to a facet to split into triangles of a
3348 # hexahedron found by @a startHexPoint.
3349 # @a facetNormal can be either a triple of coordinates or an edge.
3350 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3351 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3352 # @param allDomains if @c False, only hexahedra adjacent to one closest
3353 # to @a startHexPoint are split, else @a startHexPoint
3354 # is used to find the facet to split in all domains present in @a elems.
3355 # @ingroup l2_modif_cutquadr
3356 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3357 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3359 unRegister = genObjUnRegister()
3360 if isinstance( elems, Mesh ):
3361 elems = elems.GetMesh()
3362 if ( isinstance( elems, list )):
3363 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3364 unRegister.set( elems )
3367 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3368 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3369 elif isinstance( startHexPoint, list ):
3370 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3373 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3374 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3375 elif isinstance( facetNormal, list ):
3376 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3379 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3381 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3383 ## Splits quadrangle faces near triangular facets of volumes
3385 # @ingroup l1_auxiliary
3386 def SplitQuadsNearTriangularFacets(self):
3387 faces_array = self.GetElementsByType(SMESH.FACE)
3388 for face_id in faces_array:
3389 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3390 quad_nodes = self.mesh.GetElemNodes(face_id)
3391 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3392 isVolumeFound = False
3393 for node1_elem in node1_elems:
3394 if not isVolumeFound:
3395 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3396 nb_nodes = self.GetElemNbNodes(node1_elem)
3397 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3398 volume_elem = node1_elem
3399 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3400 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3401 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3402 isVolumeFound = True
3403 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3404 self.SplitQuad([face_id], False) # diagonal 2-4
3405 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3406 isVolumeFound = True
3407 self.SplitQuad([face_id], True) # diagonal 1-3
3408 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3409 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3410 isVolumeFound = True
3411 self.SplitQuad([face_id], True) # diagonal 1-3
3413 ## @brief Splits hexahedrons into tetrahedrons.
3415 # This operation uses pattern mapping functionality for splitting.
3416 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3417 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3418 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3419 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3420 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3421 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3422 # @return TRUE in case of success, FALSE otherwise.
3423 # @ingroup l1_auxiliary
3424 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3425 # Pattern: 5.---------.6
3430 # (0,0,1) 4.---------.7 * |
3437 # (0,0,0) 0.---------.3
3438 pattern_tetra = "!!! Nb of points: \n 8 \n\
3448 !!! Indices of points of 6 tetras: \n\
3456 pattern = self.smeshpyD.GetPattern()
3457 isDone = pattern.LoadFromFile(pattern_tetra)
3459 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3462 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3463 isDone = pattern.MakeMesh(self.mesh, False, False)
3464 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3466 # split quafrangle faces near triangular facets of volumes
3467 self.SplitQuadsNearTriangularFacets()
3471 ## @brief Split hexahedrons into prisms.
3473 # Uses the pattern mapping functionality for splitting.
3474 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3475 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3476 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3477 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3478 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3479 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3480 # @return TRUE in case of success, FALSE otherwise.
3481 # @ingroup l1_auxiliary
3482 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3483 # Pattern: 5.---------.6
3488 # (0,0,1) 4.---------.7 |
3495 # (0,0,0) 0.---------.3
3496 pattern_prism = "!!! Nb of points: \n 8 \n\
3506 !!! Indices of points of 2 prisms: \n\
3510 pattern = self.smeshpyD.GetPattern()
3511 isDone = pattern.LoadFromFile(pattern_prism)
3513 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3516 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3517 isDone = pattern.MakeMesh(self.mesh, False, False)
3518 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3520 # Splits quafrangle faces near triangular facets of volumes
3521 self.SplitQuadsNearTriangularFacets()
3525 ## Smoothes elements
3526 # @param IDsOfElements the list if ids of elements to smooth
3527 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3528 # Note that nodes built on edges and boundary nodes are always fixed.
3529 # @param MaxNbOfIterations the maximum number of iterations
3530 # @param MaxAspectRatio varies in range [1.0, inf]
3531 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3532 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3533 # @return TRUE in case of success, FALSE otherwise.
3534 # @ingroup l2_modif_smooth
3535 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3536 MaxNbOfIterations, MaxAspectRatio, Method):
3537 if IDsOfElements == []:
3538 IDsOfElements = self.GetElementsId()
3539 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3540 self.mesh.SetParameters(Parameters)
3541 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3542 MaxNbOfIterations, MaxAspectRatio, Method)
3544 ## Smoothes elements which belong to the given object
3545 # @param theObject the object to smooth
3546 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3547 # Note that nodes built on edges and boundary nodes are always fixed.
3548 # @param MaxNbOfIterations the maximum number of iterations
3549 # @param MaxAspectRatio varies in range [1.0, inf]
3550 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3551 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3552 # @return TRUE in case of success, FALSE otherwise.
3553 # @ingroup l2_modif_smooth
3554 def SmoothObject(self, theObject, IDsOfFixedNodes,
3555 MaxNbOfIterations, MaxAspectRatio, Method):
3556 if ( isinstance( theObject, Mesh )):
3557 theObject = theObject.GetMesh()
3558 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3559 MaxNbOfIterations, MaxAspectRatio, Method)
3561 ## Parametrically smoothes the given elements
3562 # @param IDsOfElements the list if ids of elements to smooth
3563 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3564 # Note that nodes built on edges and boundary nodes are always fixed.
3565 # @param MaxNbOfIterations the maximum number of iterations
3566 # @param MaxAspectRatio varies in range [1.0, inf]
3567 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3568 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3569 # @return TRUE in case of success, FALSE otherwise.
3570 # @ingroup l2_modif_smooth
3571 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3572 MaxNbOfIterations, MaxAspectRatio, Method):
3573 if IDsOfElements == []:
3574 IDsOfElements = self.GetElementsId()
3575 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3576 self.mesh.SetParameters(Parameters)
3577 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3578 MaxNbOfIterations, MaxAspectRatio, Method)
3580 ## Parametrically smoothes the elements which belong to the given object
3581 # @param theObject the object to smooth
3582 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3583 # Note that nodes built on edges and boundary nodes are always fixed.
3584 # @param MaxNbOfIterations the maximum number of iterations
3585 # @param MaxAspectRatio varies in range [1.0, inf]
3586 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3587 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3588 # @return TRUE in case of success, FALSE otherwise.
3589 # @ingroup l2_modif_smooth
3590 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3591 MaxNbOfIterations, MaxAspectRatio, Method):
3592 if ( isinstance( theObject, Mesh )):
3593 theObject = theObject.GetMesh()
3594 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3595 MaxNbOfIterations, MaxAspectRatio, Method)
3597 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3598 # them with quadratic with the same id.
3599 # @param theForce3d new node creation method:
3600 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3601 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3602 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3603 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3604 # @ingroup l2_modif_tofromqu
3605 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3606 if isinstance( theSubMesh, Mesh ):
3607 theSubMesh = theSubMesh.mesh
3609 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3612 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3614 self.editor.ConvertToQuadratic(theForce3d)
3615 error = self.editor.GetLastError()
3616 if error and error.comment:
3619 ## Converts the mesh from quadratic to ordinary,
3620 # deletes old quadratic elements, \n replacing
3621 # them with ordinary mesh elements with the same id.
3622 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3623 # @ingroup l2_modif_tofromqu
3624 def ConvertFromQuadratic(self, theSubMesh=None):
3626 self.editor.ConvertFromQuadraticObject(theSubMesh)
3628 return self.editor.ConvertFromQuadratic()
3630 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3631 # @return TRUE if operation has been completed successfully, FALSE otherwise
3632 # @ingroup l2_modif_edit
3633 def Make2DMeshFrom3D(self):
3634 return self.editor.Make2DMeshFrom3D()
3636 ## Creates missing boundary elements
3637 # @param elements - elements whose boundary is to be checked:
3638 # mesh, group, sub-mesh or list of elements
3639 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3640 # @param dimension - defines type of boundary elements to create, either of
3641 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3642 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3643 # @param groupName - a name of group to store created boundary elements in,
3644 # "" means not to create the group
3645 # @param meshName - a name of new mesh to store created boundary elements in,
3646 # "" means not to create the new mesh
3647 # @param toCopyElements - if true, the checked elements will be copied into
3648 # the new mesh else only boundary elements will be copied into the new mesh
3649 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3650 # boundary elements will be copied into the new mesh
3651 # @return tuple (mesh, group) where boundary elements were added to
3652 # @ingroup l2_modif_edit
3653 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3654 toCopyElements=False, toCopyExistingBondary=False):
3655 unRegister = genObjUnRegister()
3656 if isinstance( elements, Mesh ):
3657 elements = elements.GetMesh()
3658 if ( isinstance( elements, list )):
3659 elemType = SMESH.ALL
3660 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3661 elements = self.editor.MakeIDSource(elements, elemType)
3662 unRegister.set( elements )
3663 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3664 toCopyElements,toCopyExistingBondary)
3665 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3669 # @brief Creates missing boundary elements around either the whole mesh or
3670 # groups of elements
3671 # @param dimension - defines type of boundary elements to create, either of
3672 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3673 # @param groupName - a name of group to store all boundary elements in,
3674 # "" means not to create the group
3675 # @param meshName - a name of a new mesh, which is a copy of the initial
3676 # mesh + created boundary elements; "" means not to create the new mesh
3677 # @param toCopyAll - if true, the whole initial mesh will be copied into
3678 # the new mesh else only boundary elements will be copied into the new mesh
3679 # @param groups - groups of elements to make boundary around
3680 # @retval tuple( long, mesh, groups )
3681 # long - number of added boundary elements
3682 # mesh - the mesh where elements were added to
3683 # group - the group of boundary elements or None
3685 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3686 toCopyAll=False, groups=[]):
3687 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3689 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3690 return nb, mesh, group
3692 ## Renumber mesh nodes (Obsolete, does nothing)
3693 # @ingroup l2_modif_renumber
3694 def RenumberNodes(self):
3695 self.editor.RenumberNodes()
3697 ## Renumber mesh elements (Obsole, does nothing)
3698 # @ingroup l2_modif_renumber
3699 def RenumberElements(self):
3700 self.editor.RenumberElements()
3702 ## Private method converting \a arg into a list of SMESH_IdSource's
3703 def _getIdSourceList(self, arg, idType, unRegister):
3704 if arg and isinstance( arg, list ):
3705 if isinstance( arg[0], int ):
3706 arg = self.GetIDSource( arg, idType )
3707 unRegister.set( arg )
3708 elif isinstance( arg[0], Mesh ):
3709 arg[0] = arg[0].GetMesh()
3710 elif isinstance( arg, Mesh ):
3712 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3716 ## Generates new elements by rotation of the given elements and nodes around the axis
3717 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3718 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3719 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3720 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3721 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3722 # which defines angle in degrees
3723 # @param NbOfSteps the number of steps
3724 # @param Tolerance tolerance
3725 # @param MakeGroups forces the generation of new groups from existing ones
3726 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3727 # of all steps, else - size of each step
3728 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3729 # @ingroup l2_modif_extrurev
3730 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3731 MakeGroups=False, TotalAngle=False):
3732 unRegister = genObjUnRegister()
3733 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3734 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3735 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3737 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3738 Axis = self.smeshpyD.GetAxisStruct( Axis )
3739 if isinstance( Axis, list ):
3740 Axis = SMESH.AxisStruct( *Axis )
3742 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3743 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3744 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3745 self.mesh.SetParameters(Parameters)
3746 if TotalAngle and NbOfSteps:
3747 AngleInRadians /= NbOfSteps
3748 return self.editor.RotationSweepObjects( nodes, edges, faces,
3749 Axis, AngleInRadians,
3750 NbOfSteps, Tolerance, MakeGroups)
3752 ## Generates new elements by rotation of the elements around the axis
3753 # @param IDsOfElements the list of ids of elements to sweep
3754 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3755 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3756 # @param NbOfSteps the number of steps
3757 # @param Tolerance tolerance
3758 # @param MakeGroups forces the generation of new groups from existing ones
3759 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3760 # of all steps, else - size of each step
3761 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3762 # @ingroup l2_modif_extrurev
3763 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3764 MakeGroups=False, TotalAngle=False):
3765 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3766 AngleInRadians, NbOfSteps, Tolerance,
3767 MakeGroups, TotalAngle)
3769 ## Generates new elements by rotation of the elements of object around the axis
3770 # @param theObject object which elements should be sweeped.
3771 # It can be a mesh, a sub mesh or a group.
3772 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3773 # @param AngleInRadians the angle of Rotation
3774 # @param NbOfSteps number of steps
3775 # @param Tolerance tolerance
3776 # @param MakeGroups forces the generation of new groups from existing ones
3777 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3778 # of all steps, else - size of each step
3779 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3780 # @ingroup l2_modif_extrurev
3781 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3782 MakeGroups=False, TotalAngle=False):
3783 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3784 AngleInRadians, NbOfSteps, Tolerance,
3785 MakeGroups, TotalAngle )
3787 ## Generates new elements by rotation of the elements of object around the axis
3788 # @param theObject object which elements should be sweeped.
3789 # It can be a mesh, a sub mesh or a group.
3790 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3791 # @param AngleInRadians the angle of Rotation
3792 # @param NbOfSteps number of steps
3793 # @param Tolerance tolerance
3794 # @param MakeGroups forces the generation of new groups from existing ones
3795 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3796 # of all steps, else - size of each step
3797 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3798 # @ingroup l2_modif_extrurev
3799 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3800 MakeGroups=False, TotalAngle=False):
3801 return self.RotationSweepObjects([],theObject,[], Axis,
3802 AngleInRadians, NbOfSteps, Tolerance,
3803 MakeGroups, TotalAngle)
3805 ## Generates new elements by rotation of the elements of object around the axis
3806 # @param theObject object which elements should be sweeped.
3807 # It can be a mesh, a sub mesh or a group.
3808 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3809 # @param AngleInRadians the angle of Rotation
3810 # @param NbOfSteps number of steps
3811 # @param Tolerance tolerance
3812 # @param MakeGroups forces the generation of new groups from existing ones
3813 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3814 # of all steps, else - size of each step
3815 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3816 # @ingroup l2_modif_extrurev
3817 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3818 MakeGroups=False, TotalAngle=False):
3819 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3820 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3822 ## Generates new elements by extrusion of the given elements and nodes
3823 # @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3824 # @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3825 # @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3826 # @param StepVector vector or DirStruct or 3 vector components, defining
3827 # the direction and value of extrusion for one step (the total extrusion
3828 # length will be NbOfSteps * ||StepVector||)
3829 # @param NbOfSteps the number of steps
3830 # @param MakeGroups forces the generation of new groups from existing ones
3831 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3832 # @ingroup l2_modif_extrurev
3833 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3834 unRegister = genObjUnRegister()
3835 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3836 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3837 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3839 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3840 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3841 if isinstance( StepVector, list ):
3842 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3844 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3845 Parameters = StepVector.PS.parameters + var_separator + Parameters
3846 self.mesh.SetParameters(Parameters)
3848 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3849 StepVector, NbOfSteps, MakeGroups)
3852 ## Generates new elements by extrusion of the elements with given ids
3853 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3854 # @param StepVector vector or DirStruct or 3 vector components, defining
3855 # the direction and value of extrusion for one step (the total extrusion
3856 # length will be NbOfSteps * ||StepVector||)
3857 # @param NbOfSteps the number of steps
3858 # @param MakeGroups forces the generation of new groups from existing ones
3859 # @param IsNodes is True if elements with given ids are nodes
3860 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3861 # @ingroup l2_modif_extrurev
3862 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3864 if IsNodes: n = IDsOfElements
3865 else : e,f, = IDsOfElements,IDsOfElements
3866 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3868 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3869 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3870 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3871 # @param StepSize length of one extrusion step (the total extrusion
3872 # length will be \a NbOfSteps * \a StepSize ).
3873 # @param NbOfSteps number of extrusion steps.
3874 # @param ByAverageNormal if True each node is translated by \a StepSize
3875 # along the average of the normal vectors to the faces sharing the node;
3876 # else each node is translated along the same average normal till
3877 # intersection with the plane got by translation of the face sharing
3878 # the node along its own normal by \a StepSize.
3879 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3880 # for every node of \a Elements.
3881 # @param MakeGroups forces generation of new groups from existing ones.
3882 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3883 # is not yet implemented. This parameter is used if \a Elements contains
3884 # both faces and edges, i.e. \a Elements is a Mesh.
3885 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3886 # empty list otherwise.
3887 # @ingroup l2_modif_extrurev
3888 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3889 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3890 unRegister = genObjUnRegister()
3891 if isinstance( Elements, Mesh ):
3892 Elements = [ Elements.GetMesh() ]
3893 if isinstance( Elements, list ):
3895 raise RuntimeError, "Elements empty!"
3896 if isinstance( Elements[0], int ):
3897 Elements = self.GetIDSource( Elements, SMESH.ALL )
3898 unRegister.set( Elements )
3899 if not isinstance( Elements, list ):
3900 Elements = [ Elements ]
3901 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3902 self.mesh.SetParameters(Parameters)
3903 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3904 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3906 ## Generates new elements by extrusion of the elements or nodes which belong to the object
3907 # @param theObject the object whose elements or nodes should be processed.
3908 # It can be a mesh, a sub-mesh or a group.
3909 # @param StepVector vector or DirStruct or 3 vector components, defining
3910 # the direction and value of extrusion for one step (the total extrusion
3911 # length will be NbOfSteps * ||StepVector||)
3912 # @param NbOfSteps the number of steps
3913 # @param MakeGroups forces the generation of new groups from existing ones
3914 # @param IsNodes is True if elements to extrude are nodes
3915 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3916 # @ingroup l2_modif_extrurev
3917 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3919 if IsNodes: n = theObject
3920 else : e,f, = theObject,theObject
3921 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3923 ## Generates new elements by extrusion of edges which belong to the object
3924 # @param theObject object whose 1D elements should be processed.
3925 # It can be a mesh, a sub-mesh or a group.
3926 # @param StepVector vector or DirStruct or 3 vector components, defining
3927 # the direction and value of extrusion for one step (the total extrusion
3928 # length will be NbOfSteps * ||StepVector||)
3929 # @param NbOfSteps the number of steps
3930 # @param MakeGroups to generate new groups from existing ones
3931 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3932 # @ingroup l2_modif_extrurev
3933 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3934 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3936 ## Generates new elements by extrusion of faces which belong to the object
3937 # @param theObject object whose 2D elements should be processed.
3938 # It can be a mesh, a sub-mesh or a group.
3939 # @param StepVector vector or DirStruct or 3 vector components, defining
3940 # the direction and value of extrusion for one step (the total extrusion
3941 # length will be NbOfSteps * ||StepVector||)
3942 # @param NbOfSteps the number of steps
3943 # @param MakeGroups forces the generation of new groups from existing ones
3944 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3945 # @ingroup l2_modif_extrurev
3946 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3947 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3949 ## Generates new elements by extrusion of the elements with given ids
3950 # @param IDsOfElements is ids of elements
3951 # @param StepVector vector or DirStruct or 3 vector components, defining
3952 # the direction and value of extrusion for one step (the total extrusion
3953 # length will be NbOfSteps * ||StepVector||)
3954 # @param NbOfSteps the number of steps
3955 # @param ExtrFlags sets flags for extrusion
3956 # @param SewTolerance uses for comparing locations of nodes if flag
3957 # EXTRUSION_FLAG_SEW is set
3958 # @param MakeGroups forces the generation of new groups from existing ones
3959 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3960 # @ingroup l2_modif_extrurev
3961 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3962 ExtrFlags, SewTolerance, MakeGroups=False):
3963 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3964 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3965 if isinstance( StepVector, list ):
3966 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3967 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3968 ExtrFlags, SewTolerance, MakeGroups)
3970 ## Generates new elements by extrusion of the given elements and nodes along the path.
3971 # The path of extrusion must be a meshed edge.
3972 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3973 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3974 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3975 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3976 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3977 # contains not only path segments, else it can be None
3978 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3979 # @param HasAngles allows the shape to be rotated around the path
3980 # to get the resulting mesh in a helical fashion
3981 # @param Angles list of angles
3982 # @param LinearVariation forces the computation of rotation angles as linear
3983 # variation of the given Angles along path steps
3984 # @param HasRefPoint allows using the reference point
3985 # @param RefPoint the point around which the shape is rotated (the mass center of the
3986 # shape by default). The User can specify any point as the Reference Point.
3987 # @param MakeGroups forces the generation of new groups from existing ones
3988 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3989 # @ingroup l2_modif_extrurev
3990 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3991 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3992 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3993 unRegister = genObjUnRegister()
3994 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3995 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3996 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3998 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3999 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4000 if isinstance( RefPoint, list ):
4001 if not RefPoint: RefPoint = [0,0,0]
4002 RefPoint = SMESH.PointStruct( *RefPoint )
4003 if isinstance( PathMesh, Mesh ):
4004 PathMesh = PathMesh.GetMesh()
4005 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4006 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4007 self.mesh.SetParameters(Parameters)
4008 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4009 PathMesh, PathShape, NodeStart,
4010 HasAngles, Angles, LinearVariation,
4011 HasRefPoint, RefPoint, MakeGroups)
4013 ## Generates new elements by extrusion of the given elements
4014 # The path of extrusion must be a meshed edge.
4015 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4016 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4017 # @param NodeStart the start node from Path. Defines the direction of extrusion
4018 # @param HasAngles allows the shape to be rotated around the path
4019 # to get the resulting mesh in a helical fashion
4020 # @param Angles list of angles in radians
4021 # @param LinearVariation forces the computation of rotation angles as linear
4022 # variation of the given Angles along path steps
4023 # @param HasRefPoint allows using the reference point
4024 # @param RefPoint the point around which the elements are rotated (the mass
4025 # center of the elements by default).
4026 # The User can specify any point as the Reference Point.
4027 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4028 # @param MakeGroups forces the generation of new groups from existing ones
4029 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4030 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4031 # only SMESH::Extrusion_Error otherwise
4032 # @ingroup l2_modif_extrurev
4033 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4034 HasAngles=False, Angles=[], LinearVariation=False,
4035 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4036 ElemType=SMESH.FACE):
4038 if ElemType == SMESH.NODE: n = Base
4039 if ElemType == SMESH.EDGE: e = Base
4040 if ElemType == SMESH.FACE: f = Base
4041 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4042 HasAngles, Angles, LinearVariation,
4043 HasRefPoint, RefPoint, MakeGroups)
4044 if MakeGroups: return gr,er
4047 ## Generates new elements by extrusion of the given elements
4048 # The path of extrusion must be a meshed edge.
4049 # @param IDsOfElements ids of elements
4050 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4051 # @param PathShape shape(edge) defines the sub-mesh for the path
4052 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4053 # @param HasAngles allows the shape to be rotated around the path
4054 # to get the resulting mesh in a helical fashion
4055 # @param Angles list of angles in radians
4056 # @param HasRefPoint allows using the reference point
4057 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4058 # The User can specify any point as the Reference Point.
4059 # @param MakeGroups forces the generation of new groups from existing ones
4060 # @param LinearVariation forces the computation of rotation angles as linear
4061 # variation of the given Angles along path steps
4062 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4063 # only SMESH::Extrusion_Error otherwise
4064 # @ingroup l2_modif_extrurev
4065 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4066 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4067 MakeGroups=False, LinearVariation=False):
4068 n,e,f = [],IDsOfElements,IDsOfElements
4069 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4070 NodeStart, HasAngles, Angles,
4072 HasRefPoint, RefPoint, MakeGroups)
4073 if MakeGroups: return gr,er
4076 ## Generates new elements by extrusion of the elements which belong to the object
4077 # The path of extrusion must be a meshed edge.
4078 # @param theObject the object whose elements should be processed.
4079 # It can be a mesh, a sub-mesh or a group.
4080 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4081 # @param PathShape shape(edge) defines the sub-mesh for the path
4082 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4083 # @param HasAngles allows the shape to be rotated around the path
4084 # to get the resulting mesh in a helical fashion
4085 # @param Angles list of angles
4086 # @param HasRefPoint allows using the reference point
4087 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4088 # The User can specify any point as the Reference Point.
4089 # @param MakeGroups forces the generation of new groups from existing ones
4090 # @param LinearVariation forces the computation of rotation angles as linear
4091 # variation of the given Angles along path steps
4092 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4093 # only SMESH::Extrusion_Error otherwise
4094 # @ingroup l2_modif_extrurev
4095 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4096 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4097 MakeGroups=False, LinearVariation=False):
4098 n,e,f = [],theObject,theObject
4099 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4100 HasAngles, Angles, LinearVariation,
4101 HasRefPoint, RefPoint, MakeGroups)
4102 if MakeGroups: return gr,er
4105 ## Generates new elements by extrusion of mesh segments which belong to the object
4106 # The path of extrusion must be a meshed edge.
4107 # @param theObject the object whose 1D elements should be processed.
4108 # It can be a mesh, a sub-mesh or a group.
4109 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4110 # @param PathShape shape(edge) defines the sub-mesh for the path
4111 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4112 # @param HasAngles allows the shape to be rotated around the path
4113 # to get the resulting mesh in a helical fashion
4114 # @param Angles list of angles
4115 # @param HasRefPoint allows using the reference point
4116 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4117 # The User can specify any point as the Reference Point.
4118 # @param MakeGroups forces the generation of new groups from existing ones
4119 # @param LinearVariation forces the computation of rotation angles as linear
4120 # variation of the given Angles along path steps
4121 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4122 # only SMESH::Extrusion_Error otherwise
4123 # @ingroup l2_modif_extrurev
4124 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4125 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4126 MakeGroups=False, LinearVariation=False):
4127 n,e,f = [],theObject,[]
4128 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4129 HasAngles, Angles, LinearVariation,
4130 HasRefPoint, RefPoint, MakeGroups)
4131 if MakeGroups: return gr,er
4134 ## Generates new elements by extrusion of faces which belong to the object
4135 # The path of extrusion must be a meshed edge.
4136 # @param theObject the object whose 2D elements should be processed.
4137 # It can be a mesh, a sub-mesh or a group.
4138 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4139 # @param PathShape shape(edge) defines the sub-mesh for the path
4140 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4141 # @param HasAngles allows the shape to be rotated around the path
4142 # to get the resulting mesh in a helical fashion
4143 # @param Angles list of angles
4144 # @param HasRefPoint allows using the reference point
4145 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4146 # The User can specify any point as the Reference Point.
4147 # @param MakeGroups forces the generation of new groups from existing ones
4148 # @param LinearVariation forces the computation of rotation angles as linear
4149 # variation of the given Angles along path steps
4150 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4151 # only SMESH::Extrusion_Error otherwise
4152 # @ingroup l2_modif_extrurev
4153 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4154 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4155 MakeGroups=False, LinearVariation=False):
4156 n,e,f = [],[],theObject
4157 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4158 HasAngles, Angles, LinearVariation,
4159 HasRefPoint, RefPoint, MakeGroups)
4160 if MakeGroups: return gr,er
4163 ## Creates a symmetrical copy of mesh elements
4164 # @param IDsOfElements list of elements ids
4165 # @param Mirror is AxisStruct or geom object(point, line, plane)
4166 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4167 # If the Mirror is a geom object this parameter is unnecessary
4168 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4169 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4170 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4171 # @ingroup l2_modif_trsf
4172 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4173 if IDsOfElements == []:
4174 IDsOfElements = self.GetElementsId()
4175 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4176 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4177 theMirrorType = Mirror._mirrorType
4179 self.mesh.SetParameters(Mirror.parameters)
4180 if Copy and MakeGroups:
4181 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4182 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4185 ## Creates a new mesh by a symmetrical copy of mesh elements
4186 # @param IDsOfElements the list of elements ids
4187 # @param Mirror is AxisStruct or geom object (point, line, plane)
4188 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4189 # If the Mirror is a geom object this parameter is unnecessary
4190 # @param MakeGroups to generate new groups from existing ones
4191 # @param NewMeshName a name of the new mesh to create
4192 # @return instance of Mesh class
4193 # @ingroup l2_modif_trsf
4194 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4195 if IDsOfElements == []:
4196 IDsOfElements = self.GetElementsId()
4197 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4198 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4199 theMirrorType = Mirror._mirrorType
4201 self.mesh.SetParameters(Mirror.parameters)
4202 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4203 MakeGroups, NewMeshName)
4204 return Mesh(self.smeshpyD,self.geompyD,mesh)
4206 ## Creates a symmetrical copy of the object
4207 # @param theObject mesh, submesh or group
4208 # @param Mirror AxisStruct or geom object (point, line, plane)
4209 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4210 # If the Mirror is a geom object this parameter is unnecessary
4211 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4212 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4213 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4214 # @ingroup l2_modif_trsf
4215 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4216 if ( isinstance( theObject, Mesh )):
4217 theObject = theObject.GetMesh()
4218 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4219 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4220 theMirrorType = Mirror._mirrorType
4222 self.mesh.SetParameters(Mirror.parameters)
4223 if Copy and MakeGroups:
4224 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4225 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4228 ## Creates a new mesh by a symmetrical copy of the object
4229 # @param theObject mesh, submesh or group
4230 # @param Mirror AxisStruct or geom object (point, line, plane)
4231 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4232 # If the Mirror is a geom object this parameter is unnecessary
4233 # @param MakeGroups forces the generation of new groups from existing ones
4234 # @param NewMeshName the name of the new mesh to create
4235 # @return instance of Mesh class
4236 # @ingroup l2_modif_trsf
4237 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4238 if ( isinstance( theObject, Mesh )):
4239 theObject = theObject.GetMesh()
4240 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4241 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4242 theMirrorType = Mirror._mirrorType
4244 self.mesh.SetParameters(Mirror.parameters)
4245 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4246 MakeGroups, NewMeshName)
4247 return Mesh( self.smeshpyD,self.geompyD,mesh )
4249 ## Translates the elements
4250 # @param IDsOfElements list of elements ids
4251 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4252 # @param Copy allows copying the translated elements
4253 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4254 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4255 # @ingroup l2_modif_trsf
4256 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4257 if IDsOfElements == []:
4258 IDsOfElements = self.GetElementsId()
4259 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4260 Vector = self.smeshpyD.GetDirStruct(Vector)
4261 if isinstance( Vector, list ):
4262 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4263 self.mesh.SetParameters(Vector.PS.parameters)
4264 if Copy and MakeGroups:
4265 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4266 self.editor.Translate(IDsOfElements, Vector, Copy)
4269 ## Creates a new mesh of translated elements
4270 # @param IDsOfElements list of elements ids
4271 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4272 # @param MakeGroups forces the generation of new groups from existing ones
4273 # @param NewMeshName the name of the newly created mesh
4274 # @return instance of Mesh class
4275 # @ingroup l2_modif_trsf
4276 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4277 if IDsOfElements == []:
4278 IDsOfElements = self.GetElementsId()
4279 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4280 Vector = self.smeshpyD.GetDirStruct(Vector)
4281 if isinstance( Vector, list ):
4282 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4283 self.mesh.SetParameters(Vector.PS.parameters)
4284 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4285 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4287 ## Translates the object
4288 # @param theObject the object to translate (mesh, submesh, or group)
4289 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4290 # @param Copy allows copying the translated elements
4291 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4292 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4293 # @ingroup l2_modif_trsf
4294 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4295 if ( isinstance( theObject, Mesh )):
4296 theObject = theObject.GetMesh()
4297 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4298 Vector = self.smeshpyD.GetDirStruct(Vector)
4299 if isinstance( Vector, list ):
4300 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4301 self.mesh.SetParameters(Vector.PS.parameters)
4302 if Copy and MakeGroups:
4303 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4304 self.editor.TranslateObject(theObject, Vector, Copy)
4307 ## Creates a new mesh from the translated object
4308 # @param theObject the object to translate (mesh, submesh, or group)
4309 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4310 # @param MakeGroups forces the generation of new groups from existing ones
4311 # @param NewMeshName the name of the newly created mesh
4312 # @return instance of Mesh class
4313 # @ingroup l2_modif_trsf
4314 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4315 if isinstance( theObject, Mesh ):
4316 theObject = theObject.GetMesh()
4317 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4318 Vector = self.smeshpyD.GetDirStruct(Vector)
4319 if isinstance( Vector, list ):
4320 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4321 self.mesh.SetParameters(Vector.PS.parameters)
4322 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4323 return Mesh( self.smeshpyD, self.geompyD, mesh )
4327 ## Scales the object
4328 # @param theObject - the object to translate (mesh, submesh, or group)
4329 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4330 # @param theScaleFact - list of 1-3 scale factors for axises
4331 # @param Copy - allows copying the translated elements
4332 # @param MakeGroups - forces the generation of new groups from existing
4334 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4335 # empty list otherwise
4336 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4337 unRegister = genObjUnRegister()
4338 if ( isinstance( theObject, Mesh )):
4339 theObject = theObject.GetMesh()
4340 if ( isinstance( theObject, list )):
4341 theObject = self.GetIDSource(theObject, SMESH.ALL)
4342 unRegister.set( theObject )
4343 if ( isinstance( thePoint, list )):
4344 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4345 if ( isinstance( theScaleFact, float )):
4346 theScaleFact = [theScaleFact]
4347 if ( isinstance( theScaleFact, int )):
4348 theScaleFact = [ float(theScaleFact)]
4350 self.mesh.SetParameters(thePoint.parameters)
4352 if Copy and MakeGroups:
4353 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4354 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4357 ## Creates a new mesh from the translated object
4358 # @param theObject - the object to translate (mesh, submesh, or group)
4359 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4360 # @param theScaleFact - list of 1-3 scale factors for axises
4361 # @param MakeGroups - forces the generation of new groups from existing ones
4362 # @param NewMeshName - the name of the newly created mesh
4363 # @return instance of Mesh class
4364 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4365 unRegister = genObjUnRegister()
4366 if (isinstance(theObject, Mesh)):
4367 theObject = theObject.GetMesh()
4368 if ( isinstance( theObject, list )):
4369 theObject = self.GetIDSource(theObject,SMESH.ALL)
4370 unRegister.set( theObject )
4371 if ( isinstance( thePoint, list )):
4372 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4373 if ( isinstance( theScaleFact, float )):
4374 theScaleFact = [theScaleFact]
4375 if ( isinstance( theScaleFact, int )):
4376 theScaleFact = [ float(theScaleFact)]
4378 self.mesh.SetParameters(thePoint.parameters)
4379 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4380 MakeGroups, NewMeshName)
4381 return Mesh( self.smeshpyD, self.geompyD, mesh )
4385 ## Rotates the elements
4386 # @param IDsOfElements list of elements ids
4387 # @param Axis the axis of rotation (AxisStruct or geom line)
4388 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4389 # @param Copy allows copying the rotated elements
4390 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4391 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4392 # @ingroup l2_modif_trsf
4393 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4394 if IDsOfElements == []:
4395 IDsOfElements = self.GetElementsId()
4396 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4397 Axis = self.smeshpyD.GetAxisStruct(Axis)
4398 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4399 Parameters = Axis.parameters + var_separator + Parameters
4400 self.mesh.SetParameters(Parameters)
4401 if Copy and MakeGroups:
4402 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4403 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4406 ## Creates a new mesh of rotated elements
4407 # @param IDsOfElements list of element ids
4408 # @param Axis the axis of rotation (AxisStruct or geom line)
4409 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4410 # @param MakeGroups forces the generation of new groups from existing ones
4411 # @param NewMeshName the name of the newly created mesh
4412 # @return instance of Mesh class
4413 # @ingroup l2_modif_trsf
4414 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4415 if IDsOfElements == []:
4416 IDsOfElements = self.GetElementsId()
4417 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4418 Axis = self.smeshpyD.GetAxisStruct(Axis)
4419 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4420 Parameters = Axis.parameters + var_separator + Parameters
4421 self.mesh.SetParameters(Parameters)
4422 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4423 MakeGroups, NewMeshName)
4424 return Mesh( self.smeshpyD, self.geompyD, mesh )
4426 ## Rotates the object
4427 # @param theObject the object to rotate( mesh, submesh, or group)
4428 # @param Axis the axis of rotation (AxisStruct or geom line)
4429 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4430 # @param Copy allows copying the rotated elements
4431 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4432 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4433 # @ingroup l2_modif_trsf
4434 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4435 if (isinstance(theObject, Mesh)):
4436 theObject = theObject.GetMesh()
4437 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4438 Axis = self.smeshpyD.GetAxisStruct(Axis)
4439 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4440 Parameters = Axis.parameters + ":" + Parameters
4441 self.mesh.SetParameters(Parameters)
4442 if Copy and MakeGroups:
4443 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4444 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4447 ## Creates a new mesh from the rotated object
4448 # @param theObject the object to rotate (mesh, submesh, or group)
4449 # @param Axis the axis of rotation (AxisStruct or geom line)
4450 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4451 # @param MakeGroups forces the generation of new groups from existing ones
4452 # @param NewMeshName the name of the newly created mesh
4453 # @return instance of Mesh class
4454 # @ingroup l2_modif_trsf
4455 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4456 if (isinstance( theObject, Mesh )):
4457 theObject = theObject.GetMesh()
4458 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4459 Axis = self.smeshpyD.GetAxisStruct(Axis)
4460 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4461 Parameters = Axis.parameters + ":" + Parameters
4462 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4463 MakeGroups, NewMeshName)
4464 self.mesh.SetParameters(Parameters)
4465 return Mesh( self.smeshpyD, self.geompyD, mesh )
4467 ## Finds groups of adjacent nodes within Tolerance.
4468 # @param Tolerance the value of tolerance
4469 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4470 # corner and medium nodes in separate groups thus preventing
4471 # their further merge.
4472 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4473 # @ingroup l2_modif_trsf
4474 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4475 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4477 ## Finds groups of ajacent nodes within Tolerance.
4478 # @param Tolerance the value of tolerance
4479 # @param SubMeshOrGroup SubMesh or Group
4480 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4481 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4482 # corner and medium nodes in separate groups thus preventing
4483 # their further merge.
4484 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4485 # @ingroup l2_modif_trsf
4486 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4487 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4488 unRegister = genObjUnRegister()
4489 if (isinstance( SubMeshOrGroup, Mesh )):
4490 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4491 if not isinstance( exceptNodes, list ):
4492 exceptNodes = [ exceptNodes ]
4493 if exceptNodes and isinstance( exceptNodes[0], int ):
4494 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4495 unRegister.set( exceptNodes )
4496 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4497 exceptNodes, SeparateCornerAndMediumNodes)
4500 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4501 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4502 # by nodes 1 and 25 correspondingly in all elements and groups
4503 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4504 # If @a NodesToKeep does not include a node to keep for some group to merge,
4505 # then the first node in the group is kept.
4506 # @ingroup l2_modif_trsf
4507 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4508 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4509 self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4511 ## Finds the elements built on the same nodes.
4512 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4513 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4514 # @ingroup l2_modif_trsf
4515 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4516 if not MeshOrSubMeshOrGroup:
4517 MeshOrSubMeshOrGroup=self.mesh
4518 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4519 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4520 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4522 ## Merges elements in each given group.
4523 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4524 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4525 # replaced by elements 1 and 25 in all groups)
4526 # @ingroup l2_modif_trsf
4527 def MergeElements(self, GroupsOfElementsID):
4528 self.editor.MergeElements(GroupsOfElementsID)
4530 ## Leaves one element and removes all other elements built on the same nodes.
4531 # @ingroup l2_modif_trsf
4532 def MergeEqualElements(self):
4533 self.editor.MergeEqualElements()
4535 ## Returns groups of FreeBorder's coincident within the given tolerance.
4536 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4537 # size of elements adjacent to free borders being compared is used.
4538 # @return SMESH.CoincidentFreeBorders structure
4539 # @ingroup l2_modif_trsf
4540 def FindCoincidentFreeBorders (self, tolerance=0.):
4541 return self.editor.FindCoincidentFreeBorders( tolerance )
4543 ## Sew FreeBorder's of each group
4544 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4545 # where each enclosed list contains node IDs of a group of coincident free
4546 # borders such that each consequent triple of IDs within a group describes
4547 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4548 # last node of a border.
4549 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4550 # groups of coincident free borders, each group including two borders.
4551 # @param createPolygons if @c True faces adjacent to free borders are converted to
4552 # polygons if a node of opposite border falls on a face edge, else such
4553 # faces are split into several ones.
4554 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4555 # polyhedra if a node of opposite border falls on a volume edge, else such
4556 # volumes, if any, remain intact and the mesh becomes non-conformal.
4557 # @return a number of successfully sewed groups
4558 # @ingroup l2_modif_trsf
4559 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4560 if freeBorders and isinstance( freeBorders, list ):
4561 # construct SMESH.CoincidentFreeBorders
4562 if isinstance( freeBorders[0], int ):
4563 freeBorders = [freeBorders]
4565 coincidentGroups = []
4566 for nodeList in freeBorders:
4567 if not nodeList or len( nodeList ) % 3:
4568 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4571 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4572 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4573 nodeList = nodeList[3:]
4575 coincidentGroups.append( group )
4577 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4579 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4581 ## Sews free borders
4582 # @return SMESH::Sew_Error
4583 # @ingroup l2_modif_trsf
4584 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4585 FirstNodeID2, SecondNodeID2, LastNodeID2,
4586 CreatePolygons, CreatePolyedrs):
4587 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4588 FirstNodeID2, SecondNodeID2, LastNodeID2,
4589 CreatePolygons, CreatePolyedrs)
4591 ## Sews conform free borders
4592 # @return SMESH::Sew_Error
4593 # @ingroup l2_modif_trsf
4594 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4595 FirstNodeID2, SecondNodeID2):
4596 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4597 FirstNodeID2, SecondNodeID2)
4599 ## Sews border to side
4600 # @return SMESH::Sew_Error
4601 # @ingroup l2_modif_trsf
4602 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4603 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4604 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4605 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4607 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4608 # merged with the nodes of elements of Side2.
4609 # The number of elements in theSide1 and in theSide2 must be
4610 # equal and they should have similar nodal connectivity.
4611 # The nodes to merge should belong to side borders and
4612 # the first node should be linked to the second.
4613 # @return SMESH::Sew_Error
4614 # @ingroup l2_modif_trsf
4615 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4616 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4617 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4618 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4619 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4620 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4622 ## Sets new nodes for the given element.
4623 # @param ide the element id
4624 # @param newIDs nodes ids
4625 # @return If the number of nodes does not correspond to the type of element - returns false
4626 # @ingroup l2_modif_edit
4627 def ChangeElemNodes(self, ide, newIDs):
4628 return self.editor.ChangeElemNodes(ide, newIDs)
4630 ## If during the last operation of MeshEditor some nodes were
4631 # created, this method returns the list of their IDs, \n
4632 # if new nodes were not created - returns empty list
4633 # @return the list of integer values (can be empty)
4634 # @ingroup l1_auxiliary
4635 def GetLastCreatedNodes(self):
4636 return self.editor.GetLastCreatedNodes()
4638 ## If during the last operation of MeshEditor some elements were
4639 # created this method returns the list of their IDs, \n
4640 # if new elements were not created - returns empty list
4641 # @return the list of integer values (can be empty)
4642 # @ingroup l1_auxiliary
4643 def GetLastCreatedElems(self):
4644 return self.editor.GetLastCreatedElems()
4646 ## Clears sequences of nodes and elements created by mesh edition oparations
4647 # @ingroup l1_auxiliary
4648 def ClearLastCreated(self):
4649 self.editor.ClearLastCreated()
4651 ## Creates duplicates of given elements, i.e. creates new elements based on the
4652 # same nodes as the given ones.
4653 # @param theElements - container of elements to duplicate. It can be a Mesh,
4654 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4655 # a Mesh, elements of highest dimension are duplicated
4656 # @param theGroupName - a name of group to contain the generated elements.
4657 # If a group with such a name already exists, the new elements
4658 # are added to the existng group, else a new group is created.
4659 # If \a theGroupName is empty, new elements are not added
4661 # @return a group where the new elements are added. None if theGroupName == "".
4662 # @ingroup l2_modif_edit
4663 def DoubleElements(self, theElements, theGroupName=""):
4664 unRegister = genObjUnRegister()
4665 if isinstance( theElements, Mesh ):
4666 theElements = theElements.mesh
4667 elif isinstance( theElements, list ):
4668 theElements = self.GetIDSource( theElements, SMESH.ALL )
4669 unRegister.set( theElements )
4670 return self.editor.DoubleElements(theElements, theGroupName)
4672 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4673 # @param theNodes identifiers of nodes to be doubled
4674 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4675 # nodes. If list of element identifiers is empty then nodes are doubled but
4676 # they not assigned to elements
4677 # @return TRUE if operation has been completed successfully, FALSE otherwise
4678 # @ingroup l2_modif_edit
4679 def DoubleNodes(self, theNodes, theModifiedElems):
4680 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4682 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4683 # This method provided for convenience works as DoubleNodes() described above.
4684 # @param theNodeId identifiers of node to be doubled
4685 # @param theModifiedElems identifiers of elements to be updated
4686 # @return TRUE if operation has been completed successfully, FALSE otherwise
4687 # @ingroup l2_modif_edit
4688 def DoubleNode(self, theNodeId, theModifiedElems):
4689 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4691 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4692 # This method provided for convenience works as DoubleNodes() described above.
4693 # @param theNodes group of nodes to be doubled
4694 # @param theModifiedElems group of elements to be updated.
4695 # @param theMakeGroup forces the generation of a group containing new nodes.
4696 # @return TRUE or a created group if operation has been completed successfully,
4697 # FALSE or None otherwise
4698 # @ingroup l2_modif_edit
4699 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4701 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4702 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4704 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4705 # This method provided for convenience works as DoubleNodes() described above.
4706 # @param theNodes list of groups of nodes to be doubled
4707 # @param theModifiedElems list of groups of elements to be updated.
4708 # @param theMakeGroup forces the generation of a group containing new nodes.
4709 # @return TRUE if operation has been completed successfully, FALSE otherwise
4710 # @ingroup l2_modif_edit
4711 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4713 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4714 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4716 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4717 # @param theElems - the list of elements (edges or faces) to be replicated
4718 # The nodes for duplication could be found from these elements
4719 # @param theNodesNot - list of nodes to NOT replicate
4720 # @param theAffectedElems - the list of elements (cells and edges) to which the
4721 # replicated nodes should be associated to.
4722 # @return TRUE if operation has been completed successfully, FALSE otherwise
4723 # @ingroup l2_modif_edit
4724 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4725 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4727 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4728 # @param theElems - the list of elements (edges or faces) to be replicated
4729 # The nodes for duplication could be found from these elements
4730 # @param theNodesNot - list of nodes to NOT replicate
4731 # @param theShape - shape to detect affected elements (element which geometric center
4732 # located on or inside shape).
4733 # The replicated nodes should be associated to affected elements.
4734 # @return TRUE if operation has been completed successfully, FALSE otherwise
4735 # @ingroup l2_modif_edit
4736 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4737 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4739 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4740 # This method provided for convenience works as DoubleNodes() described above.
4741 # @param theElems - group of of elements (edges or faces) to be replicated
4742 # @param theNodesNot - group of nodes not to replicated
4743 # @param theAffectedElems - group of elements to which the replicated nodes
4744 # should be associated to.
4745 # @param theMakeGroup forces the generation of a group containing new elements.
4746 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4747 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4748 # FALSE or None otherwise
4749 # @ingroup l2_modif_edit
4750 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4751 theMakeGroup=False, theMakeNodeGroup=False):
4752 if theMakeGroup or theMakeNodeGroup:
4753 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4755 theMakeGroup, theMakeNodeGroup)
4756 if theMakeGroup and theMakeNodeGroup:
4759 return twoGroups[ int(theMakeNodeGroup) ]
4760 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4762 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4763 # This method provided for convenience works as DoubleNodes() described above.
4764 # @param theElems - group of of elements (edges or faces) to be replicated
4765 # @param theNodesNot - group of nodes not to replicated
4766 # @param theShape - shape to detect affected elements (element which geometric center
4767 # located on or inside shape).
4768 # The replicated nodes should be associated to affected elements.
4769 # @ingroup l2_modif_edit
4770 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4771 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4773 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4774 # This method provided for convenience works as DoubleNodes() described above.
4775 # @param theElems - list of groups of elements (edges or faces) to be replicated
4776 # @param theNodesNot - list of groups of nodes not to replicated
4777 # @param theAffectedElems - group of elements to which the replicated nodes
4778 # should be associated to.
4779 # @param theMakeGroup forces the generation of a group containing new elements.
4780 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4781 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4782 # FALSE or None otherwise
4783 # @ingroup l2_modif_edit
4784 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4785 theMakeGroup=False, theMakeNodeGroup=False):
4786 if theMakeGroup or theMakeNodeGroup:
4787 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4789 theMakeGroup, theMakeNodeGroup)
4790 if theMakeGroup and theMakeNodeGroup:
4793 return twoGroups[ int(theMakeNodeGroup) ]
4794 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4796 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4797 # This method provided for convenience works as DoubleNodes() described above.
4798 # @param theElems - list of groups of elements (edges or faces) to be replicated
4799 # @param theNodesNot - list of groups of nodes not to replicated
4800 # @param theShape - shape to detect affected elements (element which geometric center
4801 # located on or inside shape).
4802 # The replicated nodes should be associated to affected elements.
4803 # @return TRUE if operation has been completed successfully, FALSE otherwise
4804 # @ingroup l2_modif_edit
4805 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4806 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4808 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4809 # This method is the first step of DoubleNodeElemGroupsInRegion.
4810 # @param theElems - list of groups of elements (edges or faces) to be replicated
4811 # @param theNodesNot - list of groups of nodes not to replicated
4812 # @param theShape - shape to detect affected elements (element which geometric center
4813 # located on or inside shape).
4814 # The replicated nodes should be associated to affected elements.
4815 # @return groups of affected elements
4816 # @ingroup l2_modif_edit
4817 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4818 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4820 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4821 # The list of groups must describe a partition of the mesh volumes.
4822 # The nodes of the internal faces at the boundaries of the groups are doubled.
4823 # In option, the internal faces are replaced by flat elements.
4824 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4825 # @param theDomains - list of groups of volumes
4826 # @param createJointElems - if TRUE, create the elements
4827 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4828 # the boundary between \a theDomains and the rest mesh
4829 # @return TRUE if operation has been completed successfully, FALSE otherwise
4830 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4831 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4833 ## Double nodes on some external faces and create flat elements.
4834 # Flat elements are mainly used by some types of mechanic calculations.
4836 # Each group of the list must be constituted of faces.
4837 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4838 # @param theGroupsOfFaces - list of groups of faces
4839 # @return TRUE if operation has been completed successfully, FALSE otherwise
4840 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4841 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4843 ## identify all the elements around a geom shape, get the faces delimiting the hole
4845 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4846 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4848 def _getFunctor(self, funcType ):
4849 fn = self.functors[ funcType._v ]
4851 fn = self.smeshpyD.GetFunctor(funcType)
4852 fn.SetMesh(self.mesh)
4853 self.functors[ funcType._v ] = fn
4856 ## Returns value of a functor for a given element
4857 # @param funcType an item of SMESH.FunctorType enum
4858 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4859 # @param elemId element or node ID
4860 # @param isElem @a elemId is ID of element or node
4861 # @return the functor value or zero in case of invalid arguments
4862 def FunctorValue(self, funcType, elemId, isElem=True):
4863 fn = self._getFunctor( funcType )
4864 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4865 val = fn.GetValue(elemId)
4870 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4871 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4872 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4873 # @ingroup l1_measurements
4874 def GetLength(self, elemId=None):
4877 length = self.smeshpyD.GetLength(self)
4879 length = self.FunctorValue(SMESH.FT_Length, elemId)
4882 ## Get area of 2D element or sum of areas of all 2D mesh elements
4883 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4884 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4885 # @ingroup l1_measurements
4886 def GetArea(self, elemId=None):
4889 area = self.smeshpyD.GetArea(self)
4891 area = self.FunctorValue(SMESH.FT_Area, elemId)
4894 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4895 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4896 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4897 # @ingroup l1_measurements
4898 def GetVolume(self, elemId=None):
4901 volume = self.smeshpyD.GetVolume(self)
4903 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4906 ## Get maximum element length.
4907 # @param elemId mesh element ID
4908 # @return element's maximum length value
4909 # @ingroup l1_measurements
4910 def GetMaxElementLength(self, elemId):
4911 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4912 ftype = SMESH.FT_MaxElementLength3D
4914 ftype = SMESH.FT_MaxElementLength2D
4915 return self.FunctorValue(ftype, elemId)
4917 ## Get aspect ratio of 2D or 3D element.
4918 # @param elemId mesh element ID
4919 # @return element's aspect ratio value
4920 # @ingroup l1_measurements
4921 def GetAspectRatio(self, elemId):
4922 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4923 ftype = SMESH.FT_AspectRatio3D
4925 ftype = SMESH.FT_AspectRatio
4926 return self.FunctorValue(ftype, elemId)
4928 ## Get warping angle of 2D element.
4929 # @param elemId mesh element ID
4930 # @return element's warping angle value
4931 # @ingroup l1_measurements
4932 def GetWarping(self, elemId):
4933 return self.FunctorValue(SMESH.FT_Warping, elemId)
4935 ## Get minimum angle of 2D element.
4936 # @param elemId mesh element ID
4937 # @return element's minimum angle value
4938 # @ingroup l1_measurements
4939 def GetMinimumAngle(self, elemId):
4940 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4942 ## Get taper of 2D element.
4943 # @param elemId mesh element ID
4944 # @return element's taper value
4945 # @ingroup l1_measurements
4946 def GetTaper(self, elemId):
4947 return self.FunctorValue(SMESH.FT_Taper, elemId)
4949 ## Get skew of 2D element.
4950 # @param elemId mesh element ID
4951 # @return element's skew value
4952 # @ingroup l1_measurements
4953 def GetSkew(self, elemId):
4954 return self.FunctorValue(SMESH.FT_Skew, elemId)
4956 ## Return minimal and maximal value of a given functor.
4957 # @param funType a functor type, an item of SMESH.FunctorType enum
4958 # (one of SMESH.FunctorType._items)
4959 # @param meshPart a part of mesh (group, sub-mesh) to treat
4960 # @return tuple (min,max)
4961 # @ingroup l1_measurements
4962 def GetMinMax(self, funType, meshPart=None):
4963 unRegister = genObjUnRegister()
4964 if isinstance( meshPart, list ):
4965 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4966 unRegister.set( meshPart )
4967 if isinstance( meshPart, Mesh ):
4968 meshPart = meshPart.mesh
4969 fun = self._getFunctor( funType )
4972 if hasattr( meshPart, "SetMesh" ):
4973 meshPart.SetMesh( self.mesh ) # set mesh to filter
4974 hist = fun.GetLocalHistogram( 1, False, meshPart )
4976 hist = fun.GetHistogram( 1, False )
4978 return hist[0].min, hist[0].max
4981 pass # end of Mesh class
4984 ## class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
4985 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
4987 class meshProxy(SMESH._objref_SMESH_Mesh):
4989 SMESH._objref_SMESH_Mesh.__init__(self)
4990 def __deepcopy__(self, memo=None):
4991 new = self.__class__()
4993 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
4994 if len( args ) == 3:
4995 args += SMESH.ALL_NODES, True
4996 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
4998 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5000 ## class used to compensate change of CORBA API of SMESH_MeshEditor for backward compatibility
5001 # with old dump scripts which call SMESH_MeshEditor directly and not via smeshBuilder.Mesh
5003 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5005 SMESH._objref_SMESH_MeshEditor.__init__(self)
5007 def __getattr__(self, name ): # method called if an attribute not found
5008 if not self.mesh: # look for name() method in Mesh class
5009 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5010 if hasattr( self.mesh, name ):
5011 return getattr( self.mesh, name )
5012 if name == "ExtrusionAlongPathObjX":
5013 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5014 print "meshEditor: attribute '%s' NOT FOUND" % name
5016 def __deepcopy__(self, memo=None):
5017 new = self.__class__()
5019 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5020 if len( args ) == 1: args += False,
5021 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5022 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5023 if len( args ) == 2: args += False,
5024 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5025 def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
5026 if len( args ) == 1:
5027 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
5028 NodesToKeep = args[1]
5029 unRegister = genObjUnRegister()
5031 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5032 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5033 if not isinstance( NodesToKeep, list ):
5034 NodesToKeep = [ NodesToKeep ]
5035 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
5037 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5039 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
5041 class Pattern(SMESH._objref_SMESH_Pattern):
5043 def LoadFromFile(self, patternTextOrFile ):
5044 text = patternTextOrFile
5045 if os.path.exists( text ):
5046 text = open( patternTextOrFile ).read()
5048 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5050 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5051 decrFun = lambda i: i-1
5052 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5053 theMesh.SetParameters(Parameters)
5054 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5056 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5057 decrFun = lambda i: i-1
5058 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5059 theMesh.SetParameters(Parameters)
5060 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5062 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5063 if isinstance( mesh, Mesh ):
5064 mesh = mesh.GetMesh()
5065 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5067 # Registering the new proxy for Pattern
5068 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5070 ## Private class used to bind methods creating algorithms to the class Mesh
5075 self.defaultAlgoType = ""
5076 self.algoTypeToClass = {}
5078 # Stores a python class of algorithm
5079 def add(self, algoClass):
5080 if type( algoClass ).__name__ == 'classobj' and \
5081 hasattr( algoClass, "algoType"):
5082 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5083 if not self.defaultAlgoType and \
5084 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5085 self.defaultAlgoType = algoClass.algoType
5086 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5088 # creates a copy of self and assign mesh to the copy
5089 def copy(self, mesh):
5090 other = algoCreator()
5091 other.defaultAlgoType = self.defaultAlgoType
5092 other.algoTypeToClass = self.algoTypeToClass
5096 # creates an instance of algorithm
5097 def __call__(self,algo="",geom=0,*args):
5098 algoType = self.defaultAlgoType
5099 for arg in args + (algo,geom):
5100 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5102 if isinstance( arg, str ) and arg:
5104 if not algoType and self.algoTypeToClass:
5105 algoType = self.algoTypeToClass.keys()[0]
5106 if self.algoTypeToClass.has_key( algoType ):
5107 #print "Create algo",algoType
5108 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5109 raise RuntimeError, "No class found for algo type %s" % algoType
5112 # Private class used to substitute and store variable parameters of hypotheses.
5114 class hypMethodWrapper:
5115 def __init__(self, hyp, method):
5117 self.method = method
5118 #print "REBIND:", method.__name__
5121 # call a method of hypothesis with calling SetVarParameter() before
5122 def __call__(self,*args):
5124 return self.method( self.hyp, *args ) # hypothesis method with no args
5126 #print "MethWrapper.__call__",self.method.__name__, args
5128 parsed = ParseParameters(*args) # replace variables with their values
5129 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5130 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5131 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5132 # maybe there is a replaced string arg which is not variable
5133 result = self.method( self.hyp, *args )
5134 except ValueError, detail: # raised by ParseParameters()
5136 result = self.method( self.hyp, *args )
5137 except omniORB.CORBA.BAD_PARAM:
5138 raise ValueError, detail # wrong variable name
5143 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
5144 class genObjUnRegister:
5146 def __init__(self, genObj=None):
5147 self.genObjList = []
5151 def set(self, genObj):
5152 "Store one or a list of of SALOME.GenericObj'es"
5153 if isinstance( genObj, list ):
5154 self.genObjList.extend( genObj )
5156 self.genObjList.append( genObj )
5160 for genObj in self.genObjList:
5161 if genObj and hasattr( genObj, "UnRegister" ):
5164 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5166 #print "pluginName: ", pluginName
5167 pluginBuilderName = pluginName + "Builder"
5169 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5170 except Exception, e:
5171 from salome_utils import verbose
5172 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5174 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5175 plugin = eval( pluginBuilderName )
5176 #print " plugin:" , str(plugin)
5178 # add methods creating algorithms to Mesh
5179 for k in dir( plugin ):
5180 if k[0] == '_': continue
5181 algo = getattr( plugin, k )
5182 #print " algo:", str(algo)
5183 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5184 #print " meshMethod:" , str(algo.meshMethod)
5185 if not hasattr( Mesh, algo.meshMethod ):
5186 setattr( Mesh, algo.meshMethod, algoCreator() )
5188 getattr( Mesh, algo.meshMethod ).add( algo )