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 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1501 smeshgui = salome.ImportComponentGUI("SMESH")
1502 smeshgui.Init(self.mesh.GetStudyId())
1503 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1504 if refresh: salome.sg.updateObjBrowser(1)
1508 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1509 def GetComputeErrors(self, shape=0 ):
1511 shape = self.mesh.GetShapeToMesh()
1512 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1514 ## Return a name of a sub-shape by its ID
1515 # @param subShapeID a unique ID of a sub-shape
1516 # @return a string describing the sub-shape; possible variants:
1517 # - "Face_12" (published sub-shape)
1518 # - FACE #3 (not published sub-shape)
1519 # - sub-shape #3 (invalid sub-shape ID)
1520 # - #3 (error in this function)
1521 def GetSubShapeName(self, subShapeID ):
1522 if not self.mesh.HasShapeToMesh():
1526 mainIOR = salome.orb.object_to_string( self.GetShape() )
1527 for sname in salome.myStudyManager.GetOpenStudies():
1528 s = salome.myStudyManager.GetStudyByName(sname)
1530 mainSO = s.FindObjectIOR(mainIOR)
1531 if not mainSO: continue
1533 shapeText = '"%s"' % mainSO.GetName()
1534 subIt = s.NewChildIterator(mainSO)
1536 subSO = subIt.Value()
1538 obj = subSO.GetObject()
1539 if not obj: continue
1540 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1543 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1546 if ids == subShapeID:
1547 shapeText = '"%s"' % subSO.GetName()
1550 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1552 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1554 shapeText = 'sub-shape #%s' % (subShapeID)
1556 shapeText = "#%s" % (subShapeID)
1559 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1560 # error of an algorithm
1561 # @param publish if @c True, the returned groups will be published in the study
1562 # @return a list of GEOM groups each named after a failed algorithm
1563 def GetFailedShapes(self, publish=False):
1566 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1567 for err in computeErrors:
1568 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1569 if not shape: continue
1570 if err.algoName in algo2shapes:
1571 algo2shapes[ err.algoName ].append( shape )
1573 algo2shapes[ err.algoName ] = [ shape ]
1577 for algoName, shapes in algo2shapes.items():
1579 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1580 otherTypeShapes = []
1582 group = self.geompyD.CreateGroup( self.geom, groupType )
1583 for shape in shapes:
1584 if shape.GetShapeType() == shapes[0].GetShapeType():
1585 sameTypeShapes.append( shape )
1587 otherTypeShapes.append( shape )
1588 self.geompyD.UnionList( group, sameTypeShapes )
1590 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1592 group.SetName( algoName )
1593 groups.append( group )
1594 shapes = otherTypeShapes
1597 for group in groups:
1598 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1601 ## Return sub-mesh objects list in meshing order
1602 # @return list of lists of sub-meshes
1603 # @ingroup l2_construct
1604 def GetMeshOrder(self):
1605 return self.mesh.GetMeshOrder()
1607 ## Set order in which concurrent sub-meshes sould be meshed
1608 # @param submeshes list of lists of sub-meshes
1609 # @ingroup l2_construct
1610 def SetMeshOrder(self, submeshes):
1611 return self.mesh.SetMeshOrder(submeshes)
1613 ## Removes all nodes and elements
1614 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1615 # @ingroup l2_construct
1616 def Clear(self, refresh=False):
1618 if ( salome.sg.hasDesktop() and
1619 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1620 smeshgui = salome.ImportComponentGUI("SMESH")
1621 smeshgui.Init(self.mesh.GetStudyId())
1622 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1623 if refresh: salome.sg.updateObjBrowser(1)
1625 ## Removes all nodes and elements of indicated shape
1626 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1627 # @param geomId the ID of a sub-shape to remove elements on
1628 # @ingroup l2_construct
1629 def ClearSubMesh(self, geomId, refresh=False):
1630 self.mesh.ClearSubMesh(geomId)
1631 if salome.sg.hasDesktop():
1632 smeshgui = salome.ImportComponentGUI("SMESH")
1633 smeshgui.Init(self.mesh.GetStudyId())
1634 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1635 if refresh: salome.sg.updateObjBrowser(1)
1637 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1638 # @param fineness [0.0,1.0] defines mesh fineness
1639 # @return True or False
1640 # @ingroup l3_algos_basic
1641 def AutomaticTetrahedralization(self, fineness=0):
1642 dim = self.MeshDimension()
1644 self.RemoveGlobalHypotheses()
1645 self.Segment().AutomaticLength(fineness)
1647 self.Triangle().LengthFromEdges()
1652 return self.Compute()
1654 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1655 # @param fineness [0.0, 1.0] defines mesh fineness
1656 # @return True or False
1657 # @ingroup l3_algos_basic
1658 def AutomaticHexahedralization(self, fineness=0):
1659 dim = self.MeshDimension()
1660 # assign the hypotheses
1661 self.RemoveGlobalHypotheses()
1662 self.Segment().AutomaticLength(fineness)
1669 return self.Compute()
1671 ## Assigns a hypothesis
1672 # @param hyp a hypothesis to assign
1673 # @param geom a subhape of mesh geometry
1674 # @return SMESH.Hypothesis_Status
1675 # @ingroup l2_hypotheses
1676 def AddHypothesis(self, hyp, geom=0):
1677 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1678 hyp, geom = geom, hyp
1679 if isinstance( hyp, Mesh_Algorithm ):
1680 hyp = hyp.GetAlgorithm()
1685 geom = self.mesh.GetShapeToMesh()
1688 if self.mesh.HasShapeToMesh():
1689 hyp_type = hyp.GetName()
1690 lib_name = hyp.GetLibName()
1691 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1692 # if checkAll and geom:
1693 # checkAll = geom.GetType() == 37
1695 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1697 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1698 status = self.mesh.AddHypothesis(geom, hyp)
1700 status = HYP_BAD_GEOMETRY,""
1701 hyp_name = GetName( hyp )
1704 geom_name = geom.GetName()
1705 isAlgo = hyp._narrow( SMESH_Algo )
1706 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1709 ## Return True if an algorithm of hypothesis is assigned to a given shape
1710 # @param hyp a hypothesis to check
1711 # @param geom a subhape of mesh geometry
1712 # @return True of False
1713 # @ingroup l2_hypotheses
1714 def IsUsedHypothesis(self, hyp, geom):
1715 if not hyp: # or not geom
1717 if isinstance( hyp, Mesh_Algorithm ):
1718 hyp = hyp.GetAlgorithm()
1720 hyps = self.GetHypothesisList(geom)
1722 if h.GetId() == hyp.GetId():
1726 ## Unassigns a hypothesis
1727 # @param hyp a hypothesis to unassign
1728 # @param geom a sub-shape of mesh geometry
1729 # @return SMESH.Hypothesis_Status
1730 # @ingroup l2_hypotheses
1731 def RemoveHypothesis(self, hyp, geom=0):
1734 if isinstance( hyp, Mesh_Algorithm ):
1735 hyp = hyp.GetAlgorithm()
1741 if self.IsUsedHypothesis( hyp, shape ):
1742 return self.mesh.RemoveHypothesis( shape, hyp )
1743 hypName = GetName( hyp )
1744 geoName = GetName( shape )
1745 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1748 ## Gets the list of hypotheses added on a geometry
1749 # @param geom a sub-shape of mesh geometry
1750 # @return the sequence of SMESH_Hypothesis
1751 # @ingroup l2_hypotheses
1752 def GetHypothesisList(self, geom):
1753 return self.mesh.GetHypothesisList( geom )
1755 ## Removes all global hypotheses
1756 # @ingroup l2_hypotheses
1757 def RemoveGlobalHypotheses(self):
1758 current_hyps = self.mesh.GetHypothesisList( self.geom )
1759 for hyp in current_hyps:
1760 self.mesh.RemoveHypothesis( self.geom, hyp )
1764 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1765 ## allowing to overwrite the file if it exists or add the exported data to its contents
1766 # @param f is the file name
1767 # @param auto_groups boolean parameter for creating/not creating
1768 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1769 # the typical use is auto_groups=false.
1770 # @param version MED format version(MED_V2_1 or MED_V2_2)
1771 # @param overwrite boolean parameter for overwriting/not overwriting the file
1772 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1773 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1774 # - 1D if all mesh nodes lie on OX coordinate axis, or
1775 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1776 # - 3D in the rest cases.
1777 # If @a autoDimension is @c False, the space dimension is always 3.
1778 # @param fields : list of GEOM fields defined on the shape to mesh.
1779 # @param geomAssocFields : each character of this string means a need to export a
1780 # corresponding field; correspondence between fields and characters is following:
1781 # - 'v' stands for _vertices_ field;
1782 # - 'e' stands for _edges_ field;
1783 # - 'f' stands for _faces_ field;
1784 # - 's' stands for _solids_ field.
1785 # @ingroup l2_impexp
1786 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1787 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1788 if meshPart or fields or geomAssocFields:
1789 unRegister = genObjUnRegister()
1790 if isinstance( meshPart, list ):
1791 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1792 unRegister.set( meshPart )
1793 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1794 fields, geomAssocFields)
1796 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1798 ## Exports the mesh in a file in SAUV format
1799 # @param f is the file name
1800 # @param auto_groups boolean parameter for creating/not creating
1801 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1802 # the typical use is auto_groups=false.
1803 # @ingroup l2_impexp
1804 def ExportSAUV(self, f, auto_groups=0):
1805 self.mesh.ExportSAUV(f, auto_groups)
1807 ## Exports the mesh in a file in DAT format
1808 # @param f the file name
1809 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1810 # @ingroup l2_impexp
1811 def ExportDAT(self, f, meshPart=None):
1813 unRegister = genObjUnRegister()
1814 if isinstance( meshPart, list ):
1815 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1816 unRegister.set( meshPart )
1817 self.mesh.ExportPartToDAT( meshPart, f )
1819 self.mesh.ExportDAT(f)
1821 ## Exports the mesh in a file in UNV format
1822 # @param f the file name
1823 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1824 # @ingroup l2_impexp
1825 def ExportUNV(self, f, meshPart=None):
1827 unRegister = genObjUnRegister()
1828 if isinstance( meshPart, list ):
1829 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1830 unRegister.set( meshPart )
1831 self.mesh.ExportPartToUNV( meshPart, f )
1833 self.mesh.ExportUNV(f)
1835 ## Export the mesh in a file in STL format
1836 # @param f the file name
1837 # @param ascii defines the file encoding
1838 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1839 # @ingroup l2_impexp
1840 def ExportSTL(self, f, ascii=1, meshPart=None):
1842 unRegister = genObjUnRegister()
1843 if isinstance( meshPart, list ):
1844 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1845 unRegister.set( meshPart )
1846 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1848 self.mesh.ExportSTL(f, ascii)
1850 ## Exports the mesh in a file in CGNS format
1851 # @param f is the file name
1852 # @param overwrite boolean parameter for overwriting/not overwriting the file
1853 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1854 # @ingroup l2_impexp
1855 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1856 unRegister = genObjUnRegister()
1857 if isinstance( meshPart, list ):
1858 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1859 unRegister.set( meshPart )
1860 if isinstance( meshPart, Mesh ):
1861 meshPart = meshPart.mesh
1863 meshPart = self.mesh
1864 self.mesh.ExportCGNS(meshPart, f, overwrite)
1866 ## Exports the mesh in a file in GMF format.
1867 # GMF files must have .mesh extension for the ASCII format and .meshb for
1868 # the bynary format. Other extensions are not allowed.
1869 # @param f is the file name
1870 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1871 # @ingroup l2_impexp
1872 def ExportGMF(self, f, meshPart=None):
1873 unRegister = genObjUnRegister()
1874 if isinstance( meshPart, list ):
1875 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1876 unRegister.set( meshPart )
1877 if isinstance( meshPart, Mesh ):
1878 meshPart = meshPart.mesh
1880 meshPart = self.mesh
1881 self.mesh.ExportGMF(meshPart, f, True)
1883 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1884 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1885 ## allowing to overwrite the file if it exists or add the exported data to its contents
1886 # @param f the file name
1887 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1888 # @param opt boolean parameter for creating/not creating
1889 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1890 # @param overwrite boolean parameter for overwriting/not overwriting the file
1891 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1892 # - 1D if all mesh nodes lie on OX coordinate axis, or
1893 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1894 # - 3D in the rest cases.
1896 # If @a autoDimension is @c False, the space dimension is always 3.
1897 # @ingroup l2_impexp
1898 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1899 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1901 # Operations with groups:
1902 # ----------------------
1904 ## Creates an empty mesh group
1905 # @param elementType the type of elements in the group; either of
1906 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1907 # @param name the name of the mesh group
1908 # @return SMESH_Group
1909 # @ingroup l2_grps_create
1910 def CreateEmptyGroup(self, elementType, name):
1911 return self.mesh.CreateGroup(elementType, name)
1913 ## Creates a mesh group based on the geometric object \a grp
1914 # and gives a \a name, \n if this parameter is not defined
1915 # the name is the same as the geometric group name \n
1916 # Note: Works like GroupOnGeom().
1917 # @param grp a geometric group, a vertex, an edge, a face or a solid
1918 # @param name the name of the mesh group
1919 # @return SMESH_GroupOnGeom
1920 # @ingroup l2_grps_create
1921 def Group(self, grp, name=""):
1922 return self.GroupOnGeom(grp, name)
1924 ## Creates a mesh group based on the geometrical object \a grp
1925 # and gives a \a name, \n if this parameter is not defined
1926 # the name is the same as the geometrical group name
1927 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1928 # @param name the name of the mesh group
1929 # @param typ the type of elements in the group; either of
1930 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1931 # automatically detected by the type of the geometry
1932 # @return SMESH_GroupOnGeom
1933 # @ingroup l2_grps_create
1934 def GroupOnGeom(self, grp, name="", typ=None):
1935 AssureGeomPublished( self, grp, name )
1937 name = grp.GetName()
1939 typ = self._groupTypeFromShape( grp )
1940 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1942 ## Pivate method to get a type of group on geometry
1943 def _groupTypeFromShape( self, shape ):
1944 tgeo = str(shape.GetShapeType())
1945 if tgeo == "VERTEX":
1947 elif tgeo == "EDGE":
1949 elif tgeo == "FACE" or tgeo == "SHELL":
1951 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1953 elif tgeo == "COMPOUND":
1954 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1956 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1957 return self._groupTypeFromShape( sub[0] )
1960 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1963 ## Creates a mesh group with given \a name based on the \a filter which
1964 ## is a special type of group dynamically updating it's contents during
1965 ## mesh modification
1966 # @param typ the type of elements in the group; either of
1967 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1968 # @param name the name of the mesh group
1969 # @param filter the filter defining group contents
1970 # @return SMESH_GroupOnFilter
1971 # @ingroup l2_grps_create
1972 def GroupOnFilter(self, typ, name, filter):
1973 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1975 ## Creates a mesh group by the given ids of elements
1976 # @param groupName the name of the mesh group
1977 # @param elementType the type of elements in the group; either of
1978 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1979 # @param elemIDs either the list of ids, group, sub-mesh, or filter
1980 # @return SMESH_Group
1981 # @ingroup l2_grps_create
1982 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1983 group = self.mesh.CreateGroup(elementType, groupName)
1984 if hasattr( elemIDs, "GetIDs" ):
1985 if hasattr( elemIDs, "SetMesh" ):
1986 elemIDs.SetMesh( self.GetMesh() )
1987 group.AddFrom( elemIDs )
1992 ## Creates a mesh group by the given conditions
1993 # @param groupName the name of the mesh group
1994 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1995 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
1996 # Type SMESH.FunctorType._items in the Python Console to see all values.
1997 # Note that the items starting from FT_LessThan are not suitable for CritType.
1998 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1999 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2000 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2001 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2002 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2003 # @return SMESH_GroupOnFilter
2004 # @ingroup l2_grps_create
2008 CritType=FT_Undefined,
2011 UnaryOp=FT_Undefined,
2013 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2014 group = self.MakeGroupByCriterion(groupName, aCriterion)
2017 ## Creates a mesh group by the given criterion
2018 # @param groupName the name of the mesh group
2019 # @param Criterion the instance of Criterion class
2020 # @return SMESH_GroupOnFilter
2021 # @ingroup l2_grps_create
2022 def MakeGroupByCriterion(self, groupName, Criterion):
2023 return self.MakeGroupByCriteria( groupName, [Criterion] )
2025 ## Creates a mesh group by the given criteria (list of criteria)
2026 # @param groupName the name of the mesh group
2027 # @param theCriteria the list of criteria
2028 # @param binOp binary operator used when binary operator of criteria is undefined
2029 # @return SMESH_GroupOnFilter
2030 # @ingroup l2_grps_create
2031 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2032 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2033 group = self.MakeGroupByFilter(groupName, aFilter)
2036 ## Creates a mesh group by the given filter
2037 # @param groupName the name of the mesh group
2038 # @param theFilter the instance of Filter class
2039 # @return SMESH_GroupOnFilter
2040 # @ingroup l2_grps_create
2041 def MakeGroupByFilter(self, groupName, theFilter):
2042 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2043 #theFilter.SetMesh( self.mesh )
2044 #group.AddFrom( theFilter )
2045 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2049 # @ingroup l2_grps_delete
2050 def RemoveGroup(self, group):
2051 self.mesh.RemoveGroup(group)
2053 ## Removes a group with its contents
2054 # @ingroup l2_grps_delete
2055 def RemoveGroupWithContents(self, group):
2056 self.mesh.RemoveGroupWithContents(group)
2058 ## Gets the list of groups existing in the mesh in the order
2059 # of creation (starting from the oldest one)
2060 # @param elemType type of elements the groups contain; either of
2061 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2062 # by default groups of elements of all types are returned
2063 # @return a sequence of SMESH_GroupBase
2064 # @ingroup l2_grps_create
2065 def GetGroups(self, elemType = SMESH.ALL):
2066 groups = self.mesh.GetGroups()
2067 if elemType == SMESH.ALL:
2071 if g.GetType() == elemType:
2072 typedGroups.append( g )
2077 ## Gets the number of groups existing in the mesh
2078 # @return the quantity of groups as an integer value
2079 # @ingroup l2_grps_create
2081 return self.mesh.NbGroups()
2083 ## Gets the list of names of groups existing in the mesh
2084 # @return list of strings
2085 # @ingroup l2_grps_create
2086 def GetGroupNames(self):
2087 groups = self.GetGroups()
2089 for group in groups:
2090 names.append(group.GetName())
2093 ## Finds groups by name and type
2094 # @param name name of the group of interest
2095 # @param elemType type of elements the groups contain; either of
2096 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2097 # by default one group of any type of elements is returned
2098 # if elemType == SMESH.ALL then all groups of any type are returned
2099 # @return a list of SMESH_GroupBase's
2100 # @ingroup l2_grps_create
2101 def GetGroupByName(self, name, elemType = None):
2103 for group in self.GetGroups():
2104 if group.GetName() == name:
2105 if elemType is None:
2107 if ( elemType == SMESH.ALL or
2108 group.GetType() == elemType ):
2109 groups.append( group )
2112 ## Produces a union of two groups.
2113 # A new group is created. All mesh elements that are
2114 # present in the initial groups are added to the new one
2115 # @return an instance of SMESH_Group
2116 # @ingroup l2_grps_operon
2117 def UnionGroups(self, group1, group2, name):
2118 return self.mesh.UnionGroups(group1, group2, name)
2120 ## Produces a union list of groups.
2121 # New group is created. All mesh elements that are present in
2122 # initial groups are added to the new one
2123 # @return an instance of SMESH_Group
2124 # @ingroup l2_grps_operon
2125 def UnionListOfGroups(self, groups, name):
2126 return self.mesh.UnionListOfGroups(groups, name)
2128 ## Prodices an intersection of two groups.
2129 # A new group is created. All mesh elements that are common
2130 # for the two initial groups are added to the new one.
2131 # @return an instance of SMESH_Group
2132 # @ingroup l2_grps_operon
2133 def IntersectGroups(self, group1, group2, name):
2134 return self.mesh.IntersectGroups(group1, group2, name)
2136 ## Produces an intersection of groups.
2137 # New group is created. All mesh elements that are present in all
2138 # initial groups simultaneously are added to the new one
2139 # @return an instance of SMESH_Group
2140 # @ingroup l2_grps_operon
2141 def IntersectListOfGroups(self, groups, name):
2142 return self.mesh.IntersectListOfGroups(groups, name)
2144 ## Produces a cut of two groups.
2145 # A new group is created. All mesh elements that are present in
2146 # the main group but are not present in the tool group are added to the new one
2147 # @return an instance of SMESH_Group
2148 # @ingroup l2_grps_operon
2149 def CutGroups(self, main_group, tool_group, name):
2150 return self.mesh.CutGroups(main_group, tool_group, name)
2152 ## Produces a cut of groups.
2153 # A new group is created. All mesh elements that are present in main groups
2154 # but do not present in tool groups are added to the new one
2155 # @return an instance of SMESH_Group
2156 # @ingroup l2_grps_operon
2157 def CutListOfGroups(self, main_groups, tool_groups, name):
2158 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2161 # Create a standalone group of entities basing on nodes of other groups.
2162 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2163 # \param elemType - a type of elements to include to the new group; either of
2164 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2165 # \param name - a name of the new group.
2166 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2167 # basing on number of element nodes common with reference \a groups.
2168 # Meaning of possible values are:
2169 # - SMESH.ALL_NODES - include if all nodes are common,
2170 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2171 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2172 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2173 # \param underlyingOnly - if \c True (default), an element is included to the
2174 # new group provided that it is based on nodes of an element of \a groups;
2175 # in this case the reference \a groups are supposed to be of higher dimension
2176 # than \a elemType, which can be useful for example to get all faces lying on
2177 # volumes of the reference \a groups.
2178 # @return an instance of SMESH_Group
2179 # @ingroup l2_grps_operon
2180 def CreateDimGroup(self, groups, elemType, name,
2181 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2182 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2184 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2187 ## Convert group on geom into standalone group
2188 # @ingroup l2_grps_edit
2189 def ConvertToStandalone(self, group):
2190 return self.mesh.ConvertToStandalone(group)
2192 # Get some info about mesh:
2193 # ------------------------
2195 ## Returns the log of nodes and elements added or removed
2196 # since the previous clear of the log.
2197 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2198 # @return list of log_block structures:
2203 # @ingroup l1_auxiliary
2204 def GetLog(self, clearAfterGet):
2205 return self.mesh.GetLog(clearAfterGet)
2207 ## Clears the log of nodes and elements added or removed since the previous
2208 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2209 # @ingroup l1_auxiliary
2211 self.mesh.ClearLog()
2213 ## Toggles auto color mode on the object.
2214 # @param theAutoColor the flag which toggles auto color mode.
2215 # @ingroup l1_auxiliary
2216 def SetAutoColor(self, theAutoColor):
2217 self.mesh.SetAutoColor(theAutoColor)
2219 ## Gets flag of object auto color mode.
2220 # @return True or False
2221 # @ingroup l1_auxiliary
2222 def GetAutoColor(self):
2223 return self.mesh.GetAutoColor()
2225 ## Gets the internal ID
2226 # @return integer value, which is the internal Id of the mesh
2227 # @ingroup l1_auxiliary
2229 return self.mesh.GetId()
2232 # @return integer value, which is the study Id of the mesh
2233 # @ingroup l1_auxiliary
2234 def GetStudyId(self):
2235 return self.mesh.GetStudyId()
2237 ## Checks the group names for duplications.
2238 # Consider the maximum group name length stored in MED file.
2239 # @return True or False
2240 # @ingroup l1_auxiliary
2241 def HasDuplicatedGroupNamesMED(self):
2242 return self.mesh.HasDuplicatedGroupNamesMED()
2244 ## Obtains the mesh editor tool
2245 # @return an instance of SMESH_MeshEditor
2246 # @ingroup l1_modifying
2247 def GetMeshEditor(self):
2250 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2251 # can be passed as argument to a method accepting mesh, group or sub-mesh
2252 # @param ids list of IDs
2253 # @param elemType type of elements; this parameter is used to distinguish
2254 # IDs of nodes from IDs of elements; by default ids are treated as
2255 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2256 # @return an instance of SMESH_IDSource
2257 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2258 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2259 # mesh.DoSomething( idSrc )
2260 # idSrc.UnRegister()
2261 # @ingroup l1_auxiliary
2262 def GetIDSource(self, ids, elemType = SMESH.ALL):
2263 return self.editor.MakeIDSource(ids, elemType)
2266 # Get informations about mesh contents:
2267 # ------------------------------------
2269 ## Gets the mesh stattistic
2270 # @return dictionary type element - count of elements
2271 # @ingroup l1_meshinfo
2272 def GetMeshInfo(self, obj = None):
2273 if not obj: obj = self.mesh
2274 return self.smeshpyD.GetMeshInfo(obj)
2276 ## Returns the number of nodes in the mesh
2277 # @return an integer value
2278 # @ingroup l1_meshinfo
2280 return self.mesh.NbNodes()
2282 ## Returns the number of elements in the mesh
2283 # @return an integer value
2284 # @ingroup l1_meshinfo
2285 def NbElements(self):
2286 return self.mesh.NbElements()
2288 ## Returns the number of 0d elements in the mesh
2289 # @return an integer value
2290 # @ingroup l1_meshinfo
2291 def Nb0DElements(self):
2292 return self.mesh.Nb0DElements()
2294 ## Returns the number of ball discrete elements in the mesh
2295 # @return an integer value
2296 # @ingroup l1_meshinfo
2298 return self.mesh.NbBalls()
2300 ## Returns the number of edges in the mesh
2301 # @return an integer value
2302 # @ingroup l1_meshinfo
2304 return self.mesh.NbEdges()
2306 ## Returns the number of edges with the given order in the mesh
2307 # @param elementOrder the order of elements:
2308 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2309 # @return an integer value
2310 # @ingroup l1_meshinfo
2311 def NbEdgesOfOrder(self, elementOrder):
2312 return self.mesh.NbEdgesOfOrder(elementOrder)
2314 ## Returns the number of faces in the mesh
2315 # @return an integer value
2316 # @ingroup l1_meshinfo
2318 return self.mesh.NbFaces()
2320 ## Returns the number of faces with the given order in the mesh
2321 # @param elementOrder the order of elements:
2322 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2323 # @return an integer value
2324 # @ingroup l1_meshinfo
2325 def NbFacesOfOrder(self, elementOrder):
2326 return self.mesh.NbFacesOfOrder(elementOrder)
2328 ## Returns the number of triangles in the mesh
2329 # @return an integer value
2330 # @ingroup l1_meshinfo
2331 def NbTriangles(self):
2332 return self.mesh.NbTriangles()
2334 ## Returns the number of triangles with the given order in the mesh
2335 # @param elementOrder is the order of elements:
2336 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2337 # @return an integer value
2338 # @ingroup l1_meshinfo
2339 def NbTrianglesOfOrder(self, elementOrder):
2340 return self.mesh.NbTrianglesOfOrder(elementOrder)
2342 ## Returns the number of biquadratic triangles in the mesh
2343 # @return an integer value
2344 # @ingroup l1_meshinfo
2345 def NbBiQuadTriangles(self):
2346 return self.mesh.NbBiQuadTriangles()
2348 ## Returns the number of quadrangles in the mesh
2349 # @return an integer value
2350 # @ingroup l1_meshinfo
2351 def NbQuadrangles(self):
2352 return self.mesh.NbQuadrangles()
2354 ## Returns the number of quadrangles with the given order in the mesh
2355 # @param elementOrder the order of elements:
2356 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2357 # @return an integer value
2358 # @ingroup l1_meshinfo
2359 def NbQuadranglesOfOrder(self, elementOrder):
2360 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2362 ## Returns the number of biquadratic quadrangles in the mesh
2363 # @return an integer value
2364 # @ingroup l1_meshinfo
2365 def NbBiQuadQuadrangles(self):
2366 return self.mesh.NbBiQuadQuadrangles()
2368 ## Returns the number of polygons of given order in the mesh
2369 # @param elementOrder the order of elements:
2370 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2371 # @return an integer value
2372 # @ingroup l1_meshinfo
2373 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2374 return self.mesh.NbPolygonsOfOrder(elementOrder)
2376 ## Returns the number of volumes in the mesh
2377 # @return an integer value
2378 # @ingroup l1_meshinfo
2379 def NbVolumes(self):
2380 return self.mesh.NbVolumes()
2382 ## Returns the number of volumes with the given order in the mesh
2383 # @param elementOrder the order of elements:
2384 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2385 # @return an integer value
2386 # @ingroup l1_meshinfo
2387 def NbVolumesOfOrder(self, elementOrder):
2388 return self.mesh.NbVolumesOfOrder(elementOrder)
2390 ## Returns the number of tetrahedrons in the mesh
2391 # @return an integer value
2392 # @ingroup l1_meshinfo
2394 return self.mesh.NbTetras()
2396 ## Returns the number of tetrahedrons with the given order in the mesh
2397 # @param elementOrder the order of elements:
2398 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2399 # @return an integer value
2400 # @ingroup l1_meshinfo
2401 def NbTetrasOfOrder(self, elementOrder):
2402 return self.mesh.NbTetrasOfOrder(elementOrder)
2404 ## Returns the number of hexahedrons in the mesh
2405 # @return an integer value
2406 # @ingroup l1_meshinfo
2408 return self.mesh.NbHexas()
2410 ## Returns the number of hexahedrons with the given order in the mesh
2411 # @param elementOrder the order of elements:
2412 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2413 # @return an integer value
2414 # @ingroup l1_meshinfo
2415 def NbHexasOfOrder(self, elementOrder):
2416 return self.mesh.NbHexasOfOrder(elementOrder)
2418 ## Returns the number of triquadratic hexahedrons in the mesh
2419 # @return an integer value
2420 # @ingroup l1_meshinfo
2421 def NbTriQuadraticHexas(self):
2422 return self.mesh.NbTriQuadraticHexas()
2424 ## Returns the number of pyramids in the mesh
2425 # @return an integer value
2426 # @ingroup l1_meshinfo
2427 def NbPyramids(self):
2428 return self.mesh.NbPyramids()
2430 ## Returns the number of pyramids with the given order in the mesh
2431 # @param elementOrder the order of elements:
2432 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2433 # @return an integer value
2434 # @ingroup l1_meshinfo
2435 def NbPyramidsOfOrder(self, elementOrder):
2436 return self.mesh.NbPyramidsOfOrder(elementOrder)
2438 ## Returns the number of prisms in the mesh
2439 # @return an integer value
2440 # @ingroup l1_meshinfo
2442 return self.mesh.NbPrisms()
2444 ## Returns the number of prisms with the given order in the mesh
2445 # @param elementOrder the order of elements:
2446 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2447 # @return an integer value
2448 # @ingroup l1_meshinfo
2449 def NbPrismsOfOrder(self, elementOrder):
2450 return self.mesh.NbPrismsOfOrder(elementOrder)
2452 ## Returns the number of hexagonal prisms in the mesh
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2455 def NbHexagonalPrisms(self):
2456 return self.mesh.NbHexagonalPrisms()
2458 ## Returns the number of polyhedrons in the mesh
2459 # @return an integer value
2460 # @ingroup l1_meshinfo
2461 def NbPolyhedrons(self):
2462 return self.mesh.NbPolyhedrons()
2464 ## Returns the number of submeshes in the mesh
2465 # @return an integer value
2466 # @ingroup l1_meshinfo
2467 def NbSubMesh(self):
2468 return self.mesh.NbSubMesh()
2470 ## Returns the list of mesh elements IDs
2471 # @return the list of integer values
2472 # @ingroup l1_meshinfo
2473 def GetElementsId(self):
2474 return self.mesh.GetElementsId()
2476 ## Returns the list of IDs of mesh elements with the given type
2477 # @param elementType the required type of elements, either of
2478 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2479 # @return list of integer values
2480 # @ingroup l1_meshinfo
2481 def GetElementsByType(self, elementType):
2482 return self.mesh.GetElementsByType(elementType)
2484 ## Returns the list of mesh nodes IDs
2485 # @return the list of integer values
2486 # @ingroup l1_meshinfo
2487 def GetNodesId(self):
2488 return self.mesh.GetNodesId()
2490 # Get the information about mesh elements:
2491 # ------------------------------------
2493 ## Returns the type of mesh element
2494 # @return the value from SMESH::ElementType enumeration
2495 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2496 # @ingroup l1_meshinfo
2497 def GetElementType(self, id, iselem=True):
2498 return self.mesh.GetElementType(id, iselem)
2500 ## Returns the geometric type of mesh element
2501 # @return the value from SMESH::EntityType enumeration
2502 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2503 # @ingroup l1_meshinfo
2504 def GetElementGeomType(self, id):
2505 return self.mesh.GetElementGeomType(id)
2507 ## Returns the shape type of mesh element
2508 # @return the value from SMESH::GeometryType enumeration.
2509 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2510 # @ingroup l1_meshinfo
2511 def GetElementShape(self, id):
2512 return self.mesh.GetElementShape(id)
2514 ## Returns the list of submesh elements IDs
2515 # @param Shape a geom object(sub-shape) IOR
2516 # Shape must be the sub-shape of a ShapeToMesh()
2517 # @return the list of integer values
2518 # @ingroup l1_meshinfo
2519 def GetSubMeshElementsId(self, Shape):
2520 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2521 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2524 return self.mesh.GetSubMeshElementsId(ShapeID)
2526 ## Returns the list of submesh nodes IDs
2527 # @param Shape a geom object(sub-shape) IOR
2528 # Shape must be the sub-shape of a ShapeToMesh()
2529 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2530 # @return the list of integer values
2531 # @ingroup l1_meshinfo
2532 def GetSubMeshNodesId(self, Shape, all):
2533 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2534 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2537 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2539 ## Returns type of elements on given shape
2540 # @param Shape a geom object(sub-shape) IOR
2541 # Shape must be a sub-shape of a ShapeToMesh()
2542 # @return element type
2543 # @ingroup l1_meshinfo
2544 def GetSubMeshElementType(self, Shape):
2545 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2546 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2549 return self.mesh.GetSubMeshElementType(ShapeID)
2551 ## Gets the mesh description
2552 # @return string value
2553 # @ingroup l1_meshinfo
2555 return self.mesh.Dump()
2558 # Get the information about nodes and elements of a mesh by its IDs:
2559 # -----------------------------------------------------------
2561 ## Gets XYZ coordinates of a node
2562 # \n If there is no nodes for the given ID - returns an empty list
2563 # @return a list of double precision values
2564 # @ingroup l1_meshinfo
2565 def GetNodeXYZ(self, id):
2566 return self.mesh.GetNodeXYZ(id)
2568 ## Returns list of IDs of inverse elements for the given node
2569 # \n If there is no node for the given ID - returns an empty list
2570 # @return a list of integer values
2571 # @ingroup l1_meshinfo
2572 def GetNodeInverseElements(self, id):
2573 return self.mesh.GetNodeInverseElements(id)
2575 ## @brief Returns the position of a node on the shape
2576 # @return SMESH::NodePosition
2577 # @ingroup l1_meshinfo
2578 def GetNodePosition(self,NodeID):
2579 return self.mesh.GetNodePosition(NodeID)
2581 ## @brief Returns the position of an element on the shape
2582 # @return SMESH::ElementPosition
2583 # @ingroup l1_meshinfo
2584 def GetElementPosition(self,ElemID):
2585 return self.mesh.GetElementPosition(ElemID)
2587 ## Returns the ID of the shape, on which the given node was generated.
2588 # @return an integer value > 0 or -1 if there is no node for the given
2589 # ID or the node is not assigned to any geometry
2590 # @ingroup l1_meshinfo
2591 def GetShapeID(self, id):
2592 return self.mesh.GetShapeID(id)
2594 ## Returns the ID of the shape, on which the given element was generated.
2595 # @return an integer value > 0 or -1 if there is no element for the given
2596 # ID or the element is not assigned to any geometry
2597 # @ingroup l1_meshinfo
2598 def GetShapeIDForElem(self,id):
2599 return self.mesh.GetShapeIDForElem(id)
2601 ## Returns the number of nodes of the given element
2602 # @return an integer value > 0 or -1 if there is no element for the given ID
2603 # @ingroup l1_meshinfo
2604 def GetElemNbNodes(self, id):
2605 return self.mesh.GetElemNbNodes(id)
2607 ## Returns the node ID the given (zero based) index for the given element
2608 # \n If there is no element for the given ID - returns -1
2609 # \n If there is no node for the given index - returns -2
2610 # @return an integer value
2611 # @ingroup l1_meshinfo
2612 def GetElemNode(self, id, index):
2613 return self.mesh.GetElemNode(id, index)
2615 ## Returns the IDs of nodes of the given element
2616 # @return a list of integer values
2617 # @ingroup l1_meshinfo
2618 def GetElemNodes(self, id):
2619 return self.mesh.GetElemNodes(id)
2621 ## Returns true if the given node is the medium node in the given quadratic element
2622 # @ingroup l1_meshinfo
2623 def IsMediumNode(self, elementID, nodeID):
2624 return self.mesh.IsMediumNode(elementID, nodeID)
2626 ## Returns true if the given node is the medium node in one of quadratic elements
2627 # @param nodeID ID of the node
2628 # @param elementType the type of elements to check a state of the node, either of
2629 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2630 # @ingroup l1_meshinfo
2631 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2632 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2634 ## Returns the number of edges for the given element
2635 # @ingroup l1_meshinfo
2636 def ElemNbEdges(self, id):
2637 return self.mesh.ElemNbEdges(id)
2639 ## Returns the number of faces for the given element
2640 # @ingroup l1_meshinfo
2641 def ElemNbFaces(self, id):
2642 return self.mesh.ElemNbFaces(id)
2644 ## Returns nodes of given face (counted from zero) for given volumic element.
2645 # @ingroup l1_meshinfo
2646 def GetElemFaceNodes(self,elemId, faceIndex):
2647 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2649 ## Returns three components of normal of given mesh face
2650 # (or an empty array in KO case)
2651 # @ingroup l1_meshinfo
2652 def GetFaceNormal(self, faceId, normalized=False):
2653 return self.mesh.GetFaceNormal(faceId,normalized)
2655 ## Returns an element based on all given nodes.
2656 # @ingroup l1_meshinfo
2657 def FindElementByNodes(self,nodes):
2658 return self.mesh.FindElementByNodes(nodes)
2660 ## Returns true if the given element is a polygon
2661 # @ingroup l1_meshinfo
2662 def IsPoly(self, id):
2663 return self.mesh.IsPoly(id)
2665 ## Returns true if the given element is quadratic
2666 # @ingroup l1_meshinfo
2667 def IsQuadratic(self, id):
2668 return self.mesh.IsQuadratic(id)
2670 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2671 # @ingroup l1_meshinfo
2672 def GetBallDiameter(self, id):
2673 return self.mesh.GetBallDiameter(id)
2675 ## Returns XYZ coordinates of the barycenter of the given element
2676 # \n If there is no element for the given ID - returns an empty list
2677 # @return a list of three double values
2678 # @ingroup l1_meshinfo
2679 def BaryCenter(self, id):
2680 return self.mesh.BaryCenter(id)
2682 ## Passes mesh elements through the given filter and return IDs of fitting elements
2683 # @param theFilter SMESH_Filter
2684 # @return a list of ids
2685 # @ingroup l1_controls
2686 def GetIdsFromFilter(self, theFilter):
2687 theFilter.SetMesh( self.mesh )
2688 return theFilter.GetIDs()
2690 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2691 # Returns a list of special structures (borders).
2692 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2693 # @ingroup l1_controls
2694 def GetFreeBorders(self):
2695 aFilterMgr = self.smeshpyD.CreateFilterManager()
2696 aPredicate = aFilterMgr.CreateFreeEdges()
2697 aPredicate.SetMesh(self.mesh)
2698 aBorders = aPredicate.GetBorders()
2699 aFilterMgr.UnRegister()
2703 # Get mesh measurements information:
2704 # ------------------------------------
2706 ## Get minimum distance between two nodes, elements or distance to the origin
2707 # @param id1 first node/element id
2708 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2709 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2710 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2711 # @return minimum distance value
2712 # @sa GetMinDistance()
2713 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2714 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2715 return aMeasure.value
2717 ## Get measure structure specifying minimum distance data between two objects
2718 # @param id1 first node/element id
2719 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2720 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2721 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2722 # @return Measure structure
2724 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2726 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2728 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2731 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2733 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2738 aMeasurements = self.smeshpyD.CreateMeasurements()
2739 aMeasure = aMeasurements.MinDistance(id1, id2)
2740 genObjUnRegister([aMeasurements,id1, id2])
2743 ## Get bounding box of the specified object(s)
2744 # @param objects single source object or list of source objects or list of nodes/elements IDs
2745 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2746 # @c False specifies that @a objects are nodes
2747 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2748 # @sa GetBoundingBox()
2749 def BoundingBox(self, objects=None, isElem=False):
2750 result = self.GetBoundingBox(objects, isElem)
2754 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2757 ## Get measure structure specifying bounding box data of the specified object(s)
2758 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2759 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2760 # @c False specifies that @a objects are nodes
2761 # @return Measure structure
2763 def GetBoundingBox(self, IDs=None, isElem=False):
2766 elif isinstance(IDs, tuple):
2768 if not isinstance(IDs, list):
2770 if len(IDs) > 0 and isinstance(IDs[0], int):
2773 unRegister = genObjUnRegister()
2775 if isinstance(o, Mesh):
2776 srclist.append(o.mesh)
2777 elif hasattr(o, "_narrow"):
2778 src = o._narrow(SMESH.SMESH_IDSource)
2779 if src: srclist.append(src)
2781 elif isinstance(o, list):
2783 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2785 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2786 unRegister.set( srclist[-1] )
2789 aMeasurements = self.smeshpyD.CreateMeasurements()
2790 unRegister.set( aMeasurements )
2791 aMeasure = aMeasurements.BoundingBox(srclist)
2794 # Mesh edition (SMESH_MeshEditor functionality):
2795 # ---------------------------------------------
2797 ## Removes the elements from the mesh by ids
2798 # @param IDsOfElements is a list of ids of elements to remove
2799 # @return True or False
2800 # @ingroup l2_modif_del
2801 def RemoveElements(self, IDsOfElements):
2802 return self.editor.RemoveElements(IDsOfElements)
2804 ## Removes nodes from mesh by ids
2805 # @param IDsOfNodes is a list of ids of nodes to remove
2806 # @return True or False
2807 # @ingroup l2_modif_del
2808 def RemoveNodes(self, IDsOfNodes):
2809 return self.editor.RemoveNodes(IDsOfNodes)
2811 ## Removes all orphan (free) nodes from mesh
2812 # @return number of the removed nodes
2813 # @ingroup l2_modif_del
2814 def RemoveOrphanNodes(self):
2815 return self.editor.RemoveOrphanNodes()
2817 ## Add a node to the mesh by coordinates
2818 # @return Id of the new node
2819 # @ingroup l2_modif_add
2820 def AddNode(self, x, y, z):
2821 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2822 if hasVars: self.mesh.SetParameters(Parameters)
2823 return self.editor.AddNode( x, y, z)
2825 ## Creates a 0D element on a node with given number.
2826 # @param IDOfNode the ID of node for creation of the element.
2827 # @return the Id of the new 0D element
2828 # @ingroup l2_modif_add
2829 def Add0DElement(self, IDOfNode):
2830 return self.editor.Add0DElement(IDOfNode)
2832 ## Create 0D elements on all nodes of the given elements except those
2833 # nodes on which a 0D element already exists.
2834 # @param theObject an object on whose nodes 0D elements will be created.
2835 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2836 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2837 # @param theGroupName optional name of a group to add 0D elements created
2838 # and/or found on nodes of \a theObject.
2839 # @return an object (a new group or a temporary SMESH_IDSource) holding
2840 # IDs of new and/or found 0D elements. IDs of 0D elements
2841 # can be retrieved from the returned object by calling GetIDs()
2842 # @ingroup l2_modif_add
2843 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2844 unRegister = genObjUnRegister()
2845 if isinstance( theObject, Mesh ):
2846 theObject = theObject.GetMesh()
2847 if isinstance( theObject, list ):
2848 theObject = self.GetIDSource( theObject, SMESH.ALL )
2849 unRegister.set( theObject )
2850 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2852 ## Creates a ball element on a node with given ID.
2853 # @param IDOfNode the ID of node for creation of the element.
2854 # @param diameter the bal diameter.
2855 # @return the Id of the new ball element
2856 # @ingroup l2_modif_add
2857 def AddBall(self, IDOfNode, diameter):
2858 return self.editor.AddBall( IDOfNode, diameter )
2860 ## Creates a linear or quadratic edge (this is determined
2861 # by the number of given nodes).
2862 # @param IDsOfNodes the list of node IDs for creation of the element.
2863 # The order of nodes in this list should correspond to the description
2864 # of MED. \n This description is located by the following link:
2865 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2866 # @return the Id of the new edge
2867 # @ingroup l2_modif_add
2868 def AddEdge(self, IDsOfNodes):
2869 return self.editor.AddEdge(IDsOfNodes)
2871 ## Creates a linear or quadratic face (this is determined
2872 # by the number of given nodes).
2873 # @param IDsOfNodes the list of node IDs for creation of the element.
2874 # The order of nodes in this list should correspond to the description
2875 # of MED. \n This description is located by the following link:
2876 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2877 # @return the Id of the new face
2878 # @ingroup l2_modif_add
2879 def AddFace(self, IDsOfNodes):
2880 return self.editor.AddFace(IDsOfNodes)
2882 ## Adds a polygonal face to the mesh by the list of node IDs
2883 # @param IdsOfNodes the list of node IDs for creation of the element.
2884 # @return the Id of the new face
2885 # @ingroup l2_modif_add
2886 def AddPolygonalFace(self, IdsOfNodes):
2887 return self.editor.AddPolygonalFace(IdsOfNodes)
2889 ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2890 # @param IdsOfNodes the list of node IDs for creation of the element;
2891 # corner nodes follow first.
2892 # @return the Id of the new face
2893 # @ingroup l2_modif_add
2894 def AddQuadPolygonalFace(self, IdsOfNodes):
2895 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2897 ## Creates both simple and quadratic volume (this is determined
2898 # by the number of given nodes).
2899 # @param IDsOfNodes the list of node IDs for creation of the element.
2900 # The order of nodes in this list should correspond to the description
2901 # of MED. \n This description is located by the following link:
2902 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2903 # @return the Id of the new volumic element
2904 # @ingroup l2_modif_add
2905 def AddVolume(self, IDsOfNodes):
2906 return self.editor.AddVolume(IDsOfNodes)
2908 ## Creates a volume of many faces, giving nodes for each face.
2909 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2910 # @param Quantities the list of integer values, Quantities[i]
2911 # gives the quantity of nodes in face number i.
2912 # @return the Id of the new volumic element
2913 # @ingroup l2_modif_add
2914 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2915 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2917 ## Creates a volume of many faces, giving the IDs of the existing faces.
2918 # @param IdsOfFaces the list of face IDs for volume creation.
2920 # Note: The created volume will refer only to the nodes
2921 # of the given faces, not to the faces themselves.
2922 # @return the Id of the new volumic element
2923 # @ingroup l2_modif_add
2924 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2925 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2928 ## @brief Binds a node to a vertex
2929 # @param NodeID a node ID
2930 # @param Vertex a vertex or vertex ID
2931 # @return True if succeed else raises an exception
2932 # @ingroup l2_modif_add
2933 def SetNodeOnVertex(self, NodeID, Vertex):
2934 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2935 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2939 self.editor.SetNodeOnVertex(NodeID, VertexID)
2940 except SALOME.SALOME_Exception, inst:
2941 raise ValueError, inst.details.text
2945 ## @brief Stores the node position on an edge
2946 # @param NodeID a node ID
2947 # @param Edge an edge or edge ID
2948 # @param paramOnEdge a parameter on the edge where the node is located
2949 # @return True if succeed else raises an exception
2950 # @ingroup l2_modif_add
2951 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2952 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2953 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2957 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2958 except SALOME.SALOME_Exception, inst:
2959 raise ValueError, inst.details.text
2962 ## @brief Stores node position on a face
2963 # @param NodeID a node ID
2964 # @param Face a face or face ID
2965 # @param u U parameter on the face where the node is located
2966 # @param v V parameter on the face where the node is located
2967 # @return True if succeed else raises an exception
2968 # @ingroup l2_modif_add
2969 def SetNodeOnFace(self, NodeID, Face, u, v):
2970 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2971 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
2975 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2976 except SALOME.SALOME_Exception, inst:
2977 raise ValueError, inst.details.text
2980 ## @brief Binds a node to a solid
2981 # @param NodeID a node ID
2982 # @param Solid a solid or solid ID
2983 # @return True if succeed else raises an exception
2984 # @ingroup l2_modif_add
2985 def SetNodeInVolume(self, NodeID, Solid):
2986 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2987 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
2991 self.editor.SetNodeInVolume(NodeID, SolidID)
2992 except SALOME.SALOME_Exception, inst:
2993 raise ValueError, inst.details.text
2996 ## @brief Bind an element to a shape
2997 # @param ElementID an element ID
2998 # @param Shape a shape or shape ID
2999 # @return True if succeed else raises an exception
3000 # @ingroup l2_modif_add
3001 def SetMeshElementOnShape(self, ElementID, Shape):
3002 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3003 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3007 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3008 except SALOME.SALOME_Exception, inst:
3009 raise ValueError, inst.details.text
3013 ## Moves the node with the given id
3014 # @param NodeID the id of the node
3015 # @param x a new X coordinate
3016 # @param y a new Y coordinate
3017 # @param z a new Z coordinate
3018 # @return True if succeed else False
3019 # @ingroup l2_modif_movenode
3020 def MoveNode(self, NodeID, x, y, z):
3021 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3022 if hasVars: self.mesh.SetParameters(Parameters)
3023 return self.editor.MoveNode(NodeID, x, y, z)
3025 ## Finds the node closest to a point and moves it to a point location
3026 # @param x the X coordinate of a point
3027 # @param y the Y coordinate of a point
3028 # @param z the Z coordinate of a point
3029 # @param NodeID if specified (>0), the node with this ID is moved,
3030 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3031 # @return the ID of a node
3032 # @ingroup l2_modif_throughp
3033 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3034 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3035 if hasVars: self.mesh.SetParameters(Parameters)
3036 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3038 ## Finds the node closest to a point
3039 # @param x the X coordinate of a point
3040 # @param y the Y coordinate of a point
3041 # @param z the Z coordinate of a point
3042 # @return the ID of a node
3043 # @ingroup l2_modif_throughp
3044 def FindNodeClosestTo(self, x, y, z):
3045 #preview = self.mesh.GetMeshEditPreviewer()
3046 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3047 return self.editor.FindNodeClosestTo(x, y, z)
3049 ## Finds the elements where a point lays IN or ON
3050 # @param x the X coordinate of a point
3051 # @param y the Y coordinate of a point
3052 # @param z the Z coordinate of a point
3053 # @param elementType type of elements to find; either of
3054 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3055 # means elements of any type excluding nodes, discrete and 0D elements.
3056 # @param meshPart a part of mesh (group, sub-mesh) to search within
3057 # @return list of IDs of found elements
3058 # @ingroup l2_modif_throughp
3059 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3061 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3063 return self.editor.FindElementsByPoint(x, y, z, elementType)
3065 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3066 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3067 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3068 def GetPointState(self, x, y, z):
3069 return self.editor.GetPointState(x, y, z)
3071 ## Finds the node closest to a point and moves it to a point location
3072 # @param x the X coordinate of a point
3073 # @param y the Y coordinate of a point
3074 # @param z the Z coordinate of a point
3075 # @return the ID of a moved node
3076 # @ingroup l2_modif_throughp
3077 def MeshToPassThroughAPoint(self, x, y, z):
3078 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3080 ## Replaces two neighbour triangles sharing Node1-Node2 link
3081 # with the triangles built on the same 4 nodes but having other common link.
3082 # @param NodeID1 the ID of the first node
3083 # @param NodeID2 the ID of the second node
3084 # @return false if proper faces were not found
3085 # @ingroup l2_modif_cutquadr
3086 def InverseDiag(self, NodeID1, NodeID2):
3087 return self.editor.InverseDiag(NodeID1, NodeID2)
3089 ## Replaces two neighbour triangles sharing Node1-Node2 link
3090 # with a quadrangle built on the same 4 nodes.
3091 # @param NodeID1 the ID of the first node
3092 # @param NodeID2 the ID of the second node
3093 # @return false if proper faces were not found
3094 # @ingroup l2_modif_unitetri
3095 def DeleteDiag(self, NodeID1, NodeID2):
3096 return self.editor.DeleteDiag(NodeID1, NodeID2)
3098 ## Reorients elements by ids
3099 # @param IDsOfElements if undefined reorients all mesh elements
3100 # @return True if succeed else False
3101 # @ingroup l2_modif_changori
3102 def Reorient(self, IDsOfElements=None):
3103 if IDsOfElements == None:
3104 IDsOfElements = self.GetElementsId()
3105 return self.editor.Reorient(IDsOfElements)
3107 ## Reorients all elements of the object
3108 # @param theObject mesh, submesh or group
3109 # @return True if succeed else False
3110 # @ingroup l2_modif_changori
3111 def ReorientObject(self, theObject):
3112 if ( isinstance( theObject, Mesh )):
3113 theObject = theObject.GetMesh()
3114 return self.editor.ReorientObject(theObject)
3116 ## Reorient faces contained in \a the2DObject.
3117 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3118 # @param theDirection is a desired direction of normal of \a theFace.
3119 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3120 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3121 # compared with theDirection. It can be either ID of face or a point
3122 # by which the face will be found. The point can be given as either
3123 # a GEOM vertex or a list of point coordinates.
3124 # @return number of reoriented faces
3125 # @ingroup l2_modif_changori
3126 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3127 unRegister = genObjUnRegister()
3129 if isinstance( the2DObject, Mesh ):
3130 the2DObject = the2DObject.GetMesh()
3131 if isinstance( the2DObject, list ):
3132 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3133 unRegister.set( the2DObject )
3134 # check theDirection
3135 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3136 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3137 if isinstance( theDirection, list ):
3138 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3139 # prepare theFace and thePoint
3140 theFace = theFaceOrPoint
3141 thePoint = PointStruct(0,0,0)
3142 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3143 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3145 if isinstance( theFaceOrPoint, list ):
3146 thePoint = PointStruct( *theFaceOrPoint )
3148 if isinstance( theFaceOrPoint, PointStruct ):
3149 thePoint = theFaceOrPoint
3151 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3153 ## Reorient faces according to adjacent volumes.
3154 # @param the2DObject is a mesh, sub-mesh, group or list of
3155 # either IDs of faces or face groups.
3156 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3157 # @param theOutsideNormal to orient faces to have their normals
3158 # pointing either \a outside or \a inside the adjacent volumes.
3159 # @return number of reoriented faces.
3160 # @ingroup l2_modif_changori
3161 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3162 unRegister = genObjUnRegister()
3164 if not isinstance( the2DObject, list ):
3165 the2DObject = [ the2DObject ]
3166 elif the2DObject and isinstance( the2DObject[0], int ):
3167 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3168 unRegister.set( the2DObject )
3169 the2DObject = [ the2DObject ]
3170 for i,obj2D in enumerate( the2DObject ):
3171 if isinstance( obj2D, Mesh ):
3172 the2DObject[i] = obj2D.GetMesh()
3173 if isinstance( obj2D, list ):
3174 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3175 unRegister.set( the2DObject[i] )
3177 if isinstance( the3DObject, Mesh ):
3178 the3DObject = the3DObject.GetMesh()
3179 if isinstance( the3DObject, list ):
3180 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3181 unRegister.set( the3DObject )
3182 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3184 ## Fuses the neighbouring triangles into quadrangles.
3185 # @param IDsOfElements The triangles to be fused.
3186 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3187 # applied to possible quadrangles to choose a neighbour to fuse with.
3188 # Type SMESH.FunctorType._items in the Python Console to see all items.
3189 # Note that not all items correspond to numerical functors.
3190 # @param MaxAngle is the maximum angle between element normals at which the fusion
3191 # is still performed; theMaxAngle is mesured in radians.
3192 # Also it could be a name of variable which defines angle in degrees.
3193 # @return TRUE in case of success, FALSE otherwise.
3194 # @ingroup l2_modif_unitetri
3195 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3196 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3197 self.mesh.SetParameters(Parameters)
3198 if not IDsOfElements:
3199 IDsOfElements = self.GetElementsId()
3200 Functor = self.smeshpyD.GetFunctor(theCriterion)
3201 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3203 ## Fuses the neighbouring triangles of the object into quadrangles
3204 # @param theObject is mesh, submesh or group
3205 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3206 # applied to possible quadrangles to choose a neighbour to fuse with.
3207 # Type SMESH.FunctorType._items in the Python Console to see all items.
3208 # Note that not all items correspond to numerical functors.
3209 # @param MaxAngle a max angle between element normals at which the fusion
3210 # is still performed; theMaxAngle is mesured in radians.
3211 # @return TRUE in case of success, FALSE otherwise.
3212 # @ingroup l2_modif_unitetri
3213 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3214 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3215 self.mesh.SetParameters(Parameters)
3216 if isinstance( theObject, Mesh ):
3217 theObject = theObject.GetMesh()
3218 Functor = self.smeshpyD.GetFunctor(theCriterion)
3219 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3221 ## Splits quadrangles into triangles.
3222 # @param IDsOfElements the faces to be splitted.
3223 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3224 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3225 # value, then quadrangles will be split by the smallest diagonal.
3226 # Type SMESH.FunctorType._items in the Python Console to see all items.
3227 # Note that not all items correspond to numerical functors.
3228 # @return TRUE in case of success, FALSE otherwise.
3229 # @ingroup l2_modif_cutquadr
3230 def QuadToTri (self, IDsOfElements, theCriterion = None):
3231 if IDsOfElements == []:
3232 IDsOfElements = self.GetElementsId()
3233 if theCriterion is None:
3234 theCriterion = FT_MaxElementLength2D
3235 Functor = self.smeshpyD.GetFunctor(theCriterion)
3236 return self.editor.QuadToTri(IDsOfElements, Functor)
3238 ## Splits quadrangles into triangles.
3239 # @param theObject the object from which the list of elements is taken,
3240 # this is mesh, submesh or group
3241 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3242 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3243 # value, then quadrangles will be split by the smallest diagonal.
3244 # Type SMESH.FunctorType._items in the Python Console to see all items.
3245 # Note that not all items correspond to numerical functors.
3246 # @return TRUE in case of success, FALSE otherwise.
3247 # @ingroup l2_modif_cutquadr
3248 def QuadToTriObject (self, theObject, theCriterion = None):
3249 if ( isinstance( theObject, Mesh )):
3250 theObject = theObject.GetMesh()
3251 if theCriterion is None:
3252 theCriterion = FT_MaxElementLength2D
3253 Functor = self.smeshpyD.GetFunctor(theCriterion)
3254 return self.editor.QuadToTriObject(theObject, Functor)
3256 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3258 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3259 # group or a list of face IDs. By default all quadrangles are split
3260 # @ingroup l2_modif_cutquadr
3261 def QuadTo4Tri (self, theElements=[]):
3262 unRegister = genObjUnRegister()
3263 if isinstance( theElements, Mesh ):
3264 theElements = theElements.mesh
3265 elif not theElements:
3266 theElements = self.mesh
3267 elif isinstance( theElements, list ):
3268 theElements = self.GetIDSource( theElements, SMESH.FACE )
3269 unRegister.set( theElements )
3270 return self.editor.QuadTo4Tri( theElements )
3272 ## Splits quadrangles into triangles.
3273 # @param IDsOfElements the faces to be splitted
3274 # @param Diag13 is used to choose a diagonal for splitting.
3275 # @return TRUE in case of success, FALSE otherwise.
3276 # @ingroup l2_modif_cutquadr
3277 def SplitQuad (self, IDsOfElements, Diag13):
3278 if IDsOfElements == []:
3279 IDsOfElements = self.GetElementsId()
3280 return self.editor.SplitQuad(IDsOfElements, Diag13)
3282 ## Splits quadrangles into triangles.
3283 # @param theObject the object from which the list of elements is taken,
3284 # this is mesh, submesh or group
3285 # @param Diag13 is used to choose a diagonal for splitting.
3286 # @return TRUE in case of success, FALSE otherwise.
3287 # @ingroup l2_modif_cutquadr
3288 def SplitQuadObject (self, theObject, Diag13):
3289 if ( isinstance( theObject, Mesh )):
3290 theObject = theObject.GetMesh()
3291 return self.editor.SplitQuadObject(theObject, Diag13)
3293 ## Finds a better splitting of the given quadrangle.
3294 # @param IDOfQuad the ID of the quadrangle to be splitted.
3295 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3296 # choose a diagonal for splitting.
3297 # Type SMESH.FunctorType._items in the Python Console to see all items.
3298 # Note that not all items correspond to numerical functors.
3299 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3300 # diagonal is better, 0 if error occurs.
3301 # @ingroup l2_modif_cutquadr
3302 def BestSplit (self, IDOfQuad, theCriterion):
3303 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3305 ## Splits volumic elements into tetrahedrons
3306 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3307 # @param method flags passing splitting method:
3308 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3309 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3310 # @ingroup l2_modif_cutquadr
3311 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3312 unRegister = genObjUnRegister()
3313 if isinstance( elems, Mesh ):
3314 elems = elems.GetMesh()
3315 if ( isinstance( elems, list )):
3316 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3317 unRegister.set( elems )
3318 self.editor.SplitVolumesIntoTetra(elems, method)
3321 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3322 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3323 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3324 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3325 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3326 # will be split in order to keep the mesh conformal.
3327 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3328 # if None (default), all bi-quadratic elements will be split
3329 # @ingroup l2_modif_cutquadr
3330 def SplitBiQuadraticIntoLinear(self, elems=None):
3331 unRegister = genObjUnRegister()
3332 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3333 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3334 unRegister.set( elems )
3336 elems = [ self.GetMesh() ]
3337 if isinstance( elems, Mesh ):
3338 elems = [ elems.GetMesh() ]
3339 if not isinstance( elems, list ):
3341 self.editor.SplitBiQuadraticIntoLinear( elems )
3343 ## Splits hexahedra into prisms
3344 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3345 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3346 # gives a normal vector defining facets to split into triangles.
3347 # @a startHexPoint can be either a triple of coordinates or a vertex.
3348 # @param facetNormal a normal to a facet to split into triangles of a
3349 # hexahedron found by @a startHexPoint.
3350 # @a facetNormal can be either a triple of coordinates or an edge.
3351 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3352 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3353 # @param allDomains if @c False, only hexahedra adjacent to one closest
3354 # to @a startHexPoint are split, else @a startHexPoint
3355 # is used to find the facet to split in all domains present in @a elems.
3356 # @ingroup l2_modif_cutquadr
3357 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3358 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3360 unRegister = genObjUnRegister()
3361 if isinstance( elems, Mesh ):
3362 elems = elems.GetMesh()
3363 if ( isinstance( elems, list )):
3364 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3365 unRegister.set( elems )
3368 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3369 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3370 elif isinstance( startHexPoint, list ):
3371 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3374 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3375 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3376 elif isinstance( facetNormal, list ):
3377 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3380 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3382 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3384 ## Splits quadrangle faces near triangular facets of volumes
3386 # @ingroup l1_auxiliary
3387 def SplitQuadsNearTriangularFacets(self):
3388 faces_array = self.GetElementsByType(SMESH.FACE)
3389 for face_id in faces_array:
3390 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3391 quad_nodes = self.mesh.GetElemNodes(face_id)
3392 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3393 isVolumeFound = False
3394 for node1_elem in node1_elems:
3395 if not isVolumeFound:
3396 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3397 nb_nodes = self.GetElemNbNodes(node1_elem)
3398 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3399 volume_elem = node1_elem
3400 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3401 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3402 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3403 isVolumeFound = True
3404 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3405 self.SplitQuad([face_id], False) # diagonal 2-4
3406 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3407 isVolumeFound = True
3408 self.SplitQuad([face_id], True) # diagonal 1-3
3409 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3410 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3411 isVolumeFound = True
3412 self.SplitQuad([face_id], True) # diagonal 1-3
3414 ## @brief Splits hexahedrons into tetrahedrons.
3416 # This operation uses pattern mapping functionality for splitting.
3417 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3418 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3419 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3420 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3421 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3422 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3423 # @return TRUE in case of success, FALSE otherwise.
3424 # @ingroup l1_auxiliary
3425 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3426 # Pattern: 5.---------.6
3431 # (0,0,1) 4.---------.7 * |
3438 # (0,0,0) 0.---------.3
3439 pattern_tetra = "!!! Nb of points: \n 8 \n\
3449 !!! Indices of points of 6 tetras: \n\
3457 pattern = self.smeshpyD.GetPattern()
3458 isDone = pattern.LoadFromFile(pattern_tetra)
3460 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3463 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3464 isDone = pattern.MakeMesh(self.mesh, False, False)
3465 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3467 # split quafrangle faces near triangular facets of volumes
3468 self.SplitQuadsNearTriangularFacets()
3472 ## @brief Split hexahedrons into prisms.
3474 # Uses the pattern mapping functionality for splitting.
3475 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3476 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3477 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3478 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3479 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3480 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3481 # @return TRUE in case of success, FALSE otherwise.
3482 # @ingroup l1_auxiliary
3483 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3484 # Pattern: 5.---------.6
3489 # (0,0,1) 4.---------.7 |
3496 # (0,0,0) 0.---------.3
3497 pattern_prism = "!!! Nb of points: \n 8 \n\
3507 !!! Indices of points of 2 prisms: \n\
3511 pattern = self.smeshpyD.GetPattern()
3512 isDone = pattern.LoadFromFile(pattern_prism)
3514 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3517 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3518 isDone = pattern.MakeMesh(self.mesh, False, False)
3519 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3521 # Splits quafrangle faces near triangular facets of volumes
3522 self.SplitQuadsNearTriangularFacets()
3526 ## Smoothes elements
3527 # @param IDsOfElements the list if ids of elements to smooth
3528 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3529 # Note that nodes built on edges and boundary nodes are always fixed.
3530 # @param MaxNbOfIterations the maximum number of iterations
3531 # @param MaxAspectRatio varies in range [1.0, inf]
3532 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3533 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3534 # @return TRUE in case of success, FALSE otherwise.
3535 # @ingroup l2_modif_smooth
3536 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3537 MaxNbOfIterations, MaxAspectRatio, Method):
3538 if IDsOfElements == []:
3539 IDsOfElements = self.GetElementsId()
3540 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3541 self.mesh.SetParameters(Parameters)
3542 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3543 MaxNbOfIterations, MaxAspectRatio, Method)
3545 ## Smoothes elements which belong to the given object
3546 # @param theObject the object to smooth
3547 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3548 # Note that nodes built on edges and boundary nodes are always fixed.
3549 # @param MaxNbOfIterations the maximum number of iterations
3550 # @param MaxAspectRatio varies in range [1.0, inf]
3551 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3552 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3553 # @return TRUE in case of success, FALSE otherwise.
3554 # @ingroup l2_modif_smooth
3555 def SmoothObject(self, theObject, IDsOfFixedNodes,
3556 MaxNbOfIterations, MaxAspectRatio, Method):
3557 if ( isinstance( theObject, Mesh )):
3558 theObject = theObject.GetMesh()
3559 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3560 MaxNbOfIterations, MaxAspectRatio, Method)
3562 ## Parametrically smoothes the given elements
3563 # @param IDsOfElements the list if ids of elements to smooth
3564 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3565 # Note that nodes built on edges and boundary nodes are always fixed.
3566 # @param MaxNbOfIterations the maximum number of iterations
3567 # @param MaxAspectRatio varies in range [1.0, inf]
3568 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3569 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3570 # @return TRUE in case of success, FALSE otherwise.
3571 # @ingroup l2_modif_smooth
3572 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3573 MaxNbOfIterations, MaxAspectRatio, Method):
3574 if IDsOfElements == []:
3575 IDsOfElements = self.GetElementsId()
3576 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3577 self.mesh.SetParameters(Parameters)
3578 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3579 MaxNbOfIterations, MaxAspectRatio, Method)
3581 ## Parametrically smoothes the elements which belong to the given object
3582 # @param theObject the object to smooth
3583 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3584 # Note that nodes built on edges and boundary nodes are always fixed.
3585 # @param MaxNbOfIterations the maximum number of iterations
3586 # @param MaxAspectRatio varies in range [1.0, inf]
3587 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3588 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3589 # @return TRUE in case of success, FALSE otherwise.
3590 # @ingroup l2_modif_smooth
3591 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3592 MaxNbOfIterations, MaxAspectRatio, Method):
3593 if ( isinstance( theObject, Mesh )):
3594 theObject = theObject.GetMesh()
3595 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3596 MaxNbOfIterations, MaxAspectRatio, Method)
3598 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3599 # them with quadratic with the same id.
3600 # @param theForce3d new node creation method:
3601 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3602 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3603 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3604 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3605 # @ingroup l2_modif_tofromqu
3606 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3607 if isinstance( theSubMesh, Mesh ):
3608 theSubMesh = theSubMesh.mesh
3610 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3613 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3615 self.editor.ConvertToQuadratic(theForce3d)
3616 error = self.editor.GetLastError()
3617 if error and error.comment:
3620 ## Converts the mesh from quadratic to ordinary,
3621 # deletes old quadratic elements, \n replacing
3622 # them with ordinary mesh elements with the same id.
3623 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3624 # @ingroup l2_modif_tofromqu
3625 def ConvertFromQuadratic(self, theSubMesh=None):
3627 self.editor.ConvertFromQuadraticObject(theSubMesh)
3629 return self.editor.ConvertFromQuadratic()
3631 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3632 # @return TRUE if operation has been completed successfully, FALSE otherwise
3633 # @ingroup l2_modif_edit
3634 def Make2DMeshFrom3D(self):
3635 return self.editor.Make2DMeshFrom3D()
3637 ## Creates missing boundary elements
3638 # @param elements - elements whose boundary is to be checked:
3639 # mesh, group, sub-mesh or list of elements
3640 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3641 # @param dimension - defines type of boundary elements to create, either of
3642 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3643 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3644 # @param groupName - a name of group to store created boundary elements in,
3645 # "" means not to create the group
3646 # @param meshName - a name of new mesh to store created boundary elements in,
3647 # "" means not to create the new mesh
3648 # @param toCopyElements - if true, the checked elements will be copied into
3649 # the new mesh else only boundary elements will be copied into the new mesh
3650 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3651 # boundary elements will be copied into the new mesh
3652 # @return tuple (mesh, group) where boundary elements were added to
3653 # @ingroup l2_modif_edit
3654 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3655 toCopyElements=False, toCopyExistingBondary=False):
3656 unRegister = genObjUnRegister()
3657 if isinstance( elements, Mesh ):
3658 elements = elements.GetMesh()
3659 if ( isinstance( elements, list )):
3660 elemType = SMESH.ALL
3661 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3662 elements = self.editor.MakeIDSource(elements, elemType)
3663 unRegister.set( elements )
3664 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3665 toCopyElements,toCopyExistingBondary)
3666 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3670 # @brief Creates missing boundary elements around either the whole mesh or
3671 # groups of elements
3672 # @param dimension - defines type of boundary elements to create, either of
3673 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3674 # @param groupName - a name of group to store all boundary elements in,
3675 # "" means not to create the group
3676 # @param meshName - a name of a new mesh, which is a copy of the initial
3677 # mesh + created boundary elements; "" means not to create the new mesh
3678 # @param toCopyAll - if true, the whole initial mesh will be copied into
3679 # the new mesh else only boundary elements will be copied into the new mesh
3680 # @param groups - groups of elements to make boundary around
3681 # @retval tuple( long, mesh, groups )
3682 # long - number of added boundary elements
3683 # mesh - the mesh where elements were added to
3684 # group - the group of boundary elements or None
3686 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3687 toCopyAll=False, groups=[]):
3688 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3690 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3691 return nb, mesh, group
3693 ## Renumber mesh nodes (Obsolete, does nothing)
3694 # @ingroup l2_modif_renumber
3695 def RenumberNodes(self):
3696 self.editor.RenumberNodes()
3698 ## Renumber mesh elements (Obsole, does nothing)
3699 # @ingroup l2_modif_renumber
3700 def RenumberElements(self):
3701 self.editor.RenumberElements()
3703 ## Private method converting \a arg into a list of SMESH_IdSource's
3704 def _getIdSourceList(self, arg, idType, unRegister):
3705 if arg and isinstance( arg, list ):
3706 if isinstance( arg[0], int ):
3707 arg = self.GetIDSource( arg, idType )
3708 unRegister.set( arg )
3709 elif isinstance( arg[0], Mesh ):
3710 arg[0] = arg[0].GetMesh()
3711 elif isinstance( arg, Mesh ):
3713 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3717 ## Generates new elements by rotation of the given elements and nodes around the axis
3718 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3719 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3720 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3721 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3722 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3723 # which defines angle in degrees
3724 # @param NbOfSteps the number of steps
3725 # @param Tolerance tolerance
3726 # @param MakeGroups forces the generation of new groups from existing ones
3727 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3728 # of all steps, else - size of each step
3729 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3730 # @ingroup l2_modif_extrurev
3731 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3732 MakeGroups=False, TotalAngle=False):
3733 unRegister = genObjUnRegister()
3734 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3735 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3736 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3738 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3739 Axis = self.smeshpyD.GetAxisStruct( Axis )
3740 if isinstance( Axis, list ):
3741 Axis = SMESH.AxisStruct( *Axis )
3743 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3744 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3745 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3746 self.mesh.SetParameters(Parameters)
3747 if TotalAngle and NbOfSteps:
3748 AngleInRadians /= NbOfSteps
3749 return self.editor.RotationSweepObjects( nodes, edges, faces,
3750 Axis, AngleInRadians,
3751 NbOfSteps, Tolerance, MakeGroups)
3753 ## Generates new elements by rotation of the elements around the axis
3754 # @param IDsOfElements the list of ids of elements to sweep
3755 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3756 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3757 # @param NbOfSteps the number of steps
3758 # @param Tolerance tolerance
3759 # @param MakeGroups forces the generation of new groups from existing ones
3760 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3761 # of all steps, else - size of each step
3762 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3763 # @ingroup l2_modif_extrurev
3764 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3765 MakeGroups=False, TotalAngle=False):
3766 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3767 AngleInRadians, NbOfSteps, Tolerance,
3768 MakeGroups, TotalAngle)
3770 ## Generates new elements by rotation of the elements of object around the axis
3771 # @param theObject object which elements should be sweeped.
3772 # It can be a mesh, a sub mesh or a group.
3773 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3774 # @param AngleInRadians the angle of Rotation
3775 # @param NbOfSteps number of steps
3776 # @param Tolerance tolerance
3777 # @param MakeGroups forces the generation of new groups from existing ones
3778 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3779 # of all steps, else - size of each step
3780 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3781 # @ingroup l2_modif_extrurev
3782 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3783 MakeGroups=False, TotalAngle=False):
3784 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3785 AngleInRadians, NbOfSteps, Tolerance,
3786 MakeGroups, TotalAngle )
3788 ## Generates new elements by rotation of the elements of object around the axis
3789 # @param theObject object which elements should be sweeped.
3790 # It can be a mesh, a sub mesh or a group.
3791 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3792 # @param AngleInRadians the angle of Rotation
3793 # @param NbOfSteps number of steps
3794 # @param Tolerance tolerance
3795 # @param MakeGroups forces the generation of new groups from existing ones
3796 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3797 # of all steps, else - size of each step
3798 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3799 # @ingroup l2_modif_extrurev
3800 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3801 MakeGroups=False, TotalAngle=False):
3802 return self.RotationSweepObjects([],theObject,[], Axis,
3803 AngleInRadians, NbOfSteps, Tolerance,
3804 MakeGroups, TotalAngle)
3806 ## Generates new elements by rotation of the elements of object around the axis
3807 # @param theObject object which elements should be sweeped.
3808 # It can be a mesh, a sub mesh or a group.
3809 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3810 # @param AngleInRadians the angle of Rotation
3811 # @param NbOfSteps number of steps
3812 # @param Tolerance tolerance
3813 # @param MakeGroups forces the generation of new groups from existing ones
3814 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3815 # of all steps, else - size of each step
3816 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3817 # @ingroup l2_modif_extrurev
3818 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3819 MakeGroups=False, TotalAngle=False):
3820 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3821 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3823 ## Generates new elements by extrusion of the given elements and nodes
3824 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3825 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3826 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3827 # @param StepVector vector or DirStruct or 3 vector components, defining
3828 # the direction and value of extrusion for one step (the total extrusion
3829 # length will be NbOfSteps * ||StepVector||)
3830 # @param NbOfSteps the number of steps
3831 # @param MakeGroups forces the generation of new groups from existing ones
3832 # @param scaleFactors optional scale factors to apply during extrusion
3833 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3834 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3835 # @param basePoint optional scaling center; if not provided, a gravity center of
3836 # nodes and elements being extruded is used as the scaling center.
3838 # - a list of tree components of the point or
3841 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3842 # @ingroup l2_modif_extrurev
3843 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3844 scaleFactors=[], linearVariation=False, basePoint=[] ):
3845 unRegister = genObjUnRegister()
3846 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3847 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3848 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3850 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3851 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3852 if isinstance( StepVector, list ):
3853 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3855 if isinstance( basePoint, int):
3856 xyz = self.GetNodeXYZ( basePoint )
3858 raise RuntimeError, "Invalid node ID: %s" % basePoint
3860 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3861 basePoint = self.geompyD.PointCoordinates( basePoint )
3863 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3864 Parameters = StepVector.PS.parameters + var_separator + Parameters
3865 self.mesh.SetParameters(Parameters)
3867 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3868 StepVector, NbOfSteps,
3869 scaleFactors, linearVariation, basePoint,
3873 ## Generates new elements by extrusion of the elements with given ids
3874 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3875 # @param StepVector vector or DirStruct or 3 vector components, defining
3876 # the direction and value of extrusion for one step (the total extrusion
3877 # length will be NbOfSteps * ||StepVector||)
3878 # @param NbOfSteps the number of steps
3879 # @param MakeGroups forces the generation of new groups from existing ones
3880 # @param IsNodes is True if elements with given ids are nodes
3881 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3882 # @ingroup l2_modif_extrurev
3883 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3885 if IsNodes: n = IDsOfElements
3886 else : e,f, = IDsOfElements,IDsOfElements
3887 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3889 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3890 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3891 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3892 # @param StepSize length of one extrusion step (the total extrusion
3893 # length will be \a NbOfSteps * \a StepSize ).
3894 # @param NbOfSteps number of extrusion steps.
3895 # @param ByAverageNormal if True each node is translated by \a StepSize
3896 # along the average of the normal vectors to the faces sharing the node;
3897 # else each node is translated along the same average normal till
3898 # intersection with the plane got by translation of the face sharing
3899 # the node along its own normal by \a StepSize.
3900 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3901 # for every node of \a Elements.
3902 # @param MakeGroups forces generation of new groups from existing ones.
3903 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3904 # is not yet implemented. This parameter is used if \a Elements contains
3905 # both faces and edges, i.e. \a Elements is a Mesh.
3906 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3907 # empty list otherwise.
3908 # @ingroup l2_modif_extrurev
3909 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3910 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3911 unRegister = genObjUnRegister()
3912 if isinstance( Elements, Mesh ):
3913 Elements = [ Elements.GetMesh() ]
3914 if isinstance( Elements, list ):
3916 raise RuntimeError, "Elements empty!"
3917 if isinstance( Elements[0], int ):
3918 Elements = self.GetIDSource( Elements, SMESH.ALL )
3919 unRegister.set( Elements )
3920 if not isinstance( Elements, list ):
3921 Elements = [ Elements ]
3922 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3923 self.mesh.SetParameters(Parameters)
3924 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3925 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3927 ## Generates new elements by extrusion of the elements or nodes which belong to the object
3928 # @param theObject the object whose elements or nodes should be processed.
3929 # It can be a mesh, a sub-mesh or a group.
3930 # @param StepVector vector or DirStruct or 3 vector components, defining
3931 # the direction and value of extrusion for one step (the total extrusion
3932 # length will be NbOfSteps * ||StepVector||)
3933 # @param NbOfSteps the number of steps
3934 # @param MakeGroups forces the generation of new groups from existing ones
3935 # @param IsNodes is True if elements to extrude are nodes
3936 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3937 # @ingroup l2_modif_extrurev
3938 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3940 if IsNodes: n = theObject
3941 else : e,f, = theObject,theObject
3942 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3944 ## Generates new elements by extrusion of edges which belong to the object
3945 # @param theObject object whose 1D elements should be processed.
3946 # It can be a mesh, a sub-mesh or a group.
3947 # @param StepVector vector or DirStruct or 3 vector components, defining
3948 # the direction and value of extrusion for one step (the total extrusion
3949 # length will be NbOfSteps * ||StepVector||)
3950 # @param NbOfSteps the number of steps
3951 # @param MakeGroups to generate new groups from existing ones
3952 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3953 # @ingroup l2_modif_extrurev
3954 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3955 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3957 ## Generates new elements by extrusion of faces which belong to the object
3958 # @param theObject object whose 2D elements should be processed.
3959 # It can be a mesh, a sub-mesh or a group.
3960 # @param StepVector vector or DirStruct or 3 vector components, defining
3961 # the direction and value of extrusion for one step (the total extrusion
3962 # length will be NbOfSteps * ||StepVector||)
3963 # @param NbOfSteps the number of steps
3964 # @param MakeGroups forces the generation of new groups from existing ones
3965 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3966 # @ingroup l2_modif_extrurev
3967 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3968 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3970 ## Generates new elements by extrusion of the elements with given ids
3971 # @param IDsOfElements is ids of elements
3972 # @param StepVector vector or DirStruct or 3 vector components, defining
3973 # the direction and value of extrusion for one step (the total extrusion
3974 # length will be NbOfSteps * ||StepVector||)
3975 # @param NbOfSteps the number of steps
3976 # @param ExtrFlags sets flags for extrusion
3977 # @param SewTolerance uses for comparing locations of nodes if flag
3978 # EXTRUSION_FLAG_SEW is set
3979 # @param MakeGroups forces the generation of new groups from existing ones
3980 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3981 # @ingroup l2_modif_extrurev
3982 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3983 ExtrFlags, SewTolerance, MakeGroups=False):
3984 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3985 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3986 if isinstance( StepVector, list ):
3987 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3988 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3989 ExtrFlags, SewTolerance, MakeGroups)
3991 ## Generates new elements by extrusion of the given elements and nodes along the path.
3992 # The path of extrusion must be a meshed edge.
3993 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3994 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3995 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3996 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3997 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3998 # contains not only path segments, else it can be None
3999 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4000 # @param HasAngles allows the shape to be rotated around the path
4001 # to get the resulting mesh in a helical fashion
4002 # @param Angles list of angles
4003 # @param LinearVariation forces the computation of rotation angles as linear
4004 # variation of the given Angles along path steps
4005 # @param HasRefPoint allows using the reference point
4006 # @param RefPoint the point around which the shape is rotated (the mass center of the
4007 # shape by default). The User can specify any point as the Reference Point.
4008 # @param MakeGroups forces the generation of new groups from existing ones
4009 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4010 # @ingroup l2_modif_extrurev
4011 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4012 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4013 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4014 unRegister = genObjUnRegister()
4015 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4016 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4017 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4019 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4020 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4021 if isinstance( RefPoint, list ):
4022 if not RefPoint: RefPoint = [0,0,0]
4023 RefPoint = SMESH.PointStruct( *RefPoint )
4024 if isinstance( PathMesh, Mesh ):
4025 PathMesh = PathMesh.GetMesh()
4026 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4027 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4028 self.mesh.SetParameters(Parameters)
4029 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4030 PathMesh, PathShape, NodeStart,
4031 HasAngles, Angles, LinearVariation,
4032 HasRefPoint, RefPoint, MakeGroups)
4034 ## Generates new elements by extrusion of the given elements
4035 # The path of extrusion must be a meshed edge.
4036 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4037 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4038 # @param NodeStart the start node from Path. Defines the direction of extrusion
4039 # @param HasAngles allows the shape to be rotated around the path
4040 # to get the resulting mesh in a helical fashion
4041 # @param Angles list of angles in radians
4042 # @param LinearVariation forces the computation of rotation angles as linear
4043 # variation of the given Angles along path steps
4044 # @param HasRefPoint allows using the reference point
4045 # @param RefPoint the point around which the elements are rotated (the mass
4046 # center of the elements by default).
4047 # The User can specify any point as the Reference Point.
4048 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4049 # @param MakeGroups forces the generation of new groups from existing ones
4050 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4051 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4052 # only SMESH::Extrusion_Error otherwise
4053 # @ingroup l2_modif_extrurev
4054 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4055 HasAngles=False, Angles=[], LinearVariation=False,
4056 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4057 ElemType=SMESH.FACE):
4059 if ElemType == SMESH.NODE: n = Base
4060 if ElemType == SMESH.EDGE: e = Base
4061 if ElemType == SMESH.FACE: f = Base
4062 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4063 HasAngles, Angles, LinearVariation,
4064 HasRefPoint, RefPoint, MakeGroups)
4065 if MakeGroups: return gr,er
4068 ## Generates new elements by extrusion of the given elements
4069 # The path of extrusion must be a meshed edge.
4070 # @param IDsOfElements ids of elements
4071 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4072 # @param PathShape shape(edge) defines the sub-mesh for the path
4073 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4074 # @param HasAngles allows the shape to be rotated around the path
4075 # to get the resulting mesh in a helical fashion
4076 # @param Angles list of angles in radians
4077 # @param HasRefPoint allows using the reference point
4078 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4079 # The User can specify any point as the Reference Point.
4080 # @param MakeGroups forces the generation of new groups from existing ones
4081 # @param LinearVariation forces the computation of rotation angles as linear
4082 # variation of the given Angles along path steps
4083 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4084 # only SMESH::Extrusion_Error otherwise
4085 # @ingroup l2_modif_extrurev
4086 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4087 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4088 MakeGroups=False, LinearVariation=False):
4089 n,e,f = [],IDsOfElements,IDsOfElements
4090 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4091 NodeStart, HasAngles, Angles,
4093 HasRefPoint, RefPoint, MakeGroups)
4094 if MakeGroups: return gr,er
4097 ## Generates new elements by extrusion of the elements which belong to the object
4098 # The path of extrusion must be a meshed edge.
4099 # @param theObject the object whose elements should be processed.
4100 # It can be a mesh, a sub-mesh or a group.
4101 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4102 # @param PathShape shape(edge) defines the sub-mesh for the path
4103 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4104 # @param HasAngles allows the shape to be rotated around the path
4105 # to get the resulting mesh in a helical fashion
4106 # @param Angles list of angles
4107 # @param HasRefPoint allows using the reference point
4108 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4109 # The User can specify any point as the Reference Point.
4110 # @param MakeGroups forces the generation of new groups from existing ones
4111 # @param LinearVariation forces the computation of rotation angles as linear
4112 # variation of the given Angles along path steps
4113 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4114 # only SMESH::Extrusion_Error otherwise
4115 # @ingroup l2_modif_extrurev
4116 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4117 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4118 MakeGroups=False, LinearVariation=False):
4119 n,e,f = [],theObject,theObject
4120 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4121 HasAngles, Angles, LinearVariation,
4122 HasRefPoint, RefPoint, MakeGroups)
4123 if MakeGroups: return gr,er
4126 ## Generates new elements by extrusion of mesh segments which belong to the object
4127 # The path of extrusion must be a meshed edge.
4128 # @param theObject the object whose 1D elements should be processed.
4129 # It can be a mesh, a sub-mesh or a group.
4130 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4131 # @param PathShape shape(edge) defines the sub-mesh for the path
4132 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4133 # @param HasAngles allows the shape to be rotated around the path
4134 # to get the resulting mesh in a helical fashion
4135 # @param Angles list of angles
4136 # @param HasRefPoint allows using the reference point
4137 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4138 # The User can specify any point as the Reference Point.
4139 # @param MakeGroups forces the generation of new groups from existing ones
4140 # @param LinearVariation forces the computation of rotation angles as linear
4141 # variation of the given Angles along path steps
4142 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4143 # only SMESH::Extrusion_Error otherwise
4144 # @ingroup l2_modif_extrurev
4145 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4146 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4147 MakeGroups=False, LinearVariation=False):
4148 n,e,f = [],theObject,[]
4149 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4150 HasAngles, Angles, LinearVariation,
4151 HasRefPoint, RefPoint, MakeGroups)
4152 if MakeGroups: return gr,er
4155 ## Generates new elements by extrusion of faces which belong to the object
4156 # The path of extrusion must be a meshed edge.
4157 # @param theObject the object whose 2D elements should be processed.
4158 # It can be a mesh, a sub-mesh or a group.
4159 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4160 # @param PathShape shape(edge) defines the sub-mesh for the path
4161 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4162 # @param HasAngles allows the shape to be rotated around the path
4163 # to get the resulting mesh in a helical fashion
4164 # @param Angles list of angles
4165 # @param HasRefPoint allows using the reference point
4166 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4167 # The User can specify any point as the Reference Point.
4168 # @param MakeGroups forces the generation of new groups from existing ones
4169 # @param LinearVariation forces the computation of rotation angles as linear
4170 # variation of the given Angles along path steps
4171 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4172 # only SMESH::Extrusion_Error otherwise
4173 # @ingroup l2_modif_extrurev
4174 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4175 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4176 MakeGroups=False, LinearVariation=False):
4177 n,e,f = [],[],theObject
4178 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4179 HasAngles, Angles, LinearVariation,
4180 HasRefPoint, RefPoint, MakeGroups)
4181 if MakeGroups: return gr,er
4184 ## Creates a symmetrical copy of mesh elements
4185 # @param IDsOfElements list of elements ids
4186 # @param Mirror is AxisStruct or geom object(point, line, plane)
4187 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4188 # If the Mirror is a geom object this parameter is unnecessary
4189 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4190 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4191 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4192 # @ingroup l2_modif_trsf
4193 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4194 if IDsOfElements == []:
4195 IDsOfElements = self.GetElementsId()
4196 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4197 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4198 theMirrorType = Mirror._mirrorType
4200 self.mesh.SetParameters(Mirror.parameters)
4201 if Copy and MakeGroups:
4202 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4203 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4206 ## Creates a new mesh by a symmetrical copy of mesh elements
4207 # @param IDsOfElements the list of elements ids
4208 # @param Mirror is 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 MakeGroups to generate new groups from existing ones
4212 # @param NewMeshName a name of the new mesh to create
4213 # @return instance of Mesh class
4214 # @ingroup l2_modif_trsf
4215 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4216 if IDsOfElements == []:
4217 IDsOfElements = self.GetElementsId()
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 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4224 MakeGroups, NewMeshName)
4225 return Mesh(self.smeshpyD,self.geompyD,mesh)
4227 ## Creates a symmetrical copy of the object
4228 # @param theObject mesh, submesh or group
4229 # @param Mirror AxisStruct or geom object (point, line, plane)
4230 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4231 # If the Mirror is a geom object this parameter is unnecessary
4232 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4233 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4234 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4235 # @ingroup l2_modif_trsf
4236 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4237 if ( isinstance( theObject, Mesh )):
4238 theObject = theObject.GetMesh()
4239 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4240 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4241 theMirrorType = Mirror._mirrorType
4243 self.mesh.SetParameters(Mirror.parameters)
4244 if Copy and MakeGroups:
4245 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4246 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4249 ## Creates a new mesh by a symmetrical copy of the object
4250 # @param theObject mesh, submesh or group
4251 # @param Mirror AxisStruct or geom object (point, line, plane)
4252 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4253 # If the Mirror is a geom object this parameter is unnecessary
4254 # @param MakeGroups forces the generation of new groups from existing ones
4255 # @param NewMeshName the name of the new mesh to create
4256 # @return instance of Mesh class
4257 # @ingroup l2_modif_trsf
4258 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4259 if ( isinstance( theObject, Mesh )):
4260 theObject = theObject.GetMesh()
4261 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4262 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4263 theMirrorType = Mirror._mirrorType
4265 self.mesh.SetParameters(Mirror.parameters)
4266 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4267 MakeGroups, NewMeshName)
4268 return Mesh( self.smeshpyD,self.geompyD,mesh )
4270 ## Translates the elements
4271 # @param IDsOfElements list of elements ids
4272 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4273 # @param Copy allows copying the translated elements
4274 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4275 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4276 # @ingroup l2_modif_trsf
4277 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4278 if IDsOfElements == []:
4279 IDsOfElements = self.GetElementsId()
4280 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4281 Vector = self.smeshpyD.GetDirStruct(Vector)
4282 if isinstance( Vector, list ):
4283 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4284 self.mesh.SetParameters(Vector.PS.parameters)
4285 if Copy and MakeGroups:
4286 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4287 self.editor.Translate(IDsOfElements, Vector, Copy)
4290 ## Creates a new mesh of translated elements
4291 # @param IDsOfElements list of elements ids
4292 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4293 # @param MakeGroups forces the generation of new groups from existing ones
4294 # @param NewMeshName the name of the newly created mesh
4295 # @return instance of Mesh class
4296 # @ingroup l2_modif_trsf
4297 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4298 if IDsOfElements == []:
4299 IDsOfElements = self.GetElementsId()
4300 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4301 Vector = self.smeshpyD.GetDirStruct(Vector)
4302 if isinstance( Vector, list ):
4303 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4304 self.mesh.SetParameters(Vector.PS.parameters)
4305 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4306 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4308 ## Translates the object
4309 # @param theObject the object to translate (mesh, submesh, or group)
4310 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4311 # @param Copy allows copying the translated elements
4312 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4313 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4314 # @ingroup l2_modif_trsf
4315 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4316 if ( isinstance( theObject, Mesh )):
4317 theObject = theObject.GetMesh()
4318 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4319 Vector = self.smeshpyD.GetDirStruct(Vector)
4320 if isinstance( Vector, list ):
4321 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4322 self.mesh.SetParameters(Vector.PS.parameters)
4323 if Copy and MakeGroups:
4324 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4325 self.editor.TranslateObject(theObject, Vector, Copy)
4328 ## Creates a new mesh from the translated object
4329 # @param theObject the object to translate (mesh, submesh, or group)
4330 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4331 # @param MakeGroups forces the generation of new groups from existing ones
4332 # @param NewMeshName the name of the newly created mesh
4333 # @return instance of Mesh class
4334 # @ingroup l2_modif_trsf
4335 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4336 if isinstance( theObject, Mesh ):
4337 theObject = theObject.GetMesh()
4338 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4339 Vector = self.smeshpyD.GetDirStruct(Vector)
4340 if isinstance( Vector, list ):
4341 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4342 self.mesh.SetParameters(Vector.PS.parameters)
4343 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4344 return Mesh( self.smeshpyD, self.geompyD, mesh )
4348 ## Scales the object
4349 # @param theObject - the object to translate (mesh, submesh, or group)
4350 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4351 # @param theScaleFact - list of 1-3 scale factors for axises
4352 # @param Copy - allows copying the translated elements
4353 # @param MakeGroups - forces the generation of new groups from existing
4355 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4356 # empty list otherwise
4357 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4358 unRegister = genObjUnRegister()
4359 if ( isinstance( theObject, Mesh )):
4360 theObject = theObject.GetMesh()
4361 if ( isinstance( theObject, list )):
4362 theObject = self.GetIDSource(theObject, SMESH.ALL)
4363 unRegister.set( theObject )
4364 if ( isinstance( thePoint, list )):
4365 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4366 if ( isinstance( theScaleFact, float )):
4367 theScaleFact = [theScaleFact]
4368 if ( isinstance( theScaleFact, int )):
4369 theScaleFact = [ float(theScaleFact)]
4371 self.mesh.SetParameters(thePoint.parameters)
4373 if Copy and MakeGroups:
4374 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4375 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4378 ## Creates a new mesh from the translated object
4379 # @param theObject - the object to translate (mesh, submesh, or group)
4380 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4381 # @param theScaleFact - list of 1-3 scale factors for axises
4382 # @param MakeGroups - forces the generation of new groups from existing ones
4383 # @param NewMeshName - the name of the newly created mesh
4384 # @return instance of Mesh class
4385 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4386 unRegister = genObjUnRegister()
4387 if (isinstance(theObject, Mesh)):
4388 theObject = theObject.GetMesh()
4389 if ( isinstance( theObject, list )):
4390 theObject = self.GetIDSource(theObject,SMESH.ALL)
4391 unRegister.set( theObject )
4392 if ( isinstance( thePoint, list )):
4393 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4394 if ( isinstance( theScaleFact, float )):
4395 theScaleFact = [theScaleFact]
4396 if ( isinstance( theScaleFact, int )):
4397 theScaleFact = [ float(theScaleFact)]
4399 self.mesh.SetParameters(thePoint.parameters)
4400 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4401 MakeGroups, NewMeshName)
4402 return Mesh( self.smeshpyD, self.geompyD, mesh )
4406 ## Rotates the elements
4407 # @param IDsOfElements list of elements 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 Copy allows copying the rotated elements
4411 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4412 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4413 # @ingroup l2_modif_trsf
4414 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
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 if Copy and MakeGroups:
4423 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4424 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4427 ## Creates a new mesh of rotated elements
4428 # @param IDsOfElements list of element ids
4429 # @param Axis the axis of rotation (AxisStruct or geom line)
4430 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4431 # @param MakeGroups forces the generation of new groups from existing ones
4432 # @param NewMeshName the name of the newly created mesh
4433 # @return instance of Mesh class
4434 # @ingroup l2_modif_trsf
4435 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4436 if IDsOfElements == []:
4437 IDsOfElements = self.GetElementsId()
4438 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4439 Axis = self.smeshpyD.GetAxisStruct(Axis)
4440 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4441 Parameters = Axis.parameters + var_separator + Parameters
4442 self.mesh.SetParameters(Parameters)
4443 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4444 MakeGroups, NewMeshName)
4445 return Mesh( self.smeshpyD, self.geompyD, mesh )
4447 ## Rotates the 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 Copy allows copying the rotated elements
4452 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4453 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4454 # @ingroup l2_modif_trsf
4455 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
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 self.mesh.SetParameters(Parameters)
4463 if Copy and MakeGroups:
4464 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4465 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4468 ## Creates a new mesh from the rotated object
4469 # @param theObject the object to rotate (mesh, submesh, or group)
4470 # @param Axis the axis of rotation (AxisStruct or geom line)
4471 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4472 # @param MakeGroups forces the generation of new groups from existing ones
4473 # @param NewMeshName the name of the newly created mesh
4474 # @return instance of Mesh class
4475 # @ingroup l2_modif_trsf
4476 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4477 if (isinstance( theObject, Mesh )):
4478 theObject = theObject.GetMesh()
4479 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4480 Axis = self.smeshpyD.GetAxisStruct(Axis)
4481 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4482 Parameters = Axis.parameters + ":" + Parameters
4483 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4484 MakeGroups, NewMeshName)
4485 self.mesh.SetParameters(Parameters)
4486 return Mesh( self.smeshpyD, self.geompyD, mesh )
4488 ## Finds groups of adjacent nodes within Tolerance.
4489 # @param Tolerance the value of tolerance
4490 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4491 # corner and medium nodes in separate groups thus preventing
4492 # their further merge.
4493 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4494 # @ingroup l2_modif_trsf
4495 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4496 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4498 ## Finds groups of ajacent nodes within Tolerance.
4499 # @param Tolerance the value of tolerance
4500 # @param SubMeshOrGroup SubMesh or Group
4501 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4502 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4503 # corner and medium nodes in separate groups thus preventing
4504 # their further merge.
4505 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4506 # @ingroup l2_modif_trsf
4507 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4508 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4509 unRegister = genObjUnRegister()
4510 if (isinstance( SubMeshOrGroup, Mesh )):
4511 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4512 if not isinstance( exceptNodes, list ):
4513 exceptNodes = [ exceptNodes ]
4514 if exceptNodes and isinstance( exceptNodes[0], int ):
4515 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4516 unRegister.set( exceptNodes )
4517 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4518 exceptNodes, SeparateCornerAndMediumNodes)
4521 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4522 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4523 # by nodes 1 and 25 correspondingly in all elements and groups
4524 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4525 # If @a NodesToKeep does not include a node to keep for some group to merge,
4526 # then the first node in the group is kept.
4527 # @ingroup l2_modif_trsf
4528 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4529 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4530 self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4532 ## Finds the elements built on the same nodes.
4533 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4534 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4535 # @ingroup l2_modif_trsf
4536 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4537 if not MeshOrSubMeshOrGroup:
4538 MeshOrSubMeshOrGroup=self.mesh
4539 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4540 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4541 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4543 ## Merges elements in each given group.
4544 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4545 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4546 # replaced by elements 1 and 25 in all groups)
4547 # @ingroup l2_modif_trsf
4548 def MergeElements(self, GroupsOfElementsID):
4549 self.editor.MergeElements(GroupsOfElementsID)
4551 ## Leaves one element and removes all other elements built on the same nodes.
4552 # @ingroup l2_modif_trsf
4553 def MergeEqualElements(self):
4554 self.editor.MergeEqualElements()
4556 ## Returns groups of FreeBorder's coincident within the given tolerance.
4557 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4558 # size of elements adjacent to free borders being compared is used.
4559 # @return SMESH.CoincidentFreeBorders structure
4560 # @ingroup l2_modif_trsf
4561 def FindCoincidentFreeBorders (self, tolerance=0.):
4562 return self.editor.FindCoincidentFreeBorders( tolerance )
4564 ## Sew FreeBorder's of each group
4565 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4566 # where each enclosed list contains node IDs of a group of coincident free
4567 # borders such that each consequent triple of IDs within a group describes
4568 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4569 # last node of a border.
4570 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4571 # groups of coincident free borders, each group including two borders.
4572 # @param createPolygons if @c True faces adjacent to free borders are converted to
4573 # polygons if a node of opposite border falls on a face edge, else such
4574 # faces are split into several ones.
4575 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4576 # polyhedra if a node of opposite border falls on a volume edge, else such
4577 # volumes, if any, remain intact and the mesh becomes non-conformal.
4578 # @return a number of successfully sewed groups
4579 # @ingroup l2_modif_trsf
4580 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4581 if freeBorders and isinstance( freeBorders, list ):
4582 # construct SMESH.CoincidentFreeBorders
4583 if isinstance( freeBorders[0], int ):
4584 freeBorders = [freeBorders]
4586 coincidentGroups = []
4587 for nodeList in freeBorders:
4588 if not nodeList or len( nodeList ) % 3:
4589 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4592 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4593 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4594 nodeList = nodeList[3:]
4596 coincidentGroups.append( group )
4598 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4600 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4602 ## Sews free borders
4603 # @return SMESH::Sew_Error
4604 # @ingroup l2_modif_trsf
4605 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4606 FirstNodeID2, SecondNodeID2, LastNodeID2,
4607 CreatePolygons, CreatePolyedrs):
4608 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4609 FirstNodeID2, SecondNodeID2, LastNodeID2,
4610 CreatePolygons, CreatePolyedrs)
4612 ## Sews conform free borders
4613 # @return SMESH::Sew_Error
4614 # @ingroup l2_modif_trsf
4615 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4616 FirstNodeID2, SecondNodeID2):
4617 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4618 FirstNodeID2, SecondNodeID2)
4620 ## Sews border to side
4621 # @return SMESH::Sew_Error
4622 # @ingroup l2_modif_trsf
4623 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4624 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4625 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4626 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4628 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4629 # merged with the nodes of elements of Side2.
4630 # The number of elements in theSide1 and in theSide2 must be
4631 # equal and they should have similar nodal connectivity.
4632 # The nodes to merge should belong to side borders and
4633 # the first node should be linked to the second.
4634 # @return SMESH::Sew_Error
4635 # @ingroup l2_modif_trsf
4636 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4637 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4638 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4639 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4640 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4641 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4643 ## Sets new nodes for the given element.
4644 # @param ide the element id
4645 # @param newIDs nodes ids
4646 # @return If the number of nodes does not correspond to the type of element - returns false
4647 # @ingroup l2_modif_edit
4648 def ChangeElemNodes(self, ide, newIDs):
4649 return self.editor.ChangeElemNodes(ide, newIDs)
4651 ## If during the last operation of MeshEditor some nodes were
4652 # created, this method returns the list of their IDs, \n
4653 # if new nodes were not created - returns empty list
4654 # @return the list of integer values (can be empty)
4655 # @ingroup l1_auxiliary
4656 def GetLastCreatedNodes(self):
4657 return self.editor.GetLastCreatedNodes()
4659 ## If during the last operation of MeshEditor some elements were
4660 # created this method returns the list of their IDs, \n
4661 # if new elements were not created - returns empty list
4662 # @return the list of integer values (can be empty)
4663 # @ingroup l1_auxiliary
4664 def GetLastCreatedElems(self):
4665 return self.editor.GetLastCreatedElems()
4667 ## Clears sequences of nodes and elements created by mesh edition oparations
4668 # @ingroup l1_auxiliary
4669 def ClearLastCreated(self):
4670 self.editor.ClearLastCreated()
4672 ## Creates duplicates of given elements, i.e. creates new elements based on the
4673 # same nodes as the given ones.
4674 # @param theElements - container of elements to duplicate. It can be a Mesh,
4675 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4676 # a Mesh, elements of highest dimension are duplicated
4677 # @param theGroupName - a name of group to contain the generated elements.
4678 # If a group with such a name already exists, the new elements
4679 # are added to the existng group, else a new group is created.
4680 # If \a theGroupName is empty, new elements are not added
4682 # @return a group where the new elements are added. None if theGroupName == "".
4683 # @ingroup l2_modif_edit
4684 def DoubleElements(self, theElements, theGroupName=""):
4685 unRegister = genObjUnRegister()
4686 if isinstance( theElements, Mesh ):
4687 theElements = theElements.mesh
4688 elif isinstance( theElements, list ):
4689 theElements = self.GetIDSource( theElements, SMESH.ALL )
4690 unRegister.set( theElements )
4691 return self.editor.DoubleElements(theElements, theGroupName)
4693 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4694 # @param theNodes identifiers of nodes to be doubled
4695 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4696 # nodes. If list of element identifiers is empty then nodes are doubled but
4697 # they not assigned to elements
4698 # @return TRUE if operation has been completed successfully, FALSE otherwise
4699 # @ingroup l2_modif_edit
4700 def DoubleNodes(self, theNodes, theModifiedElems):
4701 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4703 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4704 # This method provided for convenience works as DoubleNodes() described above.
4705 # @param theNodeId identifiers of node to be doubled
4706 # @param theModifiedElems identifiers of elements to be updated
4707 # @return TRUE if operation has been completed successfully, FALSE otherwise
4708 # @ingroup l2_modif_edit
4709 def DoubleNode(self, theNodeId, theModifiedElems):
4710 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4712 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4713 # This method provided for convenience works as DoubleNodes() described above.
4714 # @param theNodes group of nodes to be doubled
4715 # @param theModifiedElems group of elements to be updated.
4716 # @param theMakeGroup forces the generation of a group containing new nodes.
4717 # @return TRUE or a created group if operation has been completed successfully,
4718 # FALSE or None otherwise
4719 # @ingroup l2_modif_edit
4720 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4722 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4723 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4725 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4726 # This method provided for convenience works as DoubleNodes() described above.
4727 # @param theNodes list of groups of nodes to be doubled
4728 # @param theModifiedElems list of groups of elements to be updated.
4729 # @param theMakeGroup forces the generation of a group containing new nodes.
4730 # @return TRUE if operation has been completed successfully, FALSE otherwise
4731 # @ingroup l2_modif_edit
4732 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4734 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4735 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4737 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4738 # @param theElems - the list of elements (edges or faces) to be replicated
4739 # The nodes for duplication could be found from these elements
4740 # @param theNodesNot - list of nodes to NOT replicate
4741 # @param theAffectedElems - the list of elements (cells and edges) to which the
4742 # replicated nodes should be associated to.
4743 # @return TRUE if operation has been completed successfully, FALSE otherwise
4744 # @ingroup l2_modif_edit
4745 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4746 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4748 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4749 # @param theElems - the list of elements (edges or faces) to be replicated
4750 # The nodes for duplication could be found from these elements
4751 # @param theNodesNot - list of nodes to NOT replicate
4752 # @param theShape - shape to detect affected elements (element which geometric center
4753 # located on or inside shape).
4754 # The replicated nodes should be associated to affected elements.
4755 # @return TRUE if operation has been completed successfully, FALSE otherwise
4756 # @ingroup l2_modif_edit
4757 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4758 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4760 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4761 # This method provided for convenience works as DoubleNodes() described above.
4762 # @param theElems - group of of elements (edges or faces) to be replicated
4763 # @param theNodesNot - group of nodes not to replicated
4764 # @param theAffectedElems - group of elements to which the replicated nodes
4765 # should be associated to.
4766 # @param theMakeGroup forces the generation of a group containing new elements.
4767 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4768 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4769 # FALSE or None otherwise
4770 # @ingroup l2_modif_edit
4771 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4772 theMakeGroup=False, theMakeNodeGroup=False):
4773 if theMakeGroup or theMakeNodeGroup:
4774 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4776 theMakeGroup, theMakeNodeGroup)
4777 if theMakeGroup and theMakeNodeGroup:
4780 return twoGroups[ int(theMakeNodeGroup) ]
4781 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4783 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4784 # This method provided for convenience works as DoubleNodes() described above.
4785 # @param theElems - group of of elements (edges or faces) to be replicated
4786 # @param theNodesNot - group of nodes not to replicated
4787 # @param theShape - shape to detect affected elements (element which geometric center
4788 # located on or inside shape).
4789 # The replicated nodes should be associated to affected elements.
4790 # @ingroup l2_modif_edit
4791 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4792 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4794 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4795 # This method provided for convenience works as DoubleNodes() described above.
4796 # @param theElems - list of groups of elements (edges or faces) to be replicated
4797 # @param theNodesNot - list of groups of nodes not to replicated
4798 # @param theAffectedElems - group of elements to which the replicated nodes
4799 # should be associated to.
4800 # @param theMakeGroup forces the generation of a group containing new elements.
4801 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4802 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4803 # FALSE or None otherwise
4804 # @ingroup l2_modif_edit
4805 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4806 theMakeGroup=False, theMakeNodeGroup=False):
4807 if theMakeGroup or theMakeNodeGroup:
4808 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4810 theMakeGroup, theMakeNodeGroup)
4811 if theMakeGroup and theMakeNodeGroup:
4814 return twoGroups[ int(theMakeNodeGroup) ]
4815 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4817 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4818 # This method provided for convenience works as DoubleNodes() described above.
4819 # @param theElems - list of groups of elements (edges or faces) to be replicated
4820 # @param theNodesNot - list of groups of nodes not to replicated
4821 # @param theShape - shape to detect affected elements (element which geometric center
4822 # located on or inside shape).
4823 # The replicated nodes should be associated to affected elements.
4824 # @return TRUE if operation has been completed successfully, FALSE otherwise
4825 # @ingroup l2_modif_edit
4826 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4827 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4829 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4830 # This method is the first step of DoubleNodeElemGroupsInRegion.
4831 # @param theElems - list of groups of elements (edges or faces) to be replicated
4832 # @param theNodesNot - list of groups of nodes not to replicated
4833 # @param theShape - shape to detect affected elements (element which geometric center
4834 # located on or inside shape).
4835 # The replicated nodes should be associated to affected elements.
4836 # @return groups of affected elements
4837 # @ingroup l2_modif_edit
4838 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4839 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4841 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4842 # The list of groups must describe a partition of the mesh volumes.
4843 # The nodes of the internal faces at the boundaries of the groups are doubled.
4844 # In option, the internal faces are replaced by flat elements.
4845 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4846 # @param theDomains - list of groups of volumes
4847 # @param createJointElems - if TRUE, create the elements
4848 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4849 # the boundary between \a theDomains and the rest mesh
4850 # @return TRUE if operation has been completed successfully, FALSE otherwise
4851 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4852 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4854 ## Double nodes on some external faces and create flat elements.
4855 # Flat elements are mainly used by some types of mechanic calculations.
4857 # Each group of the list must be constituted of faces.
4858 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4859 # @param theGroupsOfFaces - list of groups of faces
4860 # @return TRUE if operation has been completed successfully, FALSE otherwise
4861 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4862 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4864 ## identify all the elements around a geom shape, get the faces delimiting the hole
4866 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4867 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4869 def _getFunctor(self, funcType ):
4870 fn = self.functors[ funcType._v ]
4872 fn = self.smeshpyD.GetFunctor(funcType)
4873 fn.SetMesh(self.mesh)
4874 self.functors[ funcType._v ] = fn
4877 ## Returns value of a functor for a given element
4878 # @param funcType an item of SMESH.FunctorType enum
4879 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4880 # @param elemId element or node ID
4881 # @param isElem @a elemId is ID of element or node
4882 # @return the functor value or zero in case of invalid arguments
4883 def FunctorValue(self, funcType, elemId, isElem=True):
4884 fn = self._getFunctor( funcType )
4885 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4886 val = fn.GetValue(elemId)
4891 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4892 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4893 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4894 # @ingroup l1_measurements
4895 def GetLength(self, elemId=None):
4898 length = self.smeshpyD.GetLength(self)
4900 length = self.FunctorValue(SMESH.FT_Length, elemId)
4903 ## Get area of 2D element or sum of areas of all 2D mesh elements
4904 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4905 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4906 # @ingroup l1_measurements
4907 def GetArea(self, elemId=None):
4910 area = self.smeshpyD.GetArea(self)
4912 area = self.FunctorValue(SMESH.FT_Area, elemId)
4915 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4916 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4917 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4918 # @ingroup l1_measurements
4919 def GetVolume(self, elemId=None):
4922 volume = self.smeshpyD.GetVolume(self)
4924 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4927 ## Get maximum element length.
4928 # @param elemId mesh element ID
4929 # @return element's maximum length value
4930 # @ingroup l1_measurements
4931 def GetMaxElementLength(self, elemId):
4932 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4933 ftype = SMESH.FT_MaxElementLength3D
4935 ftype = SMESH.FT_MaxElementLength2D
4936 return self.FunctorValue(ftype, elemId)
4938 ## Get aspect ratio of 2D or 3D element.
4939 # @param elemId mesh element ID
4940 # @return element's aspect ratio value
4941 # @ingroup l1_measurements
4942 def GetAspectRatio(self, elemId):
4943 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4944 ftype = SMESH.FT_AspectRatio3D
4946 ftype = SMESH.FT_AspectRatio
4947 return self.FunctorValue(ftype, elemId)
4949 ## Get warping angle of 2D element.
4950 # @param elemId mesh element ID
4951 # @return element's warping angle value
4952 # @ingroup l1_measurements
4953 def GetWarping(self, elemId):
4954 return self.FunctorValue(SMESH.FT_Warping, elemId)
4956 ## Get minimum angle of 2D element.
4957 # @param elemId mesh element ID
4958 # @return element's minimum angle value
4959 # @ingroup l1_measurements
4960 def GetMinimumAngle(self, elemId):
4961 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4963 ## Get taper of 2D element.
4964 # @param elemId mesh element ID
4965 # @return element's taper value
4966 # @ingroup l1_measurements
4967 def GetTaper(self, elemId):
4968 return self.FunctorValue(SMESH.FT_Taper, elemId)
4970 ## Get skew of 2D element.
4971 # @param elemId mesh element ID
4972 # @return element's skew value
4973 # @ingroup l1_measurements
4974 def GetSkew(self, elemId):
4975 return self.FunctorValue(SMESH.FT_Skew, elemId)
4977 ## Return minimal and maximal value of a given functor.
4978 # @param funType a functor type, an item of SMESH.FunctorType enum
4979 # (one of SMESH.FunctorType._items)
4980 # @param meshPart a part of mesh (group, sub-mesh) to treat
4981 # @return tuple (min,max)
4982 # @ingroup l1_measurements
4983 def GetMinMax(self, funType, meshPart=None):
4984 unRegister = genObjUnRegister()
4985 if isinstance( meshPart, list ):
4986 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4987 unRegister.set( meshPart )
4988 if isinstance( meshPart, Mesh ):
4989 meshPart = meshPart.mesh
4990 fun = self._getFunctor( funType )
4993 if hasattr( meshPart, "SetMesh" ):
4994 meshPart.SetMesh( self.mesh ) # set mesh to filter
4995 hist = fun.GetLocalHistogram( 1, False, meshPart )
4997 hist = fun.GetHistogram( 1, False )
4999 return hist[0].min, hist[0].max
5002 pass # end of Mesh class
5005 ## Class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5006 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5008 class meshProxy(SMESH._objref_SMESH_Mesh):
5010 SMESH._objref_SMESH_Mesh.__init__(self)
5011 def __deepcopy__(self, memo=None):
5012 new = self.__class__()
5014 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5015 if len( args ) == 3:
5016 args += SMESH.ALL_NODES, True
5017 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5019 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5022 ## Class wrapping SMESH_SubMesh in order to add Compute()
5024 class submeshProxy(SMESH._objref_SMESH_subMesh):
5026 SMESH._objref_SMESH_subMesh.__init__(self)
5028 def __deepcopy__(self, memo=None):
5029 new = self.__class__()
5032 ## Computes the sub-mesh and returns the status of the computation
5033 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5034 # @return True or False
5035 # @ingroup l2_construct
5036 def Compute(self,refresh=False):
5038 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5040 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5042 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5043 smeshgui = salome.ImportComponentGUI("SMESH")
5044 smeshgui.Init(self.mesh.GetStudyId())
5045 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5046 if refresh: salome.sg.updateObjBrowser(1)
5051 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5054 ## Class used to compensate change of CORBA API of SMESH_MeshEditor for backward compatibility
5055 # with old dump scripts which call SMESH_MeshEditor directly and not via smeshBuilder.Mesh
5057 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5059 SMESH._objref_SMESH_MeshEditor.__init__(self)
5061 def __getattr__(self, name ): # method called if an attribute not found
5062 if not self.mesh: # look for name() method in Mesh class
5063 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5064 if hasattr( self.mesh, name ):
5065 return getattr( self.mesh, name )
5066 if name == "ExtrusionAlongPathObjX":
5067 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5068 print "meshEditor: attribute '%s' NOT FOUND" % name
5070 def __deepcopy__(self, memo=None):
5071 new = self.__class__()
5073 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5074 if len( args ) == 1: args += False,
5075 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5076 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5077 if len( args ) == 2: args += False,
5078 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5079 def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
5080 if len( args ) == 1:
5081 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
5082 NodesToKeep = args[1]
5083 unRegister = genObjUnRegister()
5085 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5086 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5087 if not isinstance( NodesToKeep, list ):
5088 NodesToKeep = [ NodesToKeep ]
5089 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
5091 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5093 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
5095 class Pattern(SMESH._objref_SMESH_Pattern):
5097 def LoadFromFile(self, patternTextOrFile ):
5098 text = patternTextOrFile
5099 if os.path.exists( text ):
5100 text = open( patternTextOrFile ).read()
5102 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5104 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5105 decrFun = lambda i: i-1
5106 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5107 theMesh.SetParameters(Parameters)
5108 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5110 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5111 decrFun = lambda i: i-1
5112 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5113 theMesh.SetParameters(Parameters)
5114 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5116 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5117 if isinstance( mesh, Mesh ):
5118 mesh = mesh.GetMesh()
5119 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5121 # Registering the new proxy for Pattern
5122 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5124 ## Private class used to bind methods creating algorithms to the class Mesh
5129 self.defaultAlgoType = ""
5130 self.algoTypeToClass = {}
5132 # Stores a python class of algorithm
5133 def add(self, algoClass):
5134 if type( algoClass ).__name__ == 'classobj' and \
5135 hasattr( algoClass, "algoType"):
5136 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5137 if not self.defaultAlgoType and \
5138 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5139 self.defaultAlgoType = algoClass.algoType
5140 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5142 # creates a copy of self and assign mesh to the copy
5143 def copy(self, mesh):
5144 other = algoCreator()
5145 other.defaultAlgoType = self.defaultAlgoType
5146 other.algoTypeToClass = self.algoTypeToClass
5150 # creates an instance of algorithm
5151 def __call__(self,algo="",geom=0,*args):
5152 algoType = self.defaultAlgoType
5153 for arg in args + (algo,geom):
5154 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5156 if isinstance( arg, str ) and arg:
5158 if not algoType and self.algoTypeToClass:
5159 algoType = self.algoTypeToClass.keys()[0]
5160 if self.algoTypeToClass.has_key( algoType ):
5161 #print "Create algo",algoType
5162 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5163 raise RuntimeError, "No class found for algo type %s" % algoType
5166 ## Private class used to substitute and store variable parameters of hypotheses.
5168 class hypMethodWrapper:
5169 def __init__(self, hyp, method):
5171 self.method = method
5172 #print "REBIND:", method.__name__
5175 # call a method of hypothesis with calling SetVarParameter() before
5176 def __call__(self,*args):
5178 return self.method( self.hyp, *args ) # hypothesis method with no args
5180 #print "MethWrapper.__call__",self.method.__name__, args
5182 parsed = ParseParameters(*args) # replace variables with their values
5183 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5184 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5185 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5186 # maybe there is a replaced string arg which is not variable
5187 result = self.method( self.hyp, *args )
5188 except ValueError, detail: # raised by ParseParameters()
5190 result = self.method( self.hyp, *args )
5191 except omniORB.CORBA.BAD_PARAM:
5192 raise ValueError, detail # wrong variable name
5197 ## A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
5199 class genObjUnRegister:
5201 def __init__(self, genObj=None):
5202 self.genObjList = []
5206 def set(self, genObj):
5207 "Store one or a list of of SALOME.GenericObj'es"
5208 if isinstance( genObj, list ):
5209 self.genObjList.extend( genObj )
5211 self.genObjList.append( genObj )
5215 for genObj in self.genObjList:
5216 if genObj and hasattr( genObj, "UnRegister" ):
5220 ## Bind methods creating mesher plug-ins to the Mesh class
5222 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5224 #print "pluginName: ", pluginName
5225 pluginBuilderName = pluginName + "Builder"
5227 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5228 except Exception, e:
5229 from salome_utils import verbose
5230 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5232 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5233 plugin = eval( pluginBuilderName )
5234 #print " plugin:" , str(plugin)
5236 # add methods creating algorithms to Mesh
5237 for k in dir( plugin ):
5238 if k[0] == '_': continue
5239 algo = getattr( plugin, k )
5240 #print " algo:", str(algo)
5241 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5242 #print " meshMethod:" , str(algo.meshMethod)
5243 if not hasattr( Mesh, algo.meshMethod ):
5244 setattr( Mesh, algo.meshMethod, algoCreator() )
5246 getattr( Mesh, algo.meshMethod ).add( algo )