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()
967 elif theCriterion == FT_NodeConnectivityNumber:
968 functor = aFilterMgr.CreateNodeConnectivityNumber()
969 elif theCriterion == FT_BallDiameter:
970 functor = aFilterMgr.CreateBallDiameter()
972 print "Error: given parameter is not numerical functor type."
973 aFilterMgr.UnRegister()
976 ## Creates hypothesis
977 # @param theHType mesh hypothesis type (string)
978 # @param theLibName mesh plug-in library name
979 # @return created hypothesis instance
980 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
981 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
983 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
986 # wrap hypothesis methods
987 #print "HYPOTHESIS", theHType
988 for meth_name in dir( hyp.__class__ ):
989 if not meth_name.startswith("Get") and \
990 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
991 method = getattr ( hyp.__class__, meth_name )
993 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
997 ## Gets the mesh statistic
998 # @return dictionary "element type" - "count of elements"
999 # @ingroup l1_meshinfo
1000 def GetMeshInfo(self, obj):
1001 if isinstance( obj, Mesh ):
1004 if hasattr(obj, "GetMeshInfo"):
1005 values = obj.GetMeshInfo()
1006 for i in range(SMESH.Entity_Last._v):
1007 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1011 ## Get minimum distance between two objects
1013 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1014 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1016 # @param src1 first source object
1017 # @param src2 second source object
1018 # @param id1 node/element id from the first source
1019 # @param id2 node/element id from the second (or first) source
1020 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1021 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1022 # @return minimum distance value
1023 # @sa GetMinDistance()
1024 # @ingroup l1_measurements
1025 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1026 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1030 result = result.value
1033 ## Get measure structure specifying minimum distance data between two objects
1035 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1036 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1038 # @param src1 first source object
1039 # @param src2 second source object
1040 # @param id1 node/element id from the first source
1041 # @param id2 node/element id from the second (or first) source
1042 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1043 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1044 # @return Measure structure or None if input data is invalid
1046 # @ingroup l1_measurements
1047 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1048 if isinstance(src1, Mesh): src1 = src1.mesh
1049 if isinstance(src2, Mesh): src2 = src2.mesh
1050 if src2 is None and id2 != 0: src2 = src1
1051 if not hasattr(src1, "_narrow"): return None
1052 src1 = src1._narrow(SMESH.SMESH_IDSource)
1053 if not src1: return None
1054 unRegister = genObjUnRegister()
1057 e = m.GetMeshEditor()
1059 src1 = e.MakeIDSource([id1], SMESH.FACE)
1061 src1 = e.MakeIDSource([id1], SMESH.NODE)
1062 unRegister.set( src1 )
1064 if hasattr(src2, "_narrow"):
1065 src2 = src2._narrow(SMESH.SMESH_IDSource)
1066 if src2 and id2 != 0:
1068 e = m.GetMeshEditor()
1070 src2 = e.MakeIDSource([id2], SMESH.FACE)
1072 src2 = e.MakeIDSource([id2], SMESH.NODE)
1073 unRegister.set( src2 )
1076 aMeasurements = self.CreateMeasurements()
1077 unRegister.set( aMeasurements )
1078 result = aMeasurements.MinDistance(src1, src2)
1081 ## Get bounding box of the specified object(s)
1082 # @param objects single source object or list of source objects
1083 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1084 # @sa GetBoundingBox()
1085 # @ingroup l1_measurements
1086 def BoundingBox(self, objects):
1087 result = self.GetBoundingBox(objects)
1091 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1094 ## Get measure structure specifying bounding box data of the specified object(s)
1095 # @param objects single source object or list of source objects
1096 # @return Measure structure
1098 # @ingroup l1_measurements
1099 def GetBoundingBox(self, objects):
1100 if isinstance(objects, tuple):
1101 objects = list(objects)
1102 if not isinstance(objects, list):
1106 if isinstance(o, Mesh):
1107 srclist.append(o.mesh)
1108 elif hasattr(o, "_narrow"):
1109 src = o._narrow(SMESH.SMESH_IDSource)
1110 if src: srclist.append(src)
1113 aMeasurements = self.CreateMeasurements()
1114 result = aMeasurements.BoundingBox(srclist)
1115 aMeasurements.UnRegister()
1118 ## Get sum of lengths of all 1D elements in the mesh object.
1119 # @param obj mesh, submesh or group
1120 # @return sum of lengths of all 1D elements
1121 # @ingroup l1_measurements
1122 def GetLength(self, obj):
1123 if isinstance(obj, Mesh): obj = obj.mesh
1124 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1125 aMeasurements = self.CreateMeasurements()
1126 value = aMeasurements.Length(obj)
1127 aMeasurements.UnRegister()
1130 ## Get sum of areas of all 2D elements in the mesh object.
1131 # @param obj mesh, submesh or group
1132 # @return sum of areas of all 2D elements
1133 # @ingroup l1_measurements
1134 def GetArea(self, obj):
1135 if isinstance(obj, Mesh): obj = obj.mesh
1136 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1137 aMeasurements = self.CreateMeasurements()
1138 value = aMeasurements.Area(obj)
1139 aMeasurements.UnRegister()
1142 ## Get sum of volumes of all 3D elements in the mesh object.
1143 # @param obj mesh, submesh or group
1144 # @return sum of volumes of all 3D elements
1145 # @ingroup l1_measurements
1146 def GetVolume(self, obj):
1147 if isinstance(obj, Mesh): obj = obj.mesh
1148 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1149 aMeasurements = self.CreateMeasurements()
1150 value = aMeasurements.Volume(obj)
1151 aMeasurements.UnRegister()
1154 pass # end of class smeshBuilder
1157 #Registering the new proxy for SMESH_Gen
1158 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1160 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1161 # interface to create or load meshes.
1166 # salome.salome_init()
1167 # from salome.smesh import smeshBuilder
1168 # smesh = smeshBuilder.New(salome.myStudy)
1170 # @param study SALOME study, generally obtained by salome.myStudy.
1171 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1172 # @return smeshBuilder instance
1174 def New( study, instance=None):
1176 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1177 interface to create or load meshes.
1181 salome.salome_init()
1182 from salome.smesh import smeshBuilder
1183 smesh = smeshBuilder.New(salome.myStudy)
1186 study SALOME study, generally obtained by salome.myStudy.
1187 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1189 smeshBuilder instance
1197 smeshInst = smeshBuilder()
1198 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1199 smeshInst.init_smesh(study)
1203 # Public class: Mesh
1204 # ==================
1206 ## This class allows defining and managing a mesh.
1207 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1208 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1209 # new nodes and elements and by changing the existing entities), to get information
1210 # about a mesh and to export a mesh into different formats.
1212 __metaclass__ = MeshMeta
1220 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1221 # sets the GUI name of this mesh to \a name.
1222 # @param smeshpyD an instance of smeshBuilder class
1223 # @param geompyD an instance of geomBuilder class
1224 # @param obj Shape to be meshed or SMESH_Mesh object
1225 # @param name Study name of the mesh
1226 # @ingroup l2_construct
1227 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1228 self.smeshpyD=smeshpyD
1229 self.geompyD=geompyD
1234 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1237 # publish geom of mesh (issue 0021122)
1238 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1240 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1241 if studyID != geompyD.myStudyId:
1242 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1245 geo_name = name + " shape"
1247 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1248 geompyD.addToStudy( self.geom, geo_name )
1249 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1251 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1254 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1256 self.smeshpyD.SetName(self.mesh, name)
1258 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1261 self.geom = self.mesh.GetShapeToMesh()
1263 self.editor = self.mesh.GetMeshEditor()
1264 self.functors = [None] * SMESH.FT_Undefined._v
1266 # set self to algoCreator's
1267 for attrName in dir(self):
1268 attr = getattr( self, attrName )
1269 if isinstance( attr, algoCreator ):
1270 setattr( self, attrName, attr.copy( self ))
1275 ## Destructor. Clean-up resources
1278 #self.mesh.UnRegister()
1282 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1283 # @param theMesh a SMESH_Mesh object
1284 # @ingroup l2_construct
1285 def SetMesh(self, theMesh):
1286 # do not call Register() as this prevents mesh servant deletion at closing study
1287 #if self.mesh: self.mesh.UnRegister()
1290 #self.mesh.Register()
1291 self.geom = self.mesh.GetShapeToMesh()
1294 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1295 # @return a SMESH_Mesh object
1296 # @ingroup l2_construct
1300 ## Gets the name of the mesh
1301 # @return the name of the mesh as a string
1302 # @ingroup l2_construct
1304 name = GetName(self.GetMesh())
1307 ## Sets a name to the mesh
1308 # @param name a new name of the mesh
1309 # @ingroup l2_construct
1310 def SetName(self, name):
1311 self.smeshpyD.SetName(self.GetMesh(), name)
1313 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1314 # The subMesh object gives access to the IDs of nodes and elements.
1315 # @param geom a geometrical object (shape)
1316 # @param name a name for the submesh
1317 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1318 # @ingroup l2_submeshes
1319 def GetSubMesh(self, geom, name):
1320 AssureGeomPublished( self, geom, name )
1321 submesh = self.mesh.GetSubMesh( geom, name )
1324 ## Returns the shape associated to the mesh
1325 # @return a GEOM_Object
1326 # @ingroup l2_construct
1330 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1331 # @param geom the shape to be meshed (GEOM_Object)
1332 # @ingroup l2_construct
1333 def SetShape(self, geom):
1334 self.mesh = self.smeshpyD.CreateMesh(geom)
1336 ## Loads mesh from the study after opening the study
1340 ## Returns true if the hypotheses are defined well
1341 # @param theSubObject a sub-shape of a mesh shape
1342 # @return True or False
1343 # @ingroup l2_construct
1344 def IsReadyToCompute(self, theSubObject):
1345 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1347 ## Returns errors of hypotheses definition.
1348 # The list of errors is empty if everything is OK.
1349 # @param theSubObject a sub-shape of a mesh shape
1350 # @return a list of errors
1351 # @ingroup l2_construct
1352 def GetAlgoState(self, theSubObject):
1353 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1355 ## Returns a geometrical object on which the given element was built.
1356 # The returned geometrical object, if not nil, is either found in the
1357 # study or published by this method with the given name
1358 # @param theElementID the id of the mesh element
1359 # @param theGeomName the user-defined name of the geometrical object
1360 # @return GEOM::GEOM_Object instance
1361 # @ingroup l2_construct
1362 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1363 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1365 ## Returns the mesh dimension depending on the dimension of the underlying shape
1366 # or, if the mesh is not based on any shape, basing on deimension of elements
1367 # @return mesh dimension as an integer value [0,3]
1368 # @ingroup l1_auxiliary
1369 def MeshDimension(self):
1370 if self.mesh.HasShapeToMesh():
1371 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1372 if len( shells ) > 0 :
1374 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1376 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1381 if self.NbVolumes() > 0: return 3
1382 if self.NbFaces() > 0: return 2
1383 if self.NbEdges() > 0: return 1
1386 ## Evaluates size of prospective mesh on a shape
1387 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1388 # To know predicted number of e.g. edges, inquire it this way
1389 # Evaluate()[ EnumToLong( Entity_Edge )]
1390 def Evaluate(self, geom=0):
1391 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1393 geom = self.mesh.GetShapeToMesh()
1396 return self.smeshpyD.Evaluate(self.mesh, geom)
1399 ## Computes the mesh and returns the status of the computation
1400 # @param geom geomtrical shape on which mesh data should be computed
1401 # @param discardModifs if True and the mesh has been edited since
1402 # a last total re-compute and that may prevent successful partial re-compute,
1403 # then the mesh is cleaned before Compute()
1404 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1405 # @return True or False
1406 # @ingroup l2_construct
1407 def Compute(self, geom=0, discardModifs=False, refresh=False):
1408 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1410 geom = self.mesh.GetShapeToMesh()
1415 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1417 ok = self.smeshpyD.Compute(self.mesh, geom)
1418 except SALOME.SALOME_Exception, ex:
1419 print "Mesh computation failed, exception caught:"
1420 print " ", ex.details.text
1423 print "Mesh computation failed, exception caught:"
1424 traceback.print_exc()
1428 # Treat compute errors
1429 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1431 for err in computeErrors:
1432 if self.mesh.HasShapeToMesh():
1433 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1435 stdErrors = ["OK", #COMPERR_OK
1436 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1437 "std::exception", #COMPERR_STD_EXCEPTION
1438 "OCC exception", #COMPERR_OCC_EXCEPTION
1439 "..", #COMPERR_SLM_EXCEPTION
1440 "Unknown exception", #COMPERR_EXCEPTION
1441 "Memory allocation problem", #COMPERR_MEMORY_PB
1442 "Algorithm failed", #COMPERR_ALGO_FAILED
1443 "Unexpected geometry", #COMPERR_BAD_SHAPE
1444 "Warning", #COMPERR_WARNING
1445 "Computation cancelled",#COMPERR_CANCELED
1446 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1448 if err.code < len(stdErrors): errText = stdErrors[err.code]
1450 errText = "code %s" % -err.code
1451 if errText: errText += ". "
1452 errText += err.comment
1453 if allReasons != "":allReasons += "\n"
1455 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1457 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1461 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1463 if err.isGlobalAlgo:
1471 reason = '%s %sD algorithm is missing' % (glob, dim)
1472 elif err.state == HYP_MISSING:
1473 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1474 % (glob, dim, name, dim))
1475 elif err.state == HYP_NOTCONFORM:
1476 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1477 elif err.state == HYP_BAD_PARAMETER:
1478 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1479 % ( glob, dim, name ))
1480 elif err.state == HYP_BAD_GEOMETRY:
1481 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1482 'geometry' % ( glob, dim, name ))
1483 elif err.state == HYP_HIDDEN_ALGO:
1484 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1485 'algorithm of upper dimension generating %sD mesh'
1486 % ( glob, dim, name, glob, dim ))
1488 reason = ("For unknown reason. "
1489 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1491 if allReasons != "":allReasons += "\n"
1492 allReasons += "- " + reason
1494 if not ok or allReasons != "":
1495 msg = '"' + GetName(self.mesh) + '"'
1496 if ok: msg += " has been computed with warnings"
1497 else: msg += " has not been computed"
1498 if allReasons != "": msg += ":"
1503 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1504 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1505 smeshgui = salome.ImportComponentGUI("SMESH")
1506 smeshgui.Init(self.mesh.GetStudyId())
1507 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1508 if refresh: salome.sg.updateObjBrowser(1)
1512 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1513 def GetComputeErrors(self, shape=0 ):
1515 shape = self.mesh.GetShapeToMesh()
1516 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1518 ## Return a name of a sub-shape by its ID
1519 # @param subShapeID a unique ID of a sub-shape
1520 # @return a string describing the sub-shape; possible variants:
1521 # - "Face_12" (published sub-shape)
1522 # - FACE #3 (not published sub-shape)
1523 # - sub-shape #3 (invalid sub-shape ID)
1524 # - #3 (error in this function)
1525 def GetSubShapeName(self, subShapeID ):
1526 if not self.mesh.HasShapeToMesh():
1530 mainIOR = salome.orb.object_to_string( self.GetShape() )
1531 for sname in salome.myStudyManager.GetOpenStudies():
1532 s = salome.myStudyManager.GetStudyByName(sname)
1534 mainSO = s.FindObjectIOR(mainIOR)
1535 if not mainSO: continue
1537 shapeText = '"%s"' % mainSO.GetName()
1538 subIt = s.NewChildIterator(mainSO)
1540 subSO = subIt.Value()
1542 obj = subSO.GetObject()
1543 if not obj: continue
1544 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1547 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1550 if ids == subShapeID:
1551 shapeText = '"%s"' % subSO.GetName()
1554 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1556 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1558 shapeText = 'sub-shape #%s' % (subShapeID)
1560 shapeText = "#%s" % (subShapeID)
1563 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1564 # error of an algorithm
1565 # @param publish if @c True, the returned groups will be published in the study
1566 # @return a list of GEOM groups each named after a failed algorithm
1567 def GetFailedShapes(self, publish=False):
1570 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1571 for err in computeErrors:
1572 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1573 if not shape: continue
1574 if err.algoName in algo2shapes:
1575 algo2shapes[ err.algoName ].append( shape )
1577 algo2shapes[ err.algoName ] = [ shape ]
1581 for algoName, shapes in algo2shapes.items():
1583 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1584 otherTypeShapes = []
1586 group = self.geompyD.CreateGroup( self.geom, groupType )
1587 for shape in shapes:
1588 if shape.GetShapeType() == shapes[0].GetShapeType():
1589 sameTypeShapes.append( shape )
1591 otherTypeShapes.append( shape )
1592 self.geompyD.UnionList( group, sameTypeShapes )
1594 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1596 group.SetName( algoName )
1597 groups.append( group )
1598 shapes = otherTypeShapes
1601 for group in groups:
1602 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1605 ## Return sub-mesh objects list in meshing order
1606 # @return list of lists of sub-meshes
1607 # @ingroup l2_construct
1608 def GetMeshOrder(self):
1609 return self.mesh.GetMeshOrder()
1611 ## Set order in which concurrent sub-meshes sould be meshed
1612 # @param submeshes list of lists of sub-meshes
1613 # @ingroup l2_construct
1614 def SetMeshOrder(self, submeshes):
1615 return self.mesh.SetMeshOrder(submeshes)
1617 ## Removes all nodes and elements
1618 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1619 # @ingroup l2_construct
1620 def Clear(self, refresh=False):
1622 if ( salome.sg.hasDesktop() and
1623 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1624 smeshgui = salome.ImportComponentGUI("SMESH")
1625 smeshgui.Init(self.mesh.GetStudyId())
1626 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1627 if refresh: salome.sg.updateObjBrowser(1)
1629 ## Removes all nodes and elements of indicated shape
1630 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1631 # @param geomId the ID of a sub-shape to remove elements on
1632 # @ingroup l2_construct
1633 def ClearSubMesh(self, geomId, refresh=False):
1634 self.mesh.ClearSubMesh(geomId)
1635 if salome.sg.hasDesktop():
1636 smeshgui = salome.ImportComponentGUI("SMESH")
1637 smeshgui.Init(self.mesh.GetStudyId())
1638 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1639 if refresh: salome.sg.updateObjBrowser(1)
1641 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1642 # @param fineness [0.0,1.0] defines mesh fineness
1643 # @return True or False
1644 # @ingroup l3_algos_basic
1645 def AutomaticTetrahedralization(self, fineness=0):
1646 dim = self.MeshDimension()
1648 self.RemoveGlobalHypotheses()
1649 self.Segment().AutomaticLength(fineness)
1651 self.Triangle().LengthFromEdges()
1656 return self.Compute()
1658 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1659 # @param fineness [0.0, 1.0] defines mesh fineness
1660 # @return True or False
1661 # @ingroup l3_algos_basic
1662 def AutomaticHexahedralization(self, fineness=0):
1663 dim = self.MeshDimension()
1664 # assign the hypotheses
1665 self.RemoveGlobalHypotheses()
1666 self.Segment().AutomaticLength(fineness)
1673 return self.Compute()
1675 ## Assigns a hypothesis
1676 # @param hyp a hypothesis to assign
1677 # @param geom a subhape of mesh geometry
1678 # @return SMESH.Hypothesis_Status
1679 # @ingroup l2_hypotheses
1680 def AddHypothesis(self, hyp, geom=0):
1681 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1682 hyp, geom = geom, hyp
1683 if isinstance( hyp, Mesh_Algorithm ):
1684 hyp = hyp.GetAlgorithm()
1689 geom = self.mesh.GetShapeToMesh()
1692 if self.mesh.HasShapeToMesh():
1693 hyp_type = hyp.GetName()
1694 lib_name = hyp.GetLibName()
1695 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1696 # if checkAll and geom:
1697 # checkAll = geom.GetType() == 37
1699 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1701 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1702 status = self.mesh.AddHypothesis(geom, hyp)
1704 status = HYP_BAD_GEOMETRY,""
1705 hyp_name = GetName( hyp )
1708 geom_name = geom.GetName()
1709 isAlgo = hyp._narrow( SMESH_Algo )
1710 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1713 ## Return True if an algorithm of hypothesis is assigned to a given shape
1714 # @param hyp a hypothesis to check
1715 # @param geom a subhape of mesh geometry
1716 # @return True of False
1717 # @ingroup l2_hypotheses
1718 def IsUsedHypothesis(self, hyp, geom):
1719 if not hyp: # or not geom
1721 if isinstance( hyp, Mesh_Algorithm ):
1722 hyp = hyp.GetAlgorithm()
1724 hyps = self.GetHypothesisList(geom)
1726 if h.GetId() == hyp.GetId():
1730 ## Unassigns a hypothesis
1731 # @param hyp a hypothesis to unassign
1732 # @param geom a sub-shape of mesh geometry
1733 # @return SMESH.Hypothesis_Status
1734 # @ingroup l2_hypotheses
1735 def RemoveHypothesis(self, hyp, geom=0):
1738 if isinstance( hyp, Mesh_Algorithm ):
1739 hyp = hyp.GetAlgorithm()
1745 if self.IsUsedHypothesis( hyp, shape ):
1746 return self.mesh.RemoveHypothesis( shape, hyp )
1747 hypName = GetName( hyp )
1748 geoName = GetName( shape )
1749 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1752 ## Gets the list of hypotheses added on a geometry
1753 # @param geom a sub-shape of mesh geometry
1754 # @return the sequence of SMESH_Hypothesis
1755 # @ingroup l2_hypotheses
1756 def GetHypothesisList(self, geom):
1757 return self.mesh.GetHypothesisList( geom )
1759 ## Removes all global hypotheses
1760 # @ingroup l2_hypotheses
1761 def RemoveGlobalHypotheses(self):
1762 current_hyps = self.mesh.GetHypothesisList( self.geom )
1763 for hyp in current_hyps:
1764 self.mesh.RemoveHypothesis( self.geom, hyp )
1768 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1769 ## allowing to overwrite the file if it exists or add the exported data to its contents
1770 # @param f is the file name
1771 # @param auto_groups boolean parameter for creating/not creating
1772 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1773 # the typical use is auto_groups=false.
1774 # @param version MED format version(MED_V2_1 or MED_V2_2)
1775 # @param overwrite boolean parameter for overwriting/not overwriting the file
1776 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1777 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1778 # - 1D if all mesh nodes lie on OX coordinate axis, or
1779 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1780 # - 3D in the rest cases.
1781 # If @a autoDimension is @c False, the space dimension is always 3.
1782 # @param fields : list of GEOM fields defined on the shape to mesh.
1783 # @param geomAssocFields : each character of this string means a need to export a
1784 # corresponding field; correspondence between fields and characters is following:
1785 # - 'v' stands for _vertices_ field;
1786 # - 'e' stands for _edges_ field;
1787 # - 'f' stands for _faces_ field;
1788 # - 's' stands for _solids_ field.
1789 # @ingroup l2_impexp
1790 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1791 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1792 if meshPart or fields or geomAssocFields:
1793 unRegister = genObjUnRegister()
1794 if isinstance( meshPart, list ):
1795 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1796 unRegister.set( meshPart )
1797 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1798 fields, geomAssocFields)
1800 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1802 ## Exports the mesh in a file in SAUV format
1803 # @param f is the file name
1804 # @param auto_groups boolean parameter for creating/not creating
1805 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1806 # the typical use is auto_groups=false.
1807 # @ingroup l2_impexp
1808 def ExportSAUV(self, f, auto_groups=0):
1809 self.mesh.ExportSAUV(f, auto_groups)
1811 ## Exports the mesh in a file in DAT format
1812 # @param f the file name
1813 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1814 # @ingroup l2_impexp
1815 def ExportDAT(self, f, meshPart=None):
1817 unRegister = genObjUnRegister()
1818 if isinstance( meshPart, list ):
1819 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1820 unRegister.set( meshPart )
1821 self.mesh.ExportPartToDAT( meshPart, f )
1823 self.mesh.ExportDAT(f)
1825 ## Exports the mesh in a file in UNV format
1826 # @param f the file name
1827 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1828 # @ingroup l2_impexp
1829 def ExportUNV(self, f, meshPart=None):
1831 unRegister = genObjUnRegister()
1832 if isinstance( meshPart, list ):
1833 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1834 unRegister.set( meshPart )
1835 self.mesh.ExportPartToUNV( meshPart, f )
1837 self.mesh.ExportUNV(f)
1839 ## Export the mesh in a file in STL format
1840 # @param f the file name
1841 # @param ascii defines the file encoding
1842 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1843 # @ingroup l2_impexp
1844 def ExportSTL(self, f, ascii=1, meshPart=None):
1846 unRegister = genObjUnRegister()
1847 if isinstance( meshPart, list ):
1848 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1849 unRegister.set( meshPart )
1850 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1852 self.mesh.ExportSTL(f, ascii)
1854 ## Exports the mesh in a file in CGNS format
1855 # @param f is the file name
1856 # @param overwrite boolean parameter for overwriting/not overwriting the file
1857 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1858 # @ingroup l2_impexp
1859 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1860 unRegister = genObjUnRegister()
1861 if isinstance( meshPart, list ):
1862 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1863 unRegister.set( meshPart )
1864 if isinstance( meshPart, Mesh ):
1865 meshPart = meshPart.mesh
1867 meshPart = self.mesh
1868 self.mesh.ExportCGNS(meshPart, f, overwrite)
1870 ## Exports the mesh in a file in GMF format.
1871 # GMF files must have .mesh extension for the ASCII format and .meshb for
1872 # the bynary format. Other extensions are not allowed.
1873 # @param f is the file name
1874 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1875 # @ingroup l2_impexp
1876 def ExportGMF(self, f, meshPart=None):
1877 unRegister = genObjUnRegister()
1878 if isinstance( meshPart, list ):
1879 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1880 unRegister.set( meshPart )
1881 if isinstance( meshPart, Mesh ):
1882 meshPart = meshPart.mesh
1884 meshPart = self.mesh
1885 self.mesh.ExportGMF(meshPart, f, True)
1887 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1888 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1889 ## allowing to overwrite the file if it exists or add the exported data to its contents
1890 # @param f the file name
1891 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1892 # @param opt boolean parameter for creating/not creating
1893 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1894 # @param overwrite boolean parameter for overwriting/not overwriting the file
1895 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1896 # - 1D if all mesh nodes lie on OX coordinate axis, or
1897 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1898 # - 3D in the rest cases.
1900 # If @a autoDimension is @c False, the space dimension is always 3.
1901 # @ingroup l2_impexp
1902 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1903 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1905 # Operations with groups:
1906 # ----------------------
1908 ## Creates an empty mesh group
1909 # @param elementType the type of elements in the group; either of
1910 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1911 # @param name the name of the mesh group
1912 # @return SMESH_Group
1913 # @ingroup l2_grps_create
1914 def CreateEmptyGroup(self, elementType, name):
1915 return self.mesh.CreateGroup(elementType, name)
1917 ## Creates a mesh group based on the geometric object \a grp
1918 # and gives a \a name, \n if this parameter is not defined
1919 # the name is the same as the geometric group name \n
1920 # Note: Works like GroupOnGeom().
1921 # @param grp a geometric group, a vertex, an edge, a face or a solid
1922 # @param name the name of the mesh group
1923 # @return SMESH_GroupOnGeom
1924 # @ingroup l2_grps_create
1925 def Group(self, grp, name=""):
1926 return self.GroupOnGeom(grp, name)
1928 ## Creates a mesh group based on the geometrical object \a grp
1929 # and gives a \a name, \n if this parameter is not defined
1930 # the name is the same as the geometrical group name
1931 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1932 # @param name the name of the mesh group
1933 # @param typ the type of elements in the group; either of
1934 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1935 # automatically detected by the type of the geometry
1936 # @return SMESH_GroupOnGeom
1937 # @ingroup l2_grps_create
1938 def GroupOnGeom(self, grp, name="", typ=None):
1939 AssureGeomPublished( self, grp, name )
1941 name = grp.GetName()
1943 typ = self._groupTypeFromShape( grp )
1944 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1946 ## Pivate method to get a type of group on geometry
1947 def _groupTypeFromShape( self, shape ):
1948 tgeo = str(shape.GetShapeType())
1949 if tgeo == "VERTEX":
1951 elif tgeo == "EDGE":
1953 elif tgeo == "FACE" or tgeo == "SHELL":
1955 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1957 elif tgeo == "COMPOUND":
1958 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1960 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1961 return self._groupTypeFromShape( sub[0] )
1964 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1967 ## Creates a mesh group with given \a name based on the \a filter which
1968 ## is a special type of group dynamically updating it's contents during
1969 ## mesh modification
1970 # @param typ the type of elements in the group; either of
1971 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1972 # @param name the name of the mesh group
1973 # @param filter the filter defining group contents
1974 # @return SMESH_GroupOnFilter
1975 # @ingroup l2_grps_create
1976 def GroupOnFilter(self, typ, name, filter):
1977 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1979 ## Creates a mesh group by the given ids of elements
1980 # @param groupName the name of the mesh group
1981 # @param elementType the type of elements in the group; either of
1982 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1983 # @param elemIDs either the list of ids, group, sub-mesh, or filter
1984 # @return SMESH_Group
1985 # @ingroup l2_grps_create
1986 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1987 group = self.mesh.CreateGroup(elementType, groupName)
1988 if hasattr( elemIDs, "GetIDs" ):
1989 if hasattr( elemIDs, "SetMesh" ):
1990 elemIDs.SetMesh( self.GetMesh() )
1991 group.AddFrom( elemIDs )
1996 ## Creates a mesh group by the given conditions
1997 # @param groupName the name of the mesh group
1998 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1999 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2000 # Type SMESH.FunctorType._items in the Python Console to see all values.
2001 # Note that the items starting from FT_LessThan are not suitable for CritType.
2002 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2003 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2004 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2005 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2006 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2007 # @return SMESH_GroupOnFilter
2008 # @ingroup l2_grps_create
2012 CritType=FT_Undefined,
2015 UnaryOp=FT_Undefined,
2017 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2018 group = self.MakeGroupByCriterion(groupName, aCriterion)
2021 ## Creates a mesh group by the given criterion
2022 # @param groupName the name of the mesh group
2023 # @param Criterion the instance of Criterion class
2024 # @return SMESH_GroupOnFilter
2025 # @ingroup l2_grps_create
2026 def MakeGroupByCriterion(self, groupName, Criterion):
2027 return self.MakeGroupByCriteria( groupName, [Criterion] )
2029 ## Creates a mesh group by the given criteria (list of criteria)
2030 # @param groupName the name of the mesh group
2031 # @param theCriteria the list of criteria
2032 # @param binOp binary operator used when binary operator of criteria is undefined
2033 # @return SMESH_GroupOnFilter
2034 # @ingroup l2_grps_create
2035 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2036 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2037 group = self.MakeGroupByFilter(groupName, aFilter)
2040 ## Creates a mesh group by the given filter
2041 # @param groupName the name of the mesh group
2042 # @param theFilter the instance of Filter class
2043 # @return SMESH_GroupOnFilter
2044 # @ingroup l2_grps_create
2045 def MakeGroupByFilter(self, groupName, theFilter):
2046 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2047 #theFilter.SetMesh( self.mesh )
2048 #group.AddFrom( theFilter )
2049 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2053 # @ingroup l2_grps_delete
2054 def RemoveGroup(self, group):
2055 self.mesh.RemoveGroup(group)
2057 ## Removes a group with its contents
2058 # @ingroup l2_grps_delete
2059 def RemoveGroupWithContents(self, group):
2060 self.mesh.RemoveGroupWithContents(group)
2062 ## Gets the list of groups existing in the mesh in the order
2063 # of creation (starting from the oldest one)
2064 # @param elemType type of elements the groups contain; either of
2065 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2066 # by default groups of elements of all types are returned
2067 # @return a sequence of SMESH_GroupBase
2068 # @ingroup l2_grps_create
2069 def GetGroups(self, elemType = SMESH.ALL):
2070 groups = self.mesh.GetGroups()
2071 if elemType == SMESH.ALL:
2075 if g.GetType() == elemType:
2076 typedGroups.append( g )
2081 ## Gets the number of groups existing in the mesh
2082 # @return the quantity of groups as an integer value
2083 # @ingroup l2_grps_create
2085 return self.mesh.NbGroups()
2087 ## Gets the list of names of groups existing in the mesh
2088 # @return list of strings
2089 # @ingroup l2_grps_create
2090 def GetGroupNames(self):
2091 groups = self.GetGroups()
2093 for group in groups:
2094 names.append(group.GetName())
2097 ## Finds groups by name and type
2098 # @param name name of the group of interest
2099 # @param elemType type of elements the groups contain; either of
2100 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2101 # by default one group of any type of elements is returned
2102 # if elemType == SMESH.ALL then all groups of any type are returned
2103 # @return a list of SMESH_GroupBase's
2104 # @ingroup l2_grps_create
2105 def GetGroupByName(self, name, elemType = None):
2107 for group in self.GetGroups():
2108 if group.GetName() == name:
2109 if elemType is None:
2111 if ( elemType == SMESH.ALL or
2112 group.GetType() == elemType ):
2113 groups.append( group )
2116 ## Produces a union of two groups.
2117 # A new group is created. All mesh elements that are
2118 # present in the initial groups are added to the new one
2119 # @return an instance of SMESH_Group
2120 # @ingroup l2_grps_operon
2121 def UnionGroups(self, group1, group2, name):
2122 return self.mesh.UnionGroups(group1, group2, name)
2124 ## Produces a union list of groups.
2125 # New group is created. All mesh elements that are present in
2126 # initial groups are added to the new one
2127 # @return an instance of SMESH_Group
2128 # @ingroup l2_grps_operon
2129 def UnionListOfGroups(self, groups, name):
2130 return self.mesh.UnionListOfGroups(groups, name)
2132 ## Prodices an intersection of two groups.
2133 # A new group is created. All mesh elements that are common
2134 # for the two initial groups are added to the new one.
2135 # @return an instance of SMESH_Group
2136 # @ingroup l2_grps_operon
2137 def IntersectGroups(self, group1, group2, name):
2138 return self.mesh.IntersectGroups(group1, group2, name)
2140 ## Produces an intersection of groups.
2141 # New group is created. All mesh elements that are present in all
2142 # initial groups simultaneously are added to the new one
2143 # @return an instance of SMESH_Group
2144 # @ingroup l2_grps_operon
2145 def IntersectListOfGroups(self, groups, name):
2146 return self.mesh.IntersectListOfGroups(groups, name)
2148 ## Produces a cut of two groups.
2149 # A new group is created. All mesh elements that are present in
2150 # the main group but are not present in the tool group are added to the new one
2151 # @return an instance of SMESH_Group
2152 # @ingroup l2_grps_operon
2153 def CutGroups(self, main_group, tool_group, name):
2154 return self.mesh.CutGroups(main_group, tool_group, name)
2156 ## Produces a cut of groups.
2157 # A new group is created. All mesh elements that are present in main groups
2158 # but do not present in tool groups are added to the new one
2159 # @return an instance of SMESH_Group
2160 # @ingroup l2_grps_operon
2161 def CutListOfGroups(self, main_groups, tool_groups, name):
2162 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2165 # Create a standalone group of entities basing on nodes of other groups.
2166 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2167 # \param elemType - a type of elements to include to the new group; either of
2168 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2169 # \param name - a name of the new group.
2170 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2171 # basing on number of element nodes common with reference \a groups.
2172 # Meaning of possible values are:
2173 # - SMESH.ALL_NODES - include if all nodes are common,
2174 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2175 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2176 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2177 # \param underlyingOnly - if \c True (default), an element is included to the
2178 # new group provided that it is based on nodes of an element of \a groups;
2179 # in this case the reference \a groups are supposed to be of higher dimension
2180 # than \a elemType, which can be useful for example to get all faces lying on
2181 # volumes of the reference \a groups.
2182 # @return an instance of SMESH_Group
2183 # @ingroup l2_grps_operon
2184 def CreateDimGroup(self, groups, elemType, name,
2185 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2186 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2188 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2191 ## Convert group on geom into standalone group
2192 # @ingroup l2_grps_edit
2193 def ConvertToStandalone(self, group):
2194 return self.mesh.ConvertToStandalone(group)
2196 # Get some info about mesh:
2197 # ------------------------
2199 ## Returns the log of nodes and elements added or removed
2200 # since the previous clear of the log.
2201 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2202 # @return list of log_block structures:
2207 # @ingroup l1_auxiliary
2208 def GetLog(self, clearAfterGet):
2209 return self.mesh.GetLog(clearAfterGet)
2211 ## Clears the log of nodes and elements added or removed since the previous
2212 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2213 # @ingroup l1_auxiliary
2215 self.mesh.ClearLog()
2217 ## Toggles auto color mode on the object.
2218 # @param theAutoColor the flag which toggles auto color mode.
2219 # @ingroup l1_auxiliary
2220 def SetAutoColor(self, theAutoColor):
2221 self.mesh.SetAutoColor(theAutoColor)
2223 ## Gets flag of object auto color mode.
2224 # @return True or False
2225 # @ingroup l1_auxiliary
2226 def GetAutoColor(self):
2227 return self.mesh.GetAutoColor()
2229 ## Gets the internal ID
2230 # @return integer value, which is the internal Id of the mesh
2231 # @ingroup l1_auxiliary
2233 return self.mesh.GetId()
2236 # @return integer value, which is the study Id of the mesh
2237 # @ingroup l1_auxiliary
2238 def GetStudyId(self):
2239 return self.mesh.GetStudyId()
2241 ## Checks the group names for duplications.
2242 # Consider the maximum group name length stored in MED file.
2243 # @return True or False
2244 # @ingroup l1_auxiliary
2245 def HasDuplicatedGroupNamesMED(self):
2246 return self.mesh.HasDuplicatedGroupNamesMED()
2248 ## Obtains the mesh editor tool
2249 # @return an instance of SMESH_MeshEditor
2250 # @ingroup l1_modifying
2251 def GetMeshEditor(self):
2254 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2255 # can be passed as argument to a method accepting mesh, group or sub-mesh
2256 # @param ids list of IDs
2257 # @param elemType type of elements; this parameter is used to distinguish
2258 # IDs of nodes from IDs of elements; by default ids are treated as
2259 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2260 # @return an instance of SMESH_IDSource
2261 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2262 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2263 # mesh.DoSomething( idSrc )
2264 # idSrc.UnRegister()
2265 # @ingroup l1_auxiliary
2266 def GetIDSource(self, ids, elemType = SMESH.ALL):
2267 if isinstance( ids, int ):
2269 return self.editor.MakeIDSource(ids, elemType)
2272 # Get informations about mesh contents:
2273 # ------------------------------------
2275 ## Gets the mesh stattistic
2276 # @return dictionary type element - count of elements
2277 # @ingroup l1_meshinfo
2278 def GetMeshInfo(self, obj = None):
2279 if not obj: obj = self.mesh
2280 return self.smeshpyD.GetMeshInfo(obj)
2282 ## Returns the number of nodes in the mesh
2283 # @return an integer value
2284 # @ingroup l1_meshinfo
2286 return self.mesh.NbNodes()
2288 ## Returns the number of elements in the mesh
2289 # @return an integer value
2290 # @ingroup l1_meshinfo
2291 def NbElements(self):
2292 return self.mesh.NbElements()
2294 ## Returns the number of 0d elements in the mesh
2295 # @return an integer value
2296 # @ingroup l1_meshinfo
2297 def Nb0DElements(self):
2298 return self.mesh.Nb0DElements()
2300 ## Returns the number of ball discrete elements in the mesh
2301 # @return an integer value
2302 # @ingroup l1_meshinfo
2304 return self.mesh.NbBalls()
2306 ## Returns the number of edges in the mesh
2307 # @return an integer value
2308 # @ingroup l1_meshinfo
2310 return self.mesh.NbEdges()
2312 ## Returns the number of edges with the given order in the mesh
2313 # @param elementOrder the order of elements:
2314 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2315 # @return an integer value
2316 # @ingroup l1_meshinfo
2317 def NbEdgesOfOrder(self, elementOrder):
2318 return self.mesh.NbEdgesOfOrder(elementOrder)
2320 ## Returns the number of faces in the mesh
2321 # @return an integer value
2322 # @ingroup l1_meshinfo
2324 return self.mesh.NbFaces()
2326 ## Returns the number of faces with the given order in the mesh
2327 # @param elementOrder the order of elements:
2328 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2329 # @return an integer value
2330 # @ingroup l1_meshinfo
2331 def NbFacesOfOrder(self, elementOrder):
2332 return self.mesh.NbFacesOfOrder(elementOrder)
2334 ## Returns the number of triangles in the mesh
2335 # @return an integer value
2336 # @ingroup l1_meshinfo
2337 def NbTriangles(self):
2338 return self.mesh.NbTriangles()
2340 ## Returns the number of triangles with the given order in the mesh
2341 # @param elementOrder is the order of elements:
2342 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2343 # @return an integer value
2344 # @ingroup l1_meshinfo
2345 def NbTrianglesOfOrder(self, elementOrder):
2346 return self.mesh.NbTrianglesOfOrder(elementOrder)
2348 ## Returns the number of biquadratic triangles in the mesh
2349 # @return an integer value
2350 # @ingroup l1_meshinfo
2351 def NbBiQuadTriangles(self):
2352 return self.mesh.NbBiQuadTriangles()
2354 ## Returns the number of quadrangles in the mesh
2355 # @return an integer value
2356 # @ingroup l1_meshinfo
2357 def NbQuadrangles(self):
2358 return self.mesh.NbQuadrangles()
2360 ## Returns the number of quadrangles with the given order in the mesh
2361 # @param elementOrder the order of elements:
2362 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2363 # @return an integer value
2364 # @ingroup l1_meshinfo
2365 def NbQuadranglesOfOrder(self, elementOrder):
2366 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2368 ## Returns the number of biquadratic quadrangles in the mesh
2369 # @return an integer value
2370 # @ingroup l1_meshinfo
2371 def NbBiQuadQuadrangles(self):
2372 return self.mesh.NbBiQuadQuadrangles()
2374 ## Returns the number of polygons of given order in the mesh
2375 # @param elementOrder the order of elements:
2376 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2377 # @return an integer value
2378 # @ingroup l1_meshinfo
2379 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2380 return self.mesh.NbPolygonsOfOrder(elementOrder)
2382 ## Returns the number of volumes in the mesh
2383 # @return an integer value
2384 # @ingroup l1_meshinfo
2385 def NbVolumes(self):
2386 return self.mesh.NbVolumes()
2388 ## Returns the number of volumes with the given order in the mesh
2389 # @param elementOrder the order of elements:
2390 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2391 # @return an integer value
2392 # @ingroup l1_meshinfo
2393 def NbVolumesOfOrder(self, elementOrder):
2394 return self.mesh.NbVolumesOfOrder(elementOrder)
2396 ## Returns the number of tetrahedrons in the mesh
2397 # @return an integer value
2398 # @ingroup l1_meshinfo
2400 return self.mesh.NbTetras()
2402 ## Returns the number of tetrahedrons with the given order in the mesh
2403 # @param elementOrder the order of elements:
2404 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2405 # @return an integer value
2406 # @ingroup l1_meshinfo
2407 def NbTetrasOfOrder(self, elementOrder):
2408 return self.mesh.NbTetrasOfOrder(elementOrder)
2410 ## Returns the number of hexahedrons in the mesh
2411 # @return an integer value
2412 # @ingroup l1_meshinfo
2414 return self.mesh.NbHexas()
2416 ## Returns the number of hexahedrons with the given order in the mesh
2417 # @param elementOrder the order of elements:
2418 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2419 # @return an integer value
2420 # @ingroup l1_meshinfo
2421 def NbHexasOfOrder(self, elementOrder):
2422 return self.mesh.NbHexasOfOrder(elementOrder)
2424 ## Returns the number of triquadratic hexahedrons in the mesh
2425 # @return an integer value
2426 # @ingroup l1_meshinfo
2427 def NbTriQuadraticHexas(self):
2428 return self.mesh.NbTriQuadraticHexas()
2430 ## Returns the number of pyramids in the mesh
2431 # @return an integer value
2432 # @ingroup l1_meshinfo
2433 def NbPyramids(self):
2434 return self.mesh.NbPyramids()
2436 ## Returns the number of pyramids with the given order in the mesh
2437 # @param elementOrder the order of elements:
2438 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2439 # @return an integer value
2440 # @ingroup l1_meshinfo
2441 def NbPyramidsOfOrder(self, elementOrder):
2442 return self.mesh.NbPyramidsOfOrder(elementOrder)
2444 ## Returns the number of prisms in the mesh
2445 # @return an integer value
2446 # @ingroup l1_meshinfo
2448 return self.mesh.NbPrisms()
2450 ## Returns the number of prisms with the given order in the mesh
2451 # @param elementOrder the order of elements:
2452 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2455 def NbPrismsOfOrder(self, elementOrder):
2456 return self.mesh.NbPrismsOfOrder(elementOrder)
2458 ## Returns the number of hexagonal prisms in the mesh
2459 # @return an integer value
2460 # @ingroup l1_meshinfo
2461 def NbHexagonalPrisms(self):
2462 return self.mesh.NbHexagonalPrisms()
2464 ## Returns the number of polyhedrons in the mesh
2465 # @return an integer value
2466 # @ingroup l1_meshinfo
2467 def NbPolyhedrons(self):
2468 return self.mesh.NbPolyhedrons()
2470 ## Returns the number of submeshes in the mesh
2471 # @return an integer value
2472 # @ingroup l1_meshinfo
2473 def NbSubMesh(self):
2474 return self.mesh.NbSubMesh()
2476 ## Returns the list of mesh elements IDs
2477 # @return the list of integer values
2478 # @ingroup l1_meshinfo
2479 def GetElementsId(self):
2480 return self.mesh.GetElementsId()
2482 ## Returns the list of IDs of mesh elements with the given type
2483 # @param elementType the required type of elements, either of
2484 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2485 # @return list of integer values
2486 # @ingroup l1_meshinfo
2487 def GetElementsByType(self, elementType):
2488 return self.mesh.GetElementsByType(elementType)
2490 ## Returns the list of mesh nodes IDs
2491 # @return the list of integer values
2492 # @ingroup l1_meshinfo
2493 def GetNodesId(self):
2494 return self.mesh.GetNodesId()
2496 # Get the information about mesh elements:
2497 # ------------------------------------
2499 ## Returns the type of mesh element
2500 # @return the value from SMESH::ElementType enumeration
2501 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2502 # @ingroup l1_meshinfo
2503 def GetElementType(self, id, iselem=True):
2504 return self.mesh.GetElementType(id, iselem)
2506 ## Returns the geometric type of mesh element
2507 # @return the value from SMESH::EntityType enumeration
2508 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2509 # @ingroup l1_meshinfo
2510 def GetElementGeomType(self, id):
2511 return self.mesh.GetElementGeomType(id)
2513 ## Returns the shape type of mesh element
2514 # @return the value from SMESH::GeometryType enumeration.
2515 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2516 # @ingroup l1_meshinfo
2517 def GetElementShape(self, id):
2518 return self.mesh.GetElementShape(id)
2520 ## Returns the list of submesh elements IDs
2521 # @param Shape a geom object(sub-shape) IOR
2522 # Shape must be the sub-shape of a ShapeToMesh()
2523 # @return the list of integer values
2524 # @ingroup l1_meshinfo
2525 def GetSubMeshElementsId(self, Shape):
2526 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2527 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2530 return self.mesh.GetSubMeshElementsId(ShapeID)
2532 ## Returns the list of submesh nodes IDs
2533 # @param Shape a geom object(sub-shape) IOR
2534 # Shape must be the sub-shape of a ShapeToMesh()
2535 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2536 # @return the list of integer values
2537 # @ingroup l1_meshinfo
2538 def GetSubMeshNodesId(self, Shape, all):
2539 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2540 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2543 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2545 ## Returns type of elements on given shape
2546 # @param Shape a geom object(sub-shape) IOR
2547 # Shape must be a sub-shape of a ShapeToMesh()
2548 # @return element type
2549 # @ingroup l1_meshinfo
2550 def GetSubMeshElementType(self, Shape):
2551 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2552 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2555 return self.mesh.GetSubMeshElementType(ShapeID)
2557 ## Gets the mesh description
2558 # @return string value
2559 # @ingroup l1_meshinfo
2561 return self.mesh.Dump()
2564 # Get the information about nodes and elements of a mesh by its IDs:
2565 # -----------------------------------------------------------
2567 ## Gets XYZ coordinates of a node
2568 # \n If there is no nodes for the given ID - returns an empty list
2569 # @return a list of double precision values
2570 # @ingroup l1_meshinfo
2571 def GetNodeXYZ(self, id):
2572 return self.mesh.GetNodeXYZ(id)
2574 ## Returns list of IDs of inverse elements for the given node
2575 # \n If there is no node for the given ID - returns an empty list
2576 # @return a list of integer values
2577 # @ingroup l1_meshinfo
2578 def GetNodeInverseElements(self, id):
2579 return self.mesh.GetNodeInverseElements(id)
2581 ## @brief Returns the position of a node on the shape
2582 # @return SMESH::NodePosition
2583 # @ingroup l1_meshinfo
2584 def GetNodePosition(self,NodeID):
2585 return self.mesh.GetNodePosition(NodeID)
2587 ## @brief Returns the position of an element on the shape
2588 # @return SMESH::ElementPosition
2589 # @ingroup l1_meshinfo
2590 def GetElementPosition(self,ElemID):
2591 return self.mesh.GetElementPosition(ElemID)
2593 ## Returns the ID of the shape, on which the given node was generated.
2594 # @return an integer value > 0 or -1 if there is no node for the given
2595 # ID or the node is not assigned to any geometry
2596 # @ingroup l1_meshinfo
2597 def GetShapeID(self, id):
2598 return self.mesh.GetShapeID(id)
2600 ## Returns the ID of the shape, on which the given element was generated.
2601 # @return an integer value > 0 or -1 if there is no element for the given
2602 # ID or the element is not assigned to any geometry
2603 # @ingroup l1_meshinfo
2604 def GetShapeIDForElem(self,id):
2605 return self.mesh.GetShapeIDForElem(id)
2607 ## Returns the number of nodes of the given element
2608 # @return an integer value > 0 or -1 if there is no element for the given ID
2609 # @ingroup l1_meshinfo
2610 def GetElemNbNodes(self, id):
2611 return self.mesh.GetElemNbNodes(id)
2613 ## Returns the node ID the given (zero based) index for the given element
2614 # \n If there is no element for the given ID - returns -1
2615 # \n If there is no node for the given index - returns -2
2616 # @return an integer value
2617 # @ingroup l1_meshinfo
2618 def GetElemNode(self, id, index):
2619 return self.mesh.GetElemNode(id, index)
2621 ## Returns the IDs of nodes of the given element
2622 # @return a list of integer values
2623 # @ingroup l1_meshinfo
2624 def GetElemNodes(self, id):
2625 return self.mesh.GetElemNodes(id)
2627 ## Returns true if the given node is the medium node in the given quadratic element
2628 # @ingroup l1_meshinfo
2629 def IsMediumNode(self, elementID, nodeID):
2630 return self.mesh.IsMediumNode(elementID, nodeID)
2632 ## Returns true if the given node is the medium node in one of quadratic elements
2633 # @param nodeID ID of the node
2634 # @param elementType the type of elements to check a state of the node, either of
2635 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2636 # @ingroup l1_meshinfo
2637 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2638 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2640 ## Returns the number of edges for the given element
2641 # @ingroup l1_meshinfo
2642 def ElemNbEdges(self, id):
2643 return self.mesh.ElemNbEdges(id)
2645 ## Returns the number of faces for the given element
2646 # @ingroup l1_meshinfo
2647 def ElemNbFaces(self, id):
2648 return self.mesh.ElemNbFaces(id)
2650 ## Returns nodes of given face (counted from zero) for given volumic element.
2651 # @ingroup l1_meshinfo
2652 def GetElemFaceNodes(self,elemId, faceIndex):
2653 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2655 ## Returns three components of normal of given mesh face
2656 # (or an empty array in KO case)
2657 # @ingroup l1_meshinfo
2658 def GetFaceNormal(self, faceId, normalized=False):
2659 return self.mesh.GetFaceNormal(faceId,normalized)
2661 ## Returns an element based on all given nodes.
2662 # @ingroup l1_meshinfo
2663 def FindElementByNodes(self,nodes):
2664 return self.mesh.FindElementByNodes(nodes)
2666 ## Returns true if the given element is a polygon
2667 # @ingroup l1_meshinfo
2668 def IsPoly(self, id):
2669 return self.mesh.IsPoly(id)
2671 ## Returns true if the given element is quadratic
2672 # @ingroup l1_meshinfo
2673 def IsQuadratic(self, id):
2674 return self.mesh.IsQuadratic(id)
2676 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2677 # @ingroup l1_meshinfo
2678 def GetBallDiameter(self, id):
2679 return self.mesh.GetBallDiameter(id)
2681 ## Returns XYZ coordinates of the barycenter of the given element
2682 # \n If there is no element for the given ID - returns an empty list
2683 # @return a list of three double values
2684 # @ingroup l1_meshinfo
2685 def BaryCenter(self, id):
2686 return self.mesh.BaryCenter(id)
2688 ## Passes mesh elements through the given filter and return IDs of fitting elements
2689 # @param theFilter SMESH_Filter
2690 # @return a list of ids
2691 # @ingroup l1_controls
2692 def GetIdsFromFilter(self, theFilter):
2693 theFilter.SetMesh( self.mesh )
2694 return theFilter.GetIDs()
2696 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2697 # Returns a list of special structures (borders).
2698 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2699 # @ingroup l1_controls
2700 def GetFreeBorders(self):
2701 aFilterMgr = self.smeshpyD.CreateFilterManager()
2702 aPredicate = aFilterMgr.CreateFreeEdges()
2703 aPredicate.SetMesh(self.mesh)
2704 aBorders = aPredicate.GetBorders()
2705 aFilterMgr.UnRegister()
2709 # Get mesh measurements information:
2710 # ------------------------------------
2712 ## Get minimum distance between two nodes, elements or distance to the origin
2713 # @param id1 first node/element id
2714 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2715 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2716 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2717 # @return minimum distance value
2718 # @sa GetMinDistance()
2719 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2720 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2721 return aMeasure.value
2723 ## Get measure structure specifying minimum distance data between two objects
2724 # @param id1 first node/element id
2725 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2726 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2727 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2728 # @return Measure structure
2730 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2732 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2734 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2737 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2739 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2744 aMeasurements = self.smeshpyD.CreateMeasurements()
2745 aMeasure = aMeasurements.MinDistance(id1, id2)
2746 genObjUnRegister([aMeasurements,id1, id2])
2749 ## Get bounding box of the specified object(s)
2750 # @param objects single source object or list of source objects or list of nodes/elements IDs
2751 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2752 # @c False specifies that @a objects are nodes
2753 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2754 # @sa GetBoundingBox()
2755 def BoundingBox(self, objects=None, isElem=False):
2756 result = self.GetBoundingBox(objects, isElem)
2760 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2763 ## Get measure structure specifying bounding box data of the specified object(s)
2764 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2765 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2766 # @c False specifies that @a objects are nodes
2767 # @return Measure structure
2769 def GetBoundingBox(self, IDs=None, isElem=False):
2772 elif isinstance(IDs, tuple):
2774 if not isinstance(IDs, list):
2776 if len(IDs) > 0 and isinstance(IDs[0], int):
2779 unRegister = genObjUnRegister()
2781 if isinstance(o, Mesh):
2782 srclist.append(o.mesh)
2783 elif hasattr(o, "_narrow"):
2784 src = o._narrow(SMESH.SMESH_IDSource)
2785 if src: srclist.append(src)
2787 elif isinstance(o, list):
2789 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2791 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2792 unRegister.set( srclist[-1] )
2795 aMeasurements = self.smeshpyD.CreateMeasurements()
2796 unRegister.set( aMeasurements )
2797 aMeasure = aMeasurements.BoundingBox(srclist)
2800 # Mesh edition (SMESH_MeshEditor functionality):
2801 # ---------------------------------------------
2803 ## Removes the elements from the mesh by ids
2804 # @param IDsOfElements is a list of ids of elements to remove
2805 # @return True or False
2806 # @ingroup l2_modif_del
2807 def RemoveElements(self, IDsOfElements):
2808 return self.editor.RemoveElements(IDsOfElements)
2810 ## Removes nodes from mesh by ids
2811 # @param IDsOfNodes is a list of ids of nodes to remove
2812 # @return True or False
2813 # @ingroup l2_modif_del
2814 def RemoveNodes(self, IDsOfNodes):
2815 return self.editor.RemoveNodes(IDsOfNodes)
2817 ## Removes all orphan (free) nodes from mesh
2818 # @return number of the removed nodes
2819 # @ingroup l2_modif_del
2820 def RemoveOrphanNodes(self):
2821 return self.editor.RemoveOrphanNodes()
2823 ## Add a node to the mesh by coordinates
2824 # @return Id of the new node
2825 # @ingroup l2_modif_add
2826 def AddNode(self, x, y, z):
2827 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2828 if hasVars: self.mesh.SetParameters(Parameters)
2829 return self.editor.AddNode( x, y, z)
2831 ## Creates a 0D element on a node with given number.
2832 # @param IDOfNode the ID of node for creation of the element.
2833 # @param DuplicateElements to add one more 0D element to a node or not
2834 # @return the Id of the new 0D element
2835 # @ingroup l2_modif_add
2836 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2837 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2839 ## Create 0D elements on all nodes of the given elements except those
2840 # nodes on which a 0D element already exists.
2841 # @param theObject an object on whose nodes 0D elements will be created.
2842 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2843 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2844 # @param theGroupName optional name of a group to add 0D elements created
2845 # and/or found on nodes of \a theObject.
2846 # @param DuplicateElements to add one more 0D element to a node or not
2847 # @return an object (a new group or a temporary SMESH_IDSource) holding
2848 # IDs of new and/or found 0D elements. IDs of 0D elements
2849 # can be retrieved from the returned object by calling GetIDs()
2850 # @ingroup l2_modif_add
2851 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2852 unRegister = genObjUnRegister()
2853 if isinstance( theObject, Mesh ):
2854 theObject = theObject.GetMesh()
2855 elif isinstance( theObject, list ):
2856 theObject = self.GetIDSource( theObject, SMESH.ALL )
2857 unRegister.set( theObject )
2858 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2860 ## Creates a ball element on a node with given ID.
2861 # @param IDOfNode the ID of node for creation of the element.
2862 # @param diameter the bal diameter.
2863 # @return the Id of the new ball element
2864 # @ingroup l2_modif_add
2865 def AddBall(self, IDOfNode, diameter):
2866 return self.editor.AddBall( IDOfNode, diameter )
2868 ## Creates a linear or quadratic edge (this is determined
2869 # by the number of given nodes).
2870 # @param IDsOfNodes the list of node IDs for creation of the element.
2871 # The order of nodes in this list should correspond to the description
2872 # of MED. \n This description is located by the following link:
2873 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2874 # @return the Id of the new edge
2875 # @ingroup l2_modif_add
2876 def AddEdge(self, IDsOfNodes):
2877 return self.editor.AddEdge(IDsOfNodes)
2879 ## Creates a linear or quadratic face (this is determined
2880 # by the number of given nodes).
2881 # @param IDsOfNodes the list of node IDs for creation of the element.
2882 # The order of nodes in this list should correspond to the description
2883 # of MED. \n This description is located by the following link:
2884 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2885 # @return the Id of the new face
2886 # @ingroup l2_modif_add
2887 def AddFace(self, IDsOfNodes):
2888 return self.editor.AddFace(IDsOfNodes)
2890 ## Adds a polygonal face to the mesh by the list of node IDs
2891 # @param IdsOfNodes the list of node IDs for creation of the element.
2892 # @return the Id of the new face
2893 # @ingroup l2_modif_add
2894 def AddPolygonalFace(self, IdsOfNodes):
2895 return self.editor.AddPolygonalFace(IdsOfNodes)
2897 ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2898 # @param IdsOfNodes the list of node IDs for creation of the element;
2899 # corner nodes follow first.
2900 # @return the Id of the new face
2901 # @ingroup l2_modif_add
2902 def AddQuadPolygonalFace(self, IdsOfNodes):
2903 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2905 ## Creates both simple and quadratic volume (this is determined
2906 # by the number of given nodes).
2907 # @param IDsOfNodes the list of node IDs for creation of the element.
2908 # The order of nodes in this list should correspond to the description
2909 # of MED. \n This description is located by the following link:
2910 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2911 # @return the Id of the new volumic element
2912 # @ingroup l2_modif_add
2913 def AddVolume(self, IDsOfNodes):
2914 return self.editor.AddVolume(IDsOfNodes)
2916 ## Creates a volume of many faces, giving nodes for each face.
2917 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2918 # @param Quantities the list of integer values, Quantities[i]
2919 # gives the quantity of nodes in face number i.
2920 # @return the Id of the new volumic element
2921 # @ingroup l2_modif_add
2922 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2923 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2925 ## Creates a volume of many faces, giving the IDs of the existing faces.
2926 # @param IdsOfFaces the list of face IDs for volume creation.
2928 # Note: The created volume will refer only to the nodes
2929 # of the given faces, not to the faces themselves.
2930 # @return the Id of the new volumic element
2931 # @ingroup l2_modif_add
2932 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2933 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2936 ## @brief Binds a node to a vertex
2937 # @param NodeID a node ID
2938 # @param Vertex a vertex or vertex ID
2939 # @return True if succeed else raises an exception
2940 # @ingroup l2_modif_add
2941 def SetNodeOnVertex(self, NodeID, Vertex):
2942 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2943 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2947 self.editor.SetNodeOnVertex(NodeID, VertexID)
2948 except SALOME.SALOME_Exception, inst:
2949 raise ValueError, inst.details.text
2953 ## @brief Stores the node position on an edge
2954 # @param NodeID a node ID
2955 # @param Edge an edge or edge ID
2956 # @param paramOnEdge a parameter on the edge where the node is located
2957 # @return True if succeed else raises an exception
2958 # @ingroup l2_modif_add
2959 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2960 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2961 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2965 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2966 except SALOME.SALOME_Exception, inst:
2967 raise ValueError, inst.details.text
2970 ## @brief Stores node position on a face
2971 # @param NodeID a node ID
2972 # @param Face a face or face ID
2973 # @param u U parameter on the face where the node is located
2974 # @param v V parameter on the face where the node is located
2975 # @return True if succeed else raises an exception
2976 # @ingroup l2_modif_add
2977 def SetNodeOnFace(self, NodeID, Face, u, v):
2978 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2979 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
2983 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2984 except SALOME.SALOME_Exception, inst:
2985 raise ValueError, inst.details.text
2988 ## @brief Binds a node to a solid
2989 # @param NodeID a node ID
2990 # @param Solid a solid or solid ID
2991 # @return True if succeed else raises an exception
2992 # @ingroup l2_modif_add
2993 def SetNodeInVolume(self, NodeID, Solid):
2994 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2995 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
2999 self.editor.SetNodeInVolume(NodeID, SolidID)
3000 except SALOME.SALOME_Exception, inst:
3001 raise ValueError, inst.details.text
3004 ## @brief Bind an element to a shape
3005 # @param ElementID an element ID
3006 # @param Shape a shape or shape ID
3007 # @return True if succeed else raises an exception
3008 # @ingroup l2_modif_add
3009 def SetMeshElementOnShape(self, ElementID, Shape):
3010 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3011 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3015 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3016 except SALOME.SALOME_Exception, inst:
3017 raise ValueError, inst.details.text
3021 ## Moves the node with the given id
3022 # @param NodeID the id of the node
3023 # @param x a new X coordinate
3024 # @param y a new Y coordinate
3025 # @param z a new Z coordinate
3026 # @return True if succeed else False
3027 # @ingroup l2_modif_movenode
3028 def MoveNode(self, NodeID, x, y, z):
3029 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3030 if hasVars: self.mesh.SetParameters(Parameters)
3031 return self.editor.MoveNode(NodeID, x, y, z)
3033 ## Finds the node closest to a point and moves it to a point location
3034 # @param x the X coordinate of a point
3035 # @param y the Y coordinate of a point
3036 # @param z the Z coordinate of a point
3037 # @param NodeID if specified (>0), the node with this ID is moved,
3038 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3039 # @return the ID of a node
3040 # @ingroup l2_modif_throughp
3041 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3042 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3043 if hasVars: self.mesh.SetParameters(Parameters)
3044 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3046 ## Finds the node closest to a point
3047 # @param x the X coordinate of a point
3048 # @param y the Y coordinate of a point
3049 # @param z the Z coordinate of a point
3050 # @return the ID of a node
3051 # @ingroup l2_modif_throughp
3052 def FindNodeClosestTo(self, x, y, z):
3053 #preview = self.mesh.GetMeshEditPreviewer()
3054 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3055 return self.editor.FindNodeClosestTo(x, y, z)
3057 ## Finds the elements where a point lays IN or ON
3058 # @param x the X coordinate of a point
3059 # @param y the Y coordinate of a point
3060 # @param z the Z coordinate of a point
3061 # @param elementType type of elements to find; either of
3062 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3063 # means elements of any type excluding nodes, discrete and 0D elements.
3064 # @param meshPart a part of mesh (group, sub-mesh) to search within
3065 # @return list of IDs of found elements
3066 # @ingroup l2_modif_throughp
3067 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3069 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3071 return self.editor.FindElementsByPoint(x, y, z, elementType)
3073 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3074 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3075 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3076 def GetPointState(self, x, y, z):
3077 return self.editor.GetPointState(x, y, z)
3079 ## Finds the node closest to a point and moves it to a point location
3080 # @param x the X coordinate of a point
3081 # @param y the Y coordinate of a point
3082 # @param z the Z coordinate of a point
3083 # @return the ID of a moved node
3084 # @ingroup l2_modif_throughp
3085 def MeshToPassThroughAPoint(self, x, y, z):
3086 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3088 ## Replaces two neighbour triangles sharing Node1-Node2 link
3089 # with the triangles built on the same 4 nodes but having other common link.
3090 # @param NodeID1 the ID of the first node
3091 # @param NodeID2 the ID of the second node
3092 # @return false if proper faces were not found
3093 # @ingroup l2_modif_cutquadr
3094 def InverseDiag(self, NodeID1, NodeID2):
3095 return self.editor.InverseDiag(NodeID1, NodeID2)
3097 ## Replaces two neighbour triangles sharing Node1-Node2 link
3098 # with a quadrangle built on the same 4 nodes.
3099 # @param NodeID1 the ID of the first node
3100 # @param NodeID2 the ID of the second node
3101 # @return false if proper faces were not found
3102 # @ingroup l2_modif_unitetri
3103 def DeleteDiag(self, NodeID1, NodeID2):
3104 return self.editor.DeleteDiag(NodeID1, NodeID2)
3106 ## Reorients elements by ids
3107 # @param IDsOfElements if undefined reorients all mesh elements
3108 # @return True if succeed else False
3109 # @ingroup l2_modif_changori
3110 def Reorient(self, IDsOfElements=None):
3111 if IDsOfElements == None:
3112 IDsOfElements = self.GetElementsId()
3113 return self.editor.Reorient(IDsOfElements)
3115 ## Reorients all elements of the object
3116 # @param theObject mesh, submesh or group
3117 # @return True if succeed else False
3118 # @ingroup l2_modif_changori
3119 def ReorientObject(self, theObject):
3120 if ( isinstance( theObject, Mesh )):
3121 theObject = theObject.GetMesh()
3122 return self.editor.ReorientObject(theObject)
3124 ## Reorient faces contained in \a the2DObject.
3125 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3126 # @param theDirection is a desired direction of normal of \a theFace.
3127 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3128 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3129 # compared with theDirection. It can be either ID of face or a point
3130 # by which the face will be found. The point can be given as either
3131 # a GEOM vertex or a list of point coordinates.
3132 # @return number of reoriented faces
3133 # @ingroup l2_modif_changori
3134 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3135 unRegister = genObjUnRegister()
3137 if isinstance( the2DObject, Mesh ):
3138 the2DObject = the2DObject.GetMesh()
3139 if isinstance( the2DObject, list ):
3140 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3141 unRegister.set( the2DObject )
3142 # check theDirection
3143 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3144 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3145 if isinstance( theDirection, list ):
3146 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3147 # prepare theFace and thePoint
3148 theFace = theFaceOrPoint
3149 thePoint = PointStruct(0,0,0)
3150 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3151 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3153 if isinstance( theFaceOrPoint, list ):
3154 thePoint = PointStruct( *theFaceOrPoint )
3156 if isinstance( theFaceOrPoint, PointStruct ):
3157 thePoint = theFaceOrPoint
3159 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3161 ## Reorient faces according to adjacent volumes.
3162 # @param the2DObject is a mesh, sub-mesh, group or list of
3163 # either IDs of faces or face groups.
3164 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3165 # @param theOutsideNormal to orient faces to have their normals
3166 # pointing either \a outside or \a inside the adjacent volumes.
3167 # @return number of reoriented faces.
3168 # @ingroup l2_modif_changori
3169 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3170 unRegister = genObjUnRegister()
3172 if not isinstance( the2DObject, list ):
3173 the2DObject = [ the2DObject ]
3174 elif the2DObject and isinstance( the2DObject[0], int ):
3175 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3176 unRegister.set( the2DObject )
3177 the2DObject = [ the2DObject ]
3178 for i,obj2D in enumerate( the2DObject ):
3179 if isinstance( obj2D, Mesh ):
3180 the2DObject[i] = obj2D.GetMesh()
3181 if isinstance( obj2D, list ):
3182 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3183 unRegister.set( the2DObject[i] )
3185 if isinstance( the3DObject, Mesh ):
3186 the3DObject = the3DObject.GetMesh()
3187 if isinstance( the3DObject, list ):
3188 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3189 unRegister.set( the3DObject )
3190 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3192 ## Fuses the neighbouring triangles into quadrangles.
3193 # @param IDsOfElements The triangles to be fused.
3194 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3195 # applied to possible quadrangles to choose a neighbour to fuse with.
3196 # Type SMESH.FunctorType._items in the Python Console to see all items.
3197 # Note that not all items correspond to numerical functors.
3198 # @param MaxAngle is the maximum angle between element normals at which the fusion
3199 # is still performed; theMaxAngle is mesured in radians.
3200 # Also it could be a name of variable which defines angle in degrees.
3201 # @return TRUE in case of success, FALSE otherwise.
3202 # @ingroup l2_modif_unitetri
3203 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3204 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3205 self.mesh.SetParameters(Parameters)
3206 if not IDsOfElements:
3207 IDsOfElements = self.GetElementsId()
3208 Functor = self.smeshpyD.GetFunctor(theCriterion)
3209 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3211 ## Fuses the neighbouring triangles of the object into quadrangles
3212 # @param theObject is mesh, submesh or group
3213 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3214 # applied to possible quadrangles to choose a neighbour to fuse with.
3215 # Type SMESH.FunctorType._items in the Python Console to see all items.
3216 # Note that not all items correspond to numerical functors.
3217 # @param MaxAngle a max angle between element normals at which the fusion
3218 # is still performed; theMaxAngle is mesured in radians.
3219 # @return TRUE in case of success, FALSE otherwise.
3220 # @ingroup l2_modif_unitetri
3221 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3222 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3223 self.mesh.SetParameters(Parameters)
3224 if isinstance( theObject, Mesh ):
3225 theObject = theObject.GetMesh()
3226 Functor = self.smeshpyD.GetFunctor(theCriterion)
3227 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3229 ## Splits quadrangles into triangles.
3230 # @param IDsOfElements the faces to be splitted.
3231 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3232 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3233 # value, then quadrangles will be split by the smallest diagonal.
3234 # Type SMESH.FunctorType._items in the Python Console to see all items.
3235 # Note that not all items correspond to numerical functors.
3236 # @return TRUE in case of success, FALSE otherwise.
3237 # @ingroup l2_modif_cutquadr
3238 def QuadToTri (self, IDsOfElements, theCriterion = None):
3239 if IDsOfElements == []:
3240 IDsOfElements = self.GetElementsId()
3241 if theCriterion is None:
3242 theCriterion = FT_MaxElementLength2D
3243 Functor = self.smeshpyD.GetFunctor(theCriterion)
3244 return self.editor.QuadToTri(IDsOfElements, Functor)
3246 ## Splits quadrangles into triangles.
3247 # @param theObject the object from which the list of elements is taken,
3248 # this is mesh, submesh or group
3249 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3250 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3251 # value, then quadrangles will be split by the smallest diagonal.
3252 # Type SMESH.FunctorType._items in the Python Console to see all items.
3253 # Note that not all items correspond to numerical functors.
3254 # @return TRUE in case of success, FALSE otherwise.
3255 # @ingroup l2_modif_cutquadr
3256 def QuadToTriObject (self, theObject, theCriterion = None):
3257 if ( isinstance( theObject, Mesh )):
3258 theObject = theObject.GetMesh()
3259 if theCriterion is None:
3260 theCriterion = FT_MaxElementLength2D
3261 Functor = self.smeshpyD.GetFunctor(theCriterion)
3262 return self.editor.QuadToTriObject(theObject, Functor)
3264 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3266 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3267 # group or a list of face IDs. By default all quadrangles are split
3268 # @ingroup l2_modif_cutquadr
3269 def QuadTo4Tri (self, theElements=[]):
3270 unRegister = genObjUnRegister()
3271 if isinstance( theElements, Mesh ):
3272 theElements = theElements.mesh
3273 elif not theElements:
3274 theElements = self.mesh
3275 elif isinstance( theElements, list ):
3276 theElements = self.GetIDSource( theElements, SMESH.FACE )
3277 unRegister.set( theElements )
3278 return self.editor.QuadTo4Tri( theElements )
3280 ## Splits quadrangles into triangles.
3281 # @param IDsOfElements the faces to be splitted
3282 # @param Diag13 is used to choose a diagonal for splitting.
3283 # @return TRUE in case of success, FALSE otherwise.
3284 # @ingroup l2_modif_cutquadr
3285 def SplitQuad (self, IDsOfElements, Diag13):
3286 if IDsOfElements == []:
3287 IDsOfElements = self.GetElementsId()
3288 return self.editor.SplitQuad(IDsOfElements, Diag13)
3290 ## Splits quadrangles into triangles.
3291 # @param theObject the object from which the list of elements is taken,
3292 # this is mesh, submesh or group
3293 # @param Diag13 is used to choose a diagonal for splitting.
3294 # @return TRUE in case of success, FALSE otherwise.
3295 # @ingroup l2_modif_cutquadr
3296 def SplitQuadObject (self, theObject, Diag13):
3297 if ( isinstance( theObject, Mesh )):
3298 theObject = theObject.GetMesh()
3299 return self.editor.SplitQuadObject(theObject, Diag13)
3301 ## Finds a better splitting of the given quadrangle.
3302 # @param IDOfQuad the ID of the quadrangle to be splitted.
3303 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3304 # choose a diagonal for splitting.
3305 # Type SMESH.FunctorType._items in the Python Console to see all items.
3306 # Note that not all items correspond to numerical functors.
3307 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3308 # diagonal is better, 0 if error occurs.
3309 # @ingroup l2_modif_cutquadr
3310 def BestSplit (self, IDOfQuad, theCriterion):
3311 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3313 ## Splits volumic elements into tetrahedrons
3314 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3315 # @param method flags passing splitting method:
3316 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3317 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3318 # @ingroup l2_modif_cutquadr
3319 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3320 unRegister = genObjUnRegister()
3321 if isinstance( elems, Mesh ):
3322 elems = elems.GetMesh()
3323 if ( isinstance( elems, list )):
3324 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3325 unRegister.set( elems )
3326 self.editor.SplitVolumesIntoTetra(elems, method)
3329 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3330 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3331 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3332 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3333 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3334 # will be split in order to keep the mesh conformal.
3335 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3336 # if None (default), all bi-quadratic elements will be split
3337 # @ingroup l2_modif_cutquadr
3338 def SplitBiQuadraticIntoLinear(self, elems=None):
3339 unRegister = genObjUnRegister()
3340 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3341 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3342 unRegister.set( elems )
3344 elems = [ self.GetMesh() ]
3345 if isinstance( elems, Mesh ):
3346 elems = [ elems.GetMesh() ]
3347 if not isinstance( elems, list ):
3349 self.editor.SplitBiQuadraticIntoLinear( elems )
3351 ## Splits hexahedra into prisms
3352 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3353 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3354 # gives a normal vector defining facets to split into triangles.
3355 # @a startHexPoint can be either a triple of coordinates or a vertex.
3356 # @param facetNormal a normal to a facet to split into triangles of a
3357 # hexahedron found by @a startHexPoint.
3358 # @a facetNormal can be either a triple of coordinates or an edge.
3359 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3360 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3361 # @param allDomains if @c False, only hexahedra adjacent to one closest
3362 # to @a startHexPoint are split, else @a startHexPoint
3363 # is used to find the facet to split in all domains present in @a elems.
3364 # @ingroup l2_modif_cutquadr
3365 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3366 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3368 unRegister = genObjUnRegister()
3369 if isinstance( elems, Mesh ):
3370 elems = elems.GetMesh()
3371 if ( isinstance( elems, list )):
3372 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3373 unRegister.set( elems )
3376 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3377 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3378 elif isinstance( startHexPoint, list ):
3379 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3382 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3383 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3384 elif isinstance( facetNormal, list ):
3385 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3388 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3390 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3392 ## Splits quadrangle faces near triangular facets of volumes
3394 # @ingroup l1_auxiliary
3395 def SplitQuadsNearTriangularFacets(self):
3396 faces_array = self.GetElementsByType(SMESH.FACE)
3397 for face_id in faces_array:
3398 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3399 quad_nodes = self.mesh.GetElemNodes(face_id)
3400 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3401 isVolumeFound = False
3402 for node1_elem in node1_elems:
3403 if not isVolumeFound:
3404 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3405 nb_nodes = self.GetElemNbNodes(node1_elem)
3406 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3407 volume_elem = node1_elem
3408 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3409 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3410 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3411 isVolumeFound = True
3412 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3413 self.SplitQuad([face_id], False) # diagonal 2-4
3414 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3415 isVolumeFound = True
3416 self.SplitQuad([face_id], True) # diagonal 1-3
3417 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3418 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3419 isVolumeFound = True
3420 self.SplitQuad([face_id], True) # diagonal 1-3
3422 ## @brief Splits hexahedrons into tetrahedrons.
3424 # This operation uses pattern mapping functionality for splitting.
3425 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3426 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3427 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3428 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3429 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3430 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3431 # @return TRUE in case of success, FALSE otherwise.
3432 # @ingroup l1_auxiliary
3433 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3434 # Pattern: 5.---------.6
3439 # (0,0,1) 4.---------.7 * |
3446 # (0,0,0) 0.---------.3
3447 pattern_tetra = "!!! Nb of points: \n 8 \n\
3457 !!! Indices of points of 6 tetras: \n\
3465 pattern = self.smeshpyD.GetPattern()
3466 isDone = pattern.LoadFromFile(pattern_tetra)
3468 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3471 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3472 isDone = pattern.MakeMesh(self.mesh, False, False)
3473 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3475 # split quafrangle faces near triangular facets of volumes
3476 self.SplitQuadsNearTriangularFacets()
3480 ## @brief Split hexahedrons into prisms.
3482 # Uses the pattern mapping functionality for splitting.
3483 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3484 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3485 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3486 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3487 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3488 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3489 # @return TRUE in case of success, FALSE otherwise.
3490 # @ingroup l1_auxiliary
3491 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3492 # Pattern: 5.---------.6
3497 # (0,0,1) 4.---------.7 |
3504 # (0,0,0) 0.---------.3
3505 pattern_prism = "!!! Nb of points: \n 8 \n\
3515 !!! Indices of points of 2 prisms: \n\
3519 pattern = self.smeshpyD.GetPattern()
3520 isDone = pattern.LoadFromFile(pattern_prism)
3522 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3525 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3526 isDone = pattern.MakeMesh(self.mesh, False, False)
3527 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3529 # Splits quafrangle faces near triangular facets of volumes
3530 self.SplitQuadsNearTriangularFacets()
3534 ## Smoothes elements
3535 # @param IDsOfElements the list if ids of elements to smooth
3536 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3537 # Note that nodes built on edges and boundary nodes are always fixed.
3538 # @param MaxNbOfIterations the maximum number of iterations
3539 # @param MaxAspectRatio varies in range [1.0, inf]
3540 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3541 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3542 # @return TRUE in case of success, FALSE otherwise.
3543 # @ingroup l2_modif_smooth
3544 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3545 MaxNbOfIterations, MaxAspectRatio, Method):
3546 if IDsOfElements == []:
3547 IDsOfElements = self.GetElementsId()
3548 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3549 self.mesh.SetParameters(Parameters)
3550 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3551 MaxNbOfIterations, MaxAspectRatio, Method)
3553 ## Smoothes elements which belong to the given object
3554 # @param theObject the object to smooth
3555 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3556 # Note that nodes built on edges and boundary nodes are always fixed.
3557 # @param MaxNbOfIterations the maximum number of iterations
3558 # @param MaxAspectRatio varies in range [1.0, inf]
3559 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3560 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3561 # @return TRUE in case of success, FALSE otherwise.
3562 # @ingroup l2_modif_smooth
3563 def SmoothObject(self, theObject, IDsOfFixedNodes,
3564 MaxNbOfIterations, MaxAspectRatio, Method):
3565 if ( isinstance( theObject, Mesh )):
3566 theObject = theObject.GetMesh()
3567 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3568 MaxNbOfIterations, MaxAspectRatio, Method)
3570 ## Parametrically smoothes the given elements
3571 # @param IDsOfElements the list if ids of elements to smooth
3572 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3573 # Note that nodes built on edges and boundary nodes are always fixed.
3574 # @param MaxNbOfIterations the maximum number of iterations
3575 # @param MaxAspectRatio varies in range [1.0, inf]
3576 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3577 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3578 # @return TRUE in case of success, FALSE otherwise.
3579 # @ingroup l2_modif_smooth
3580 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3581 MaxNbOfIterations, MaxAspectRatio, Method):
3582 if IDsOfElements == []:
3583 IDsOfElements = self.GetElementsId()
3584 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3585 self.mesh.SetParameters(Parameters)
3586 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3587 MaxNbOfIterations, MaxAspectRatio, Method)
3589 ## Parametrically smoothes the elements which belong to the given object
3590 # @param theObject the object to smooth
3591 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3592 # Note that nodes built on edges and boundary nodes are always fixed.
3593 # @param MaxNbOfIterations the maximum number of iterations
3594 # @param MaxAspectRatio varies in range [1.0, inf]
3595 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3596 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3597 # @return TRUE in case of success, FALSE otherwise.
3598 # @ingroup l2_modif_smooth
3599 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3600 MaxNbOfIterations, MaxAspectRatio, Method):
3601 if ( isinstance( theObject, Mesh )):
3602 theObject = theObject.GetMesh()
3603 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3604 MaxNbOfIterations, MaxAspectRatio, Method)
3606 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3607 # them with quadratic with the same id.
3608 # @param theForce3d new node creation method:
3609 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3610 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3611 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3612 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3613 # @ingroup l2_modif_tofromqu
3614 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3615 if isinstance( theSubMesh, Mesh ):
3616 theSubMesh = theSubMesh.mesh
3618 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3621 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3623 self.editor.ConvertToQuadratic(theForce3d)
3624 error = self.editor.GetLastError()
3625 if error and error.comment:
3628 ## Converts the mesh from quadratic to ordinary,
3629 # deletes old quadratic elements, \n replacing
3630 # them with ordinary mesh elements with the same id.
3631 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3632 # @ingroup l2_modif_tofromqu
3633 def ConvertFromQuadratic(self, theSubMesh=None):
3635 self.editor.ConvertFromQuadraticObject(theSubMesh)
3637 return self.editor.ConvertFromQuadratic()
3639 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3640 # @return TRUE if operation has been completed successfully, FALSE otherwise
3641 # @ingroup l2_modif_edit
3642 def Make2DMeshFrom3D(self):
3643 return self.editor.Make2DMeshFrom3D()
3645 ## Creates missing boundary elements
3646 # @param elements - elements whose boundary is to be checked:
3647 # mesh, group, sub-mesh or list of elements
3648 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3649 # @param dimension - defines type of boundary elements to create, either of
3650 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3651 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3652 # @param groupName - a name of group to store created boundary elements in,
3653 # "" means not to create the group
3654 # @param meshName - a name of new mesh to store created boundary elements in,
3655 # "" means not to create the new mesh
3656 # @param toCopyElements - if true, the checked elements will be copied into
3657 # the new mesh else only boundary elements will be copied into the new mesh
3658 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3659 # boundary elements will be copied into the new mesh
3660 # @return tuple (mesh, group) where boundary elements were added to
3661 # @ingroup l2_modif_edit
3662 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3663 toCopyElements=False, toCopyExistingBondary=False):
3664 unRegister = genObjUnRegister()
3665 if isinstance( elements, Mesh ):
3666 elements = elements.GetMesh()
3667 if ( isinstance( elements, list )):
3668 elemType = SMESH.ALL
3669 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3670 elements = self.editor.MakeIDSource(elements, elemType)
3671 unRegister.set( elements )
3672 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3673 toCopyElements,toCopyExistingBondary)
3674 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3678 # @brief Creates missing boundary elements around either the whole mesh or
3679 # groups of elements
3680 # @param dimension - defines type of boundary elements to create, either of
3681 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3682 # @param groupName - a name of group to store all boundary elements in,
3683 # "" means not to create the group
3684 # @param meshName - a name of a new mesh, which is a copy of the initial
3685 # mesh + created boundary elements; "" means not to create the new mesh
3686 # @param toCopyAll - if true, the whole initial mesh will be copied into
3687 # the new mesh else only boundary elements will be copied into the new mesh
3688 # @param groups - groups of elements to make boundary around
3689 # @retval tuple( long, mesh, groups )
3690 # long - number of added boundary elements
3691 # mesh - the mesh where elements were added to
3692 # group - the group of boundary elements or None
3694 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3695 toCopyAll=False, groups=[]):
3696 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3698 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3699 return nb, mesh, group
3701 ## Renumber mesh nodes (Obsolete, does nothing)
3702 # @ingroup l2_modif_renumber
3703 def RenumberNodes(self):
3704 self.editor.RenumberNodes()
3706 ## Renumber mesh elements (Obsole, does nothing)
3707 # @ingroup l2_modif_renumber
3708 def RenumberElements(self):
3709 self.editor.RenumberElements()
3711 ## Private method converting \a arg into a list of SMESH_IdSource's
3712 def _getIdSourceList(self, arg, idType, unRegister):
3713 if arg and isinstance( arg, list ):
3714 if isinstance( arg[0], int ):
3715 arg = self.GetIDSource( arg, idType )
3716 unRegister.set( arg )
3717 elif isinstance( arg[0], Mesh ):
3718 arg[0] = arg[0].GetMesh()
3719 elif isinstance( arg, Mesh ):
3721 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3725 ## Generates new elements by rotation of the given elements and nodes around the axis
3726 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3727 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3728 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3729 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3730 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3731 # which defines angle in degrees
3732 # @param NbOfSteps the number of steps
3733 # @param Tolerance tolerance
3734 # @param MakeGroups forces the generation of new groups from existing ones
3735 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3736 # of all steps, else - size of each step
3737 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3738 # @ingroup l2_modif_extrurev
3739 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3740 MakeGroups=False, TotalAngle=False):
3741 unRegister = genObjUnRegister()
3742 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3743 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3744 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3746 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3747 Axis = self.smeshpyD.GetAxisStruct( Axis )
3748 if isinstance( Axis, list ):
3749 Axis = SMESH.AxisStruct( *Axis )
3751 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3752 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3753 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3754 self.mesh.SetParameters(Parameters)
3755 if TotalAngle and NbOfSteps:
3756 AngleInRadians /= NbOfSteps
3757 return self.editor.RotationSweepObjects( nodes, edges, faces,
3758 Axis, AngleInRadians,
3759 NbOfSteps, Tolerance, MakeGroups)
3761 ## Generates new elements by rotation of the elements around the axis
3762 # @param IDsOfElements the list of ids of elements to sweep
3763 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3764 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3765 # @param NbOfSteps the number of steps
3766 # @param Tolerance tolerance
3767 # @param MakeGroups forces the generation of new groups from existing ones
3768 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3769 # of all steps, else - size of each step
3770 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3771 # @ingroup l2_modif_extrurev
3772 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3773 MakeGroups=False, TotalAngle=False):
3774 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3775 AngleInRadians, NbOfSteps, Tolerance,
3776 MakeGroups, TotalAngle)
3778 ## Generates new elements by rotation of the elements of object around the axis
3779 # @param theObject object which elements should be sweeped.
3780 # It can be a mesh, a sub mesh or a group.
3781 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3782 # @param AngleInRadians the angle of Rotation
3783 # @param NbOfSteps number of steps
3784 # @param Tolerance tolerance
3785 # @param MakeGroups forces the generation of new groups from existing ones
3786 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3787 # of all steps, else - size of each step
3788 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3789 # @ingroup l2_modif_extrurev
3790 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3791 MakeGroups=False, TotalAngle=False):
3792 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3793 AngleInRadians, NbOfSteps, Tolerance,
3794 MakeGroups, TotalAngle )
3796 ## Generates new elements by rotation of the elements of object around the axis
3797 # @param theObject object which elements should be sweeped.
3798 # It can be a mesh, a sub mesh or a group.
3799 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3800 # @param AngleInRadians the angle of Rotation
3801 # @param NbOfSteps number of steps
3802 # @param Tolerance tolerance
3803 # @param MakeGroups forces the generation of new groups from existing ones
3804 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3805 # of all steps, else - size of each step
3806 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3807 # @ingroup l2_modif_extrurev
3808 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3809 MakeGroups=False, TotalAngle=False):
3810 return self.RotationSweepObjects([],theObject,[], Axis,
3811 AngleInRadians, NbOfSteps, Tolerance,
3812 MakeGroups, TotalAngle)
3814 ## Generates new elements by rotation of the elements of object around the axis
3815 # @param theObject object which elements should be sweeped.
3816 # It can be a mesh, a sub mesh or a group.
3817 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3818 # @param AngleInRadians the angle of Rotation
3819 # @param NbOfSteps number of steps
3820 # @param Tolerance tolerance
3821 # @param MakeGroups forces the generation of new groups from existing ones
3822 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3823 # of all steps, else - size of each step
3824 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3825 # @ingroup l2_modif_extrurev
3826 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3827 MakeGroups=False, TotalAngle=False):
3828 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3829 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3831 ## Generates new elements by extrusion of the given elements and nodes
3832 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3833 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3834 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3835 # @param StepVector vector or DirStruct or 3 vector components, defining
3836 # the direction and value of extrusion for one step (the total extrusion
3837 # length will be NbOfSteps * ||StepVector||)
3838 # @param NbOfSteps the number of steps
3839 # @param MakeGroups forces the generation of new groups from existing ones
3840 # @param scaleFactors optional scale factors to apply during extrusion
3841 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3842 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3843 # @param basePoint optional scaling center; if not provided, a gravity center of
3844 # nodes and elements being extruded is used as the scaling center.
3846 # - a list of tree components of the point or
3849 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3850 # @ingroup l2_modif_extrurev
3851 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3852 scaleFactors=[], linearVariation=False, basePoint=[] ):
3853 unRegister = genObjUnRegister()
3854 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3855 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3856 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3858 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3859 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3860 if isinstance( StepVector, list ):
3861 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3863 if isinstance( basePoint, int):
3864 xyz = self.GetNodeXYZ( basePoint )
3866 raise RuntimeError, "Invalid node ID: %s" % basePoint
3868 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3869 basePoint = self.geompyD.PointCoordinates( basePoint )
3871 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3872 Parameters = StepVector.PS.parameters + var_separator + Parameters
3873 self.mesh.SetParameters(Parameters)
3875 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3876 StepVector, NbOfSteps,
3877 scaleFactors, linearVariation, basePoint,
3881 ## Generates new elements by extrusion of the elements with given ids
3882 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3883 # @param StepVector vector or DirStruct or 3 vector components, defining
3884 # the direction and value of extrusion for one step (the total extrusion
3885 # length will be NbOfSteps * ||StepVector||)
3886 # @param NbOfSteps the number of steps
3887 # @param MakeGroups forces the generation of new groups from existing ones
3888 # @param IsNodes is True if elements with given ids are nodes
3889 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3890 # @ingroup l2_modif_extrurev
3891 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3893 if IsNodes: n = IDsOfElements
3894 else : e,f, = IDsOfElements,IDsOfElements
3895 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3897 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3898 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3899 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3900 # @param StepSize length of one extrusion step (the total extrusion
3901 # length will be \a NbOfSteps * \a StepSize ).
3902 # @param NbOfSteps number of extrusion steps.
3903 # @param ByAverageNormal if True each node is translated by \a StepSize
3904 # along the average of the normal vectors to the faces sharing the node;
3905 # else each node is translated along the same average normal till
3906 # intersection with the plane got by translation of the face sharing
3907 # the node along its own normal by \a StepSize.
3908 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3909 # for every node of \a Elements.
3910 # @param MakeGroups forces generation of new groups from existing ones.
3911 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3912 # is not yet implemented. This parameter is used if \a Elements contains
3913 # both faces and edges, i.e. \a Elements is a Mesh.
3914 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3915 # empty list otherwise.
3916 # @ingroup l2_modif_extrurev
3917 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3918 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3919 unRegister = genObjUnRegister()
3920 if isinstance( Elements, Mesh ):
3921 Elements = [ Elements.GetMesh() ]
3922 if isinstance( Elements, list ):
3924 raise RuntimeError, "Elements empty!"
3925 if isinstance( Elements[0], int ):
3926 Elements = self.GetIDSource( Elements, SMESH.ALL )
3927 unRegister.set( Elements )
3928 if not isinstance( Elements, list ):
3929 Elements = [ Elements ]
3930 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3931 self.mesh.SetParameters(Parameters)
3932 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3933 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3935 ## Generates new elements by extrusion of the elements or nodes which belong to the object
3936 # @param theObject the object whose elements or nodes should be processed.
3937 # It can be a mesh, a sub-mesh or a group.
3938 # @param StepVector vector or DirStruct or 3 vector components, defining
3939 # the direction and value of extrusion for one step (the total extrusion
3940 # length will be NbOfSteps * ||StepVector||)
3941 # @param NbOfSteps the number of steps
3942 # @param MakeGroups forces the generation of new groups from existing ones
3943 # @param IsNodes is True if elements to extrude are nodes
3944 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3945 # @ingroup l2_modif_extrurev
3946 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3948 if IsNodes: n = theObject
3949 else : e,f, = theObject,theObject
3950 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3952 ## Generates new elements by extrusion of edges which belong to the object
3953 # @param theObject object whose 1D elements should be processed.
3954 # It can be a mesh, a sub-mesh or a group.
3955 # @param StepVector vector or DirStruct or 3 vector components, defining
3956 # the direction and value of extrusion for one step (the total extrusion
3957 # length will be NbOfSteps * ||StepVector||)
3958 # @param NbOfSteps the number of steps
3959 # @param MakeGroups to generate new groups from existing ones
3960 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3961 # @ingroup l2_modif_extrurev
3962 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3963 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3965 ## Generates new elements by extrusion of faces which belong to the object
3966 # @param theObject object whose 2D elements should be processed.
3967 # It can be a mesh, a sub-mesh or a group.
3968 # @param StepVector vector or DirStruct or 3 vector components, defining
3969 # the direction and value of extrusion for one step (the total extrusion
3970 # length will be NbOfSteps * ||StepVector||)
3971 # @param NbOfSteps the number of steps
3972 # @param MakeGroups forces the generation of new groups from existing ones
3973 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3974 # @ingroup l2_modif_extrurev
3975 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3976 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3978 ## Generates new elements by extrusion of the elements with given ids
3979 # @param IDsOfElements is ids of elements
3980 # @param StepVector vector or DirStruct or 3 vector components, defining
3981 # the direction and value of extrusion for one step (the total extrusion
3982 # length will be NbOfSteps * ||StepVector||)
3983 # @param NbOfSteps the number of steps
3984 # @param ExtrFlags sets flags for extrusion
3985 # @param SewTolerance uses for comparing locations of nodes if flag
3986 # EXTRUSION_FLAG_SEW is set
3987 # @param MakeGroups forces the generation of new groups from existing ones
3988 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3989 # @ingroup l2_modif_extrurev
3990 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3991 ExtrFlags, SewTolerance, MakeGroups=False):
3992 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3993 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3994 if isinstance( StepVector, list ):
3995 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3996 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3997 ExtrFlags, SewTolerance, MakeGroups)
3999 ## Generates new elements by extrusion of the given elements and nodes along the path.
4000 # The path of extrusion must be a meshed edge.
4001 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4002 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4003 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4004 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4005 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4006 # contains not only path segments, else it can be None
4007 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4008 # @param HasAngles allows the shape to be rotated around the path
4009 # to get the resulting mesh in a helical fashion
4010 # @param Angles list of angles
4011 # @param LinearVariation forces the computation of rotation angles as linear
4012 # variation of the given Angles along path steps
4013 # @param HasRefPoint allows using the reference point
4014 # @param RefPoint the point around which the shape is rotated (the mass center of the
4015 # shape by default). The User can specify any point as the Reference Point.
4016 # @param MakeGroups forces the generation of new groups from existing ones
4017 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4018 # @ingroup l2_modif_extrurev
4019 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4020 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4021 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4022 unRegister = genObjUnRegister()
4023 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4024 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4025 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4027 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4028 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4029 if isinstance( RefPoint, list ):
4030 if not RefPoint: RefPoint = [0,0,0]
4031 RefPoint = SMESH.PointStruct( *RefPoint )
4032 if isinstance( PathMesh, Mesh ):
4033 PathMesh = PathMesh.GetMesh()
4034 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4035 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4036 self.mesh.SetParameters(Parameters)
4037 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4038 PathMesh, PathShape, NodeStart,
4039 HasAngles, Angles, LinearVariation,
4040 HasRefPoint, RefPoint, MakeGroups)
4042 ## Generates new elements by extrusion of the given elements
4043 # The path of extrusion must be a meshed edge.
4044 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4045 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4046 # @param NodeStart the start node from Path. Defines the direction of extrusion
4047 # @param HasAngles allows the shape to be rotated around the path
4048 # to get the resulting mesh in a helical fashion
4049 # @param Angles list of angles in radians
4050 # @param LinearVariation forces the computation of rotation angles as linear
4051 # variation of the given Angles along path steps
4052 # @param HasRefPoint allows using the reference point
4053 # @param RefPoint the point around which the elements are rotated (the mass
4054 # center of the elements by default).
4055 # The User can specify any point as the Reference Point.
4056 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4057 # @param MakeGroups forces the generation of new groups from existing ones
4058 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4059 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4060 # only SMESH::Extrusion_Error otherwise
4061 # @ingroup l2_modif_extrurev
4062 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4063 HasAngles=False, Angles=[], LinearVariation=False,
4064 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4065 ElemType=SMESH.FACE):
4067 if ElemType == SMESH.NODE: n = Base
4068 if ElemType == SMESH.EDGE: e = Base
4069 if ElemType == SMESH.FACE: f = Base
4070 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4071 HasAngles, Angles, LinearVariation,
4072 HasRefPoint, RefPoint, MakeGroups)
4073 if MakeGroups: return gr,er
4076 ## Generates new elements by extrusion of the given elements
4077 # The path of extrusion must be a meshed edge.
4078 # @param IDsOfElements ids of elements
4079 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4080 # @param PathShape shape(edge) defines the sub-mesh for the path
4081 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4082 # @param HasAngles allows the shape to be rotated around the path
4083 # to get the resulting mesh in a helical fashion
4084 # @param Angles list of angles in radians
4085 # @param HasRefPoint allows using the reference point
4086 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4087 # The User can specify any point as the Reference Point.
4088 # @param MakeGroups forces the generation of new groups from existing ones
4089 # @param LinearVariation forces the computation of rotation angles as linear
4090 # variation of the given Angles along path steps
4091 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4092 # only SMESH::Extrusion_Error otherwise
4093 # @ingroup l2_modif_extrurev
4094 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4095 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4096 MakeGroups=False, LinearVariation=False):
4097 n,e,f = [],IDsOfElements,IDsOfElements
4098 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4099 NodeStart, HasAngles, Angles,
4101 HasRefPoint, RefPoint, MakeGroups)
4102 if MakeGroups: return gr,er
4105 ## Generates new elements by extrusion of the elements which belong to the object
4106 # The path of extrusion must be a meshed edge.
4107 # @param theObject the object whose elements should be processed.
4108 # It can be a mesh, a sub-mesh or a group.
4109 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4110 # @param PathShape shape(edge) defines the sub-mesh for the path
4111 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4112 # @param HasAngles allows the shape to be rotated around the path
4113 # to get the resulting mesh in a helical fashion
4114 # @param Angles list of angles
4115 # @param HasRefPoint allows using the reference point
4116 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4117 # The User can specify any point as the Reference Point.
4118 # @param MakeGroups forces the generation of new groups from existing ones
4119 # @param LinearVariation forces the computation of rotation angles as linear
4120 # variation of the given Angles along path steps
4121 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4122 # only SMESH::Extrusion_Error otherwise
4123 # @ingroup l2_modif_extrurev
4124 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4125 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4126 MakeGroups=False, LinearVariation=False):
4127 n,e,f = [],theObject,theObject
4128 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4129 HasAngles, Angles, LinearVariation,
4130 HasRefPoint, RefPoint, MakeGroups)
4131 if MakeGroups: return gr,er
4134 ## Generates new elements by extrusion of mesh segments which belong to the object
4135 # The path of extrusion must be a meshed edge.
4136 # @param theObject the object whose 1D elements should be processed.
4137 # It can be a mesh, a sub-mesh or a group.
4138 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4139 # @param PathShape shape(edge) defines the sub-mesh for the path
4140 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4141 # @param HasAngles allows the shape to be rotated around the path
4142 # to get the resulting mesh in a helical fashion
4143 # @param Angles list of angles
4144 # @param HasRefPoint allows using the reference point
4145 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4146 # The User can specify any point as the Reference Point.
4147 # @param MakeGroups forces the generation of new groups from existing ones
4148 # @param LinearVariation forces the computation of rotation angles as linear
4149 # variation of the given Angles along path steps
4150 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4151 # only SMESH::Extrusion_Error otherwise
4152 # @ingroup l2_modif_extrurev
4153 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4154 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4155 MakeGroups=False, LinearVariation=False):
4156 n,e,f = [],theObject,[]
4157 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4158 HasAngles, Angles, LinearVariation,
4159 HasRefPoint, RefPoint, MakeGroups)
4160 if MakeGroups: return gr,er
4163 ## Generates new elements by extrusion of faces which belong to the object
4164 # The path of extrusion must be a meshed edge.
4165 # @param theObject the object whose 2D elements should be processed.
4166 # It can be a mesh, a sub-mesh or a group.
4167 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4168 # @param PathShape shape(edge) defines the sub-mesh for the path
4169 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4170 # @param HasAngles allows the shape to be rotated around the path
4171 # to get the resulting mesh in a helical fashion
4172 # @param Angles list of angles
4173 # @param HasRefPoint allows using the reference point
4174 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4175 # The User can specify any point as the Reference Point.
4176 # @param MakeGroups forces the generation of new groups from existing ones
4177 # @param LinearVariation forces the computation of rotation angles as linear
4178 # variation of the given Angles along path steps
4179 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4180 # only SMESH::Extrusion_Error otherwise
4181 # @ingroup l2_modif_extrurev
4182 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4183 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4184 MakeGroups=False, LinearVariation=False):
4185 n,e,f = [],[],theObject
4186 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4187 HasAngles, Angles, LinearVariation,
4188 HasRefPoint, RefPoint, MakeGroups)
4189 if MakeGroups: return gr,er
4192 ## Creates a symmetrical copy of mesh elements
4193 # @param IDsOfElements list of elements ids
4194 # @param Mirror is AxisStruct or geom object(point, line, plane)
4195 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4196 # If the Mirror is a geom object this parameter is unnecessary
4197 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4198 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4199 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4200 # @ingroup l2_modif_trsf
4201 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4202 if IDsOfElements == []:
4203 IDsOfElements = self.GetElementsId()
4204 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4205 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4206 theMirrorType = Mirror._mirrorType
4208 self.mesh.SetParameters(Mirror.parameters)
4209 if Copy and MakeGroups:
4210 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4211 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4214 ## Creates a new mesh by a symmetrical copy of mesh elements
4215 # @param IDsOfElements the list of elements ids
4216 # @param Mirror is AxisStruct or geom object (point, line, plane)
4217 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4218 # If the Mirror is a geom object this parameter is unnecessary
4219 # @param MakeGroups to generate new groups from existing ones
4220 # @param NewMeshName a name of the new mesh to create
4221 # @return instance of Mesh class
4222 # @ingroup l2_modif_trsf
4223 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4224 if IDsOfElements == []:
4225 IDsOfElements = self.GetElementsId()
4226 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4227 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4228 theMirrorType = Mirror._mirrorType
4230 self.mesh.SetParameters(Mirror.parameters)
4231 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4232 MakeGroups, NewMeshName)
4233 return Mesh(self.smeshpyD,self.geompyD,mesh)
4235 ## Creates a symmetrical copy of the object
4236 # @param theObject mesh, submesh or group
4237 # @param Mirror AxisStruct or geom object (point, line, plane)
4238 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4239 # If the Mirror is a geom object this parameter is unnecessary
4240 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4241 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4242 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4243 # @ingroup l2_modif_trsf
4244 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4245 if ( isinstance( theObject, Mesh )):
4246 theObject = theObject.GetMesh()
4247 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4248 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4249 theMirrorType = Mirror._mirrorType
4251 self.mesh.SetParameters(Mirror.parameters)
4252 if Copy and MakeGroups:
4253 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4254 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4257 ## Creates a new mesh by a symmetrical copy of the object
4258 # @param theObject mesh, submesh or group
4259 # @param Mirror AxisStruct or geom object (point, line, plane)
4260 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4261 # If the Mirror is a geom object this parameter is unnecessary
4262 # @param MakeGroups forces the generation of new groups from existing ones
4263 # @param NewMeshName the name of the new mesh to create
4264 # @return instance of Mesh class
4265 # @ingroup l2_modif_trsf
4266 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4267 if ( isinstance( theObject, Mesh )):
4268 theObject = theObject.GetMesh()
4269 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4270 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4271 theMirrorType = Mirror._mirrorType
4273 self.mesh.SetParameters(Mirror.parameters)
4274 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4275 MakeGroups, NewMeshName)
4276 return Mesh( self.smeshpyD,self.geompyD,mesh )
4278 ## Translates the elements
4279 # @param IDsOfElements list of elements ids
4280 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4281 # @param Copy allows copying the translated elements
4282 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4283 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4284 # @ingroup l2_modif_trsf
4285 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4286 if IDsOfElements == []:
4287 IDsOfElements = self.GetElementsId()
4288 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4289 Vector = self.smeshpyD.GetDirStruct(Vector)
4290 if isinstance( Vector, list ):
4291 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4292 self.mesh.SetParameters(Vector.PS.parameters)
4293 if Copy and MakeGroups:
4294 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4295 self.editor.Translate(IDsOfElements, Vector, Copy)
4298 ## Creates a new mesh of translated elements
4299 # @param IDsOfElements list of elements ids
4300 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4301 # @param MakeGroups forces the generation of new groups from existing ones
4302 # @param NewMeshName the name of the newly created mesh
4303 # @return instance of Mesh class
4304 # @ingroup l2_modif_trsf
4305 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4306 if IDsOfElements == []:
4307 IDsOfElements = self.GetElementsId()
4308 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4309 Vector = self.smeshpyD.GetDirStruct(Vector)
4310 if isinstance( Vector, list ):
4311 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4312 self.mesh.SetParameters(Vector.PS.parameters)
4313 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4314 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4316 ## Translates the object
4317 # @param theObject the object to translate (mesh, submesh, or group)
4318 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4319 # @param Copy allows copying the translated elements
4320 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4321 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4322 # @ingroup l2_modif_trsf
4323 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4324 if ( isinstance( theObject, Mesh )):
4325 theObject = theObject.GetMesh()
4326 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4327 Vector = self.smeshpyD.GetDirStruct(Vector)
4328 if isinstance( Vector, list ):
4329 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4330 self.mesh.SetParameters(Vector.PS.parameters)
4331 if Copy and MakeGroups:
4332 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4333 self.editor.TranslateObject(theObject, Vector, Copy)
4336 ## Creates a new mesh from the translated object
4337 # @param theObject the object to translate (mesh, submesh, or group)
4338 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4339 # @param MakeGroups forces the generation of new groups from existing ones
4340 # @param NewMeshName the name of the newly created mesh
4341 # @return instance of Mesh class
4342 # @ingroup l2_modif_trsf
4343 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4344 if isinstance( theObject, Mesh ):
4345 theObject = theObject.GetMesh()
4346 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4347 Vector = self.smeshpyD.GetDirStruct(Vector)
4348 if isinstance( Vector, list ):
4349 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4350 self.mesh.SetParameters(Vector.PS.parameters)
4351 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4352 return Mesh( self.smeshpyD, self.geompyD, mesh )
4356 ## Scales the object
4357 # @param theObject - the object to translate (mesh, submesh, or group)
4358 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4359 # @param theScaleFact - list of 1-3 scale factors for axises
4360 # @param Copy - allows copying the translated elements
4361 # @param MakeGroups - forces the generation of new groups from existing
4363 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4364 # empty list otherwise
4365 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4366 unRegister = genObjUnRegister()
4367 if ( isinstance( theObject, Mesh )):
4368 theObject = theObject.GetMesh()
4369 if ( isinstance( theObject, list )):
4370 theObject = self.GetIDSource(theObject, SMESH.ALL)
4371 unRegister.set( theObject )
4372 if ( isinstance( thePoint, list )):
4373 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4374 if ( isinstance( theScaleFact, float )):
4375 theScaleFact = [theScaleFact]
4376 if ( isinstance( theScaleFact, int )):
4377 theScaleFact = [ float(theScaleFact)]
4379 self.mesh.SetParameters(thePoint.parameters)
4381 if Copy and MakeGroups:
4382 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4383 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4386 ## Creates a new mesh from the translated object
4387 # @param theObject - the object to translate (mesh, submesh, or group)
4388 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4389 # @param theScaleFact - list of 1-3 scale factors for axises
4390 # @param MakeGroups - forces the generation of new groups from existing ones
4391 # @param NewMeshName - the name of the newly created mesh
4392 # @return instance of Mesh class
4393 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4394 unRegister = genObjUnRegister()
4395 if (isinstance(theObject, Mesh)):
4396 theObject = theObject.GetMesh()
4397 if ( isinstance( theObject, list )):
4398 theObject = self.GetIDSource(theObject,SMESH.ALL)
4399 unRegister.set( theObject )
4400 if ( isinstance( thePoint, list )):
4401 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4402 if ( isinstance( theScaleFact, float )):
4403 theScaleFact = [theScaleFact]
4404 if ( isinstance( theScaleFact, int )):
4405 theScaleFact = [ float(theScaleFact)]
4407 self.mesh.SetParameters(thePoint.parameters)
4408 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4409 MakeGroups, NewMeshName)
4410 return Mesh( self.smeshpyD, self.geompyD, mesh )
4414 ## Rotates the elements
4415 # @param IDsOfElements list of elements ids
4416 # @param Axis the axis of rotation (AxisStruct or geom line)
4417 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4418 # @param Copy allows copying the rotated elements
4419 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4420 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4421 # @ingroup l2_modif_trsf
4422 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4423 if IDsOfElements == []:
4424 IDsOfElements = self.GetElementsId()
4425 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4426 Axis = self.smeshpyD.GetAxisStruct(Axis)
4427 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4428 Parameters = Axis.parameters + var_separator + Parameters
4429 self.mesh.SetParameters(Parameters)
4430 if Copy and MakeGroups:
4431 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4432 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4435 ## Creates a new mesh of rotated elements
4436 # @param IDsOfElements list of element ids
4437 # @param Axis the axis of rotation (AxisStruct or geom line)
4438 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4439 # @param MakeGroups forces the generation of new groups from existing ones
4440 # @param NewMeshName the name of the newly created mesh
4441 # @return instance of Mesh class
4442 # @ingroup l2_modif_trsf
4443 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4444 if IDsOfElements == []:
4445 IDsOfElements = self.GetElementsId()
4446 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4447 Axis = self.smeshpyD.GetAxisStruct(Axis)
4448 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4449 Parameters = Axis.parameters + var_separator + Parameters
4450 self.mesh.SetParameters(Parameters)
4451 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4452 MakeGroups, NewMeshName)
4453 return Mesh( self.smeshpyD, self.geompyD, mesh )
4455 ## Rotates the object
4456 # @param theObject the object to rotate( mesh, submesh, or group)
4457 # @param Axis the axis of rotation (AxisStruct or geom line)
4458 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4459 # @param Copy allows copying the rotated elements
4460 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4461 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4462 # @ingroup l2_modif_trsf
4463 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4464 if (isinstance(theObject, Mesh)):
4465 theObject = theObject.GetMesh()
4466 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4467 Axis = self.smeshpyD.GetAxisStruct(Axis)
4468 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4469 Parameters = Axis.parameters + ":" + Parameters
4470 self.mesh.SetParameters(Parameters)
4471 if Copy and MakeGroups:
4472 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4473 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4476 ## Creates a new mesh from the rotated object
4477 # @param theObject the object to rotate (mesh, submesh, or group)
4478 # @param Axis the axis of rotation (AxisStruct or geom line)
4479 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4480 # @param MakeGroups forces the generation of new groups from existing ones
4481 # @param NewMeshName the name of the newly created mesh
4482 # @return instance of Mesh class
4483 # @ingroup l2_modif_trsf
4484 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4485 if (isinstance( theObject, Mesh )):
4486 theObject = theObject.GetMesh()
4487 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4488 Axis = self.smeshpyD.GetAxisStruct(Axis)
4489 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4490 Parameters = Axis.parameters + ":" + Parameters
4491 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4492 MakeGroups, NewMeshName)
4493 self.mesh.SetParameters(Parameters)
4494 return Mesh( self.smeshpyD, self.geompyD, mesh )
4496 ## Finds groups of adjacent nodes within Tolerance.
4497 # @param Tolerance the value of tolerance
4498 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4499 # corner and medium nodes in separate groups thus preventing
4500 # their further merge.
4501 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4502 # @ingroup l2_modif_trsf
4503 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4504 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4506 ## Finds groups of ajacent nodes within Tolerance.
4507 # @param Tolerance the value of tolerance
4508 # @param SubMeshOrGroup SubMesh, Group or Filter
4509 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4510 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4511 # corner and medium nodes in separate groups thus preventing
4512 # their further merge.
4513 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4514 # @ingroup l2_modif_trsf
4515 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4516 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4517 unRegister = genObjUnRegister()
4518 if (isinstance( SubMeshOrGroup, Mesh )):
4519 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4520 if not isinstance( exceptNodes, list ):
4521 exceptNodes = [ exceptNodes ]
4522 if exceptNodes and isinstance( exceptNodes[0], int ):
4523 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4524 unRegister.set( exceptNodes )
4525 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4526 exceptNodes, SeparateCornerAndMediumNodes)
4529 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4530 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4531 # by nodes 1 and 25 correspondingly in all elements and groups
4532 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4533 # If @a NodesToKeep does not include a node to keep for some group to merge,
4534 # then the first node in the group is kept.
4535 # @ingroup l2_modif_trsf
4536 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4537 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4538 self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4540 ## Finds the elements built on the same nodes.
4541 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4542 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4543 # @ingroup l2_modif_trsf
4544 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4545 if not MeshOrSubMeshOrGroup:
4546 MeshOrSubMeshOrGroup=self.mesh
4547 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4548 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4549 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4551 ## Merges elements in each given group.
4552 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4553 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4554 # replaced by elements 1 and 25 in all groups)
4555 # @ingroup l2_modif_trsf
4556 def MergeElements(self, GroupsOfElementsID):
4557 self.editor.MergeElements(GroupsOfElementsID)
4559 ## Leaves one element and removes all other elements built on the same nodes.
4560 # @ingroup l2_modif_trsf
4561 def MergeEqualElements(self):
4562 self.editor.MergeEqualElements()
4564 ## Returns groups of FreeBorder's coincident within the given tolerance.
4565 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4566 # size of elements adjacent to free borders being compared is used.
4567 # @return SMESH.CoincidentFreeBorders structure
4568 # @ingroup l2_modif_trsf
4569 def FindCoincidentFreeBorders (self, tolerance=0.):
4570 return self.editor.FindCoincidentFreeBorders( tolerance )
4572 ## Sew FreeBorder's of each group
4573 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4574 # where each enclosed list contains node IDs of a group of coincident free
4575 # borders such that each consequent triple of IDs within a group describes
4576 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4577 # last node of a border.
4578 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4579 # groups of coincident free borders, each group including two borders.
4580 # @param createPolygons if @c True faces adjacent to free borders are converted to
4581 # polygons if a node of opposite border falls on a face edge, else such
4582 # faces are split into several ones.
4583 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4584 # polyhedra if a node of opposite border falls on a volume edge, else such
4585 # volumes, if any, remain intact and the mesh becomes non-conformal.
4586 # @return a number of successfully sewed groups
4587 # @ingroup l2_modif_trsf
4588 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4589 if freeBorders and isinstance( freeBorders, list ):
4590 # construct SMESH.CoincidentFreeBorders
4591 if isinstance( freeBorders[0], int ):
4592 freeBorders = [freeBorders]
4594 coincidentGroups = []
4595 for nodeList in freeBorders:
4596 if not nodeList or len( nodeList ) % 3:
4597 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4600 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4601 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4602 nodeList = nodeList[3:]
4604 coincidentGroups.append( group )
4606 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4608 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4610 ## Sews free borders
4611 # @return SMESH::Sew_Error
4612 # @ingroup l2_modif_trsf
4613 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4614 FirstNodeID2, SecondNodeID2, LastNodeID2,
4615 CreatePolygons, CreatePolyedrs):
4616 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4617 FirstNodeID2, SecondNodeID2, LastNodeID2,
4618 CreatePolygons, CreatePolyedrs)
4620 ## Sews conform free borders
4621 # @return SMESH::Sew_Error
4622 # @ingroup l2_modif_trsf
4623 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4624 FirstNodeID2, SecondNodeID2):
4625 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4626 FirstNodeID2, SecondNodeID2)
4628 ## Sews border to side
4629 # @return SMESH::Sew_Error
4630 # @ingroup l2_modif_trsf
4631 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4632 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4633 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4634 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4636 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4637 # merged with the nodes of elements of Side2.
4638 # The number of elements in theSide1 and in theSide2 must be
4639 # equal and they should have similar nodal connectivity.
4640 # The nodes to merge should belong to side borders and
4641 # the first node should be linked to the second.
4642 # @return SMESH::Sew_Error
4643 # @ingroup l2_modif_trsf
4644 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4645 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4646 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4647 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4648 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4649 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4651 ## Sets new nodes for the given element.
4652 # @param ide the element id
4653 # @param newIDs nodes ids
4654 # @return If the number of nodes does not correspond to the type of element - returns false
4655 # @ingroup l2_modif_edit
4656 def ChangeElemNodes(self, ide, newIDs):
4657 return self.editor.ChangeElemNodes(ide, newIDs)
4659 ## If during the last operation of MeshEditor some nodes were
4660 # created, this method returns the list of their IDs, \n
4661 # if new nodes were not created - returns empty list
4662 # @return the list of integer values (can be empty)
4663 # @ingroup l1_auxiliary
4664 def GetLastCreatedNodes(self):
4665 return self.editor.GetLastCreatedNodes()
4667 ## If during the last operation of MeshEditor some elements were
4668 # created this method returns the list of their IDs, \n
4669 # if new elements were not created - returns empty list
4670 # @return the list of integer values (can be empty)
4671 # @ingroup l1_auxiliary
4672 def GetLastCreatedElems(self):
4673 return self.editor.GetLastCreatedElems()
4675 ## Clears sequences of nodes and elements created by mesh edition oparations
4676 # @ingroup l1_auxiliary
4677 def ClearLastCreated(self):
4678 self.editor.ClearLastCreated()
4680 ## Creates duplicates of given elements, i.e. creates new elements based on the
4681 # same nodes as the given ones.
4682 # @param theElements - container of elements to duplicate. It can be a Mesh,
4683 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4684 # a Mesh, elements of highest dimension are duplicated
4685 # @param theGroupName - a name of group to contain the generated elements.
4686 # If a group with such a name already exists, the new elements
4687 # are added to the existng group, else a new group is created.
4688 # If \a theGroupName is empty, new elements are not added
4690 # @return a group where the new elements are added. None if theGroupName == "".
4691 # @ingroup l2_modif_edit
4692 def DoubleElements(self, theElements, theGroupName=""):
4693 unRegister = genObjUnRegister()
4694 if isinstance( theElements, Mesh ):
4695 theElements = theElements.mesh
4696 elif isinstance( theElements, list ):
4697 theElements = self.GetIDSource( theElements, SMESH.ALL )
4698 unRegister.set( theElements )
4699 return self.editor.DoubleElements(theElements, theGroupName)
4701 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4702 # @param theNodes identifiers of nodes to be doubled
4703 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4704 # nodes. If list of element identifiers is empty then nodes are doubled but
4705 # they not assigned to elements
4706 # @return TRUE if operation has been completed successfully, FALSE otherwise
4707 # @ingroup l2_modif_edit
4708 def DoubleNodes(self, theNodes, theModifiedElems):
4709 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4711 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4712 # This method provided for convenience works as DoubleNodes() described above.
4713 # @param theNodeId identifiers of node to be doubled
4714 # @param theModifiedElems identifiers of elements to be updated
4715 # @return TRUE if operation has been completed successfully, FALSE otherwise
4716 # @ingroup l2_modif_edit
4717 def DoubleNode(self, theNodeId, theModifiedElems):
4718 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4720 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4721 # This method provided for convenience works as DoubleNodes() described above.
4722 # @param theNodes group of nodes to be doubled
4723 # @param theModifiedElems group of elements to be updated.
4724 # @param theMakeGroup forces the generation of a group containing new nodes.
4725 # @return TRUE or a created group if operation has been completed successfully,
4726 # FALSE or None otherwise
4727 # @ingroup l2_modif_edit
4728 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4730 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4731 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4733 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4734 # This method provided for convenience works as DoubleNodes() described above.
4735 # @param theNodes list of groups of nodes to be doubled
4736 # @param theModifiedElems list of groups of elements to be updated.
4737 # @param theMakeGroup forces the generation of a group containing new nodes.
4738 # @return TRUE if operation has been completed successfully, FALSE otherwise
4739 # @ingroup l2_modif_edit
4740 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4742 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4743 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4745 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4746 # @param theElems - the list of elements (edges or faces) to be replicated
4747 # The nodes for duplication could be found from these elements
4748 # @param theNodesNot - list of nodes to NOT replicate
4749 # @param theAffectedElems - the list of elements (cells and edges) to which the
4750 # replicated nodes should be associated to.
4751 # @return TRUE if operation has been completed successfully, FALSE otherwise
4752 # @ingroup l2_modif_edit
4753 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4754 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4756 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4757 # @param theElems - the list of elements (edges or faces) to be replicated
4758 # The nodes for duplication could be found from these elements
4759 # @param theNodesNot - list of nodes to NOT replicate
4760 # @param theShape - shape to detect affected elements (element which geometric center
4761 # located on or inside shape).
4762 # The replicated nodes should be associated to affected elements.
4763 # @return TRUE if operation has been completed successfully, FALSE otherwise
4764 # @ingroup l2_modif_edit
4765 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4766 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4768 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4769 # This method provided for convenience works as DoubleNodes() described above.
4770 # @param theElems - group of of elements (edges or faces) to be replicated
4771 # @param theNodesNot - group of nodes not to replicated
4772 # @param theAffectedElems - group of elements to which the replicated nodes
4773 # should be associated to.
4774 # @param theMakeGroup forces the generation of a group containing new elements.
4775 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4776 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4777 # FALSE or None otherwise
4778 # @ingroup l2_modif_edit
4779 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4780 theMakeGroup=False, theMakeNodeGroup=False):
4781 if theMakeGroup or theMakeNodeGroup:
4782 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4784 theMakeGroup, theMakeNodeGroup)
4785 if theMakeGroup and theMakeNodeGroup:
4788 return twoGroups[ int(theMakeNodeGroup) ]
4789 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4791 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4792 # This method provided for convenience works as DoubleNodes() described above.
4793 # @param theElems - group of of elements (edges or faces) to be replicated
4794 # @param theNodesNot - group of nodes not to replicated
4795 # @param theShape - shape to detect affected elements (element which geometric center
4796 # located on or inside shape).
4797 # The replicated nodes should be associated to affected elements.
4798 # @ingroup l2_modif_edit
4799 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4800 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4802 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4803 # This method provided for convenience works as DoubleNodes() described above.
4804 # @param theElems - list of groups of elements (edges or faces) to be replicated
4805 # @param theNodesNot - list of groups of nodes not to replicated
4806 # @param theAffectedElems - group of elements to which the replicated nodes
4807 # should be associated to.
4808 # @param theMakeGroup forces the generation of a group containing new elements.
4809 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4810 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4811 # FALSE or None otherwise
4812 # @ingroup l2_modif_edit
4813 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4814 theMakeGroup=False, theMakeNodeGroup=False):
4815 if theMakeGroup or theMakeNodeGroup:
4816 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4818 theMakeGroup, theMakeNodeGroup)
4819 if theMakeGroup and theMakeNodeGroup:
4822 return twoGroups[ int(theMakeNodeGroup) ]
4823 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4825 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4826 # This method provided for convenience works as DoubleNodes() described above.
4827 # @param theElems - list of groups of elements (edges or faces) to be replicated
4828 # @param theNodesNot - list of groups of nodes not to replicated
4829 # @param theShape - shape to detect affected elements (element which geometric center
4830 # located on or inside shape).
4831 # The replicated nodes should be associated to affected elements.
4832 # @return TRUE if operation has been completed successfully, FALSE otherwise
4833 # @ingroup l2_modif_edit
4834 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4835 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4837 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4838 # This method is the first step of DoubleNodeElemGroupsInRegion.
4839 # @param theElems - list of groups of elements (edges or faces) to be replicated
4840 # @param theNodesNot - list of groups of nodes not to replicated
4841 # @param theShape - shape to detect affected elements (element which geometric center
4842 # located on or inside shape).
4843 # The replicated nodes should be associated to affected elements.
4844 # @return groups of affected elements
4845 # @ingroup l2_modif_edit
4846 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4847 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4849 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4850 # The list of groups must describe a partition of the mesh volumes.
4851 # The nodes of the internal faces at the boundaries of the groups are doubled.
4852 # In option, the internal faces are replaced by flat elements.
4853 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4854 # @param theDomains - list of groups of volumes
4855 # @param createJointElems - if TRUE, create the elements
4856 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4857 # the boundary between \a theDomains and the rest mesh
4858 # @return TRUE if operation has been completed successfully, FALSE otherwise
4859 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4860 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4862 ## Double nodes on some external faces and create flat elements.
4863 # Flat elements are mainly used by some types of mechanic calculations.
4865 # Each group of the list must be constituted of faces.
4866 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4867 # @param theGroupsOfFaces - list of groups of faces
4868 # @return TRUE if operation has been completed successfully, FALSE otherwise
4869 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4870 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4872 ## identify all the elements around a geom shape, get the faces delimiting the hole
4874 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4875 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4877 def _getFunctor(self, funcType ):
4878 fn = self.functors[ funcType._v ]
4880 fn = self.smeshpyD.GetFunctor(funcType)
4881 fn.SetMesh(self.mesh)
4882 self.functors[ funcType._v ] = fn
4885 ## Returns value of a functor for a given element
4886 # @param funcType an item of SMESH.FunctorType enum
4887 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4888 # @param elemId element or node ID
4889 # @param isElem @a elemId is ID of element or node
4890 # @return the functor value or zero in case of invalid arguments
4891 def FunctorValue(self, funcType, elemId, isElem=True):
4892 fn = self._getFunctor( funcType )
4893 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4894 val = fn.GetValue(elemId)
4899 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4900 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4901 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4902 # @ingroup l1_measurements
4903 def GetLength(self, elemId=None):
4906 length = self.smeshpyD.GetLength(self)
4908 length = self.FunctorValue(SMESH.FT_Length, elemId)
4911 ## Get area of 2D element or sum of areas of all 2D mesh elements
4912 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4913 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4914 # @ingroup l1_measurements
4915 def GetArea(self, elemId=None):
4918 area = self.smeshpyD.GetArea(self)
4920 area = self.FunctorValue(SMESH.FT_Area, elemId)
4923 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4924 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4925 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4926 # @ingroup l1_measurements
4927 def GetVolume(self, elemId=None):
4930 volume = self.smeshpyD.GetVolume(self)
4932 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4935 ## Get maximum element length.
4936 # @param elemId mesh element ID
4937 # @return element's maximum length value
4938 # @ingroup l1_measurements
4939 def GetMaxElementLength(self, elemId):
4940 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4941 ftype = SMESH.FT_MaxElementLength3D
4943 ftype = SMESH.FT_MaxElementLength2D
4944 return self.FunctorValue(ftype, elemId)
4946 ## Get aspect ratio of 2D or 3D element.
4947 # @param elemId mesh element ID
4948 # @return element's aspect ratio value
4949 # @ingroup l1_measurements
4950 def GetAspectRatio(self, elemId):
4951 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4952 ftype = SMESH.FT_AspectRatio3D
4954 ftype = SMESH.FT_AspectRatio
4955 return self.FunctorValue(ftype, elemId)
4957 ## Get warping angle of 2D element.
4958 # @param elemId mesh element ID
4959 # @return element's warping angle value
4960 # @ingroup l1_measurements
4961 def GetWarping(self, elemId):
4962 return self.FunctorValue(SMESH.FT_Warping, elemId)
4964 ## Get minimum angle of 2D element.
4965 # @param elemId mesh element ID
4966 # @return element's minimum angle value
4967 # @ingroup l1_measurements
4968 def GetMinimumAngle(self, elemId):
4969 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4971 ## Get taper of 2D element.
4972 # @param elemId mesh element ID
4973 # @return element's taper value
4974 # @ingroup l1_measurements
4975 def GetTaper(self, elemId):
4976 return self.FunctorValue(SMESH.FT_Taper, elemId)
4978 ## Get skew of 2D element.
4979 # @param elemId mesh element ID
4980 # @return element's skew value
4981 # @ingroup l1_measurements
4982 def GetSkew(self, elemId):
4983 return self.FunctorValue(SMESH.FT_Skew, elemId)
4985 ## Return minimal and maximal value of a given functor.
4986 # @param funType a functor type, an item of SMESH.FunctorType enum
4987 # (one of SMESH.FunctorType._items)
4988 # @param meshPart a part of mesh (group, sub-mesh) to treat
4989 # @return tuple (min,max)
4990 # @ingroup l1_measurements
4991 def GetMinMax(self, funType, meshPart=None):
4992 unRegister = genObjUnRegister()
4993 if isinstance( meshPart, list ):
4994 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4995 unRegister.set( meshPart )
4996 if isinstance( meshPart, Mesh ):
4997 meshPart = meshPart.mesh
4998 fun = self._getFunctor( funType )
5001 if hasattr( meshPart, "SetMesh" ):
5002 meshPart.SetMesh( self.mesh ) # set mesh to filter
5003 hist = fun.GetLocalHistogram( 1, False, meshPart )
5005 hist = fun.GetHistogram( 1, False )
5007 return hist[0].min, hist[0].max
5010 pass # end of Mesh class
5013 ## Class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5014 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5016 class meshProxy(SMESH._objref_SMESH_Mesh):
5018 SMESH._objref_SMESH_Mesh.__init__(self)
5019 def __deepcopy__(self, memo=None):
5020 new = self.__class__()
5022 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5023 if len( args ) == 3:
5024 args += SMESH.ALL_NODES, True
5025 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5027 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5030 ## Class wrapping SMESH_SubMesh in order to add Compute()
5032 class submeshProxy(SMESH._objref_SMESH_subMesh):
5034 SMESH._objref_SMESH_subMesh.__init__(self)
5036 def __deepcopy__(self, memo=None):
5037 new = self.__class__()
5040 ## Computes the sub-mesh and returns the status of the computation
5041 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5042 # @return True or False
5043 # @ingroup l2_construct
5044 def Compute(self,refresh=False):
5046 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5048 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5050 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5051 smeshgui = salome.ImportComponentGUI("SMESH")
5052 smeshgui.Init(self.mesh.GetStudyId())
5053 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5054 if refresh: salome.sg.updateObjBrowser(1)
5059 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5062 ## Class used to compensate change of CORBA API of SMESH_MeshEditor for backward compatibility
5063 # with old dump scripts which call SMESH_MeshEditor directly and not via smeshBuilder.Mesh
5065 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5067 SMESH._objref_SMESH_MeshEditor.__init__(self)
5069 def __getattr__(self, name ): # method called if an attribute not found
5070 if not self.mesh: # look for name() method in Mesh class
5071 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5072 if hasattr( self.mesh, name ):
5073 return getattr( self.mesh, name )
5074 if name == "ExtrusionAlongPathObjX":
5075 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5076 print "meshEditor: attribute '%s' NOT FOUND" % name
5078 def __deepcopy__(self, memo=None):
5079 new = self.__class__()
5081 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5082 if len( args ) == 1: args += False,
5083 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5084 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5085 if len( args ) == 2: args += False,
5086 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5087 def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
5088 if len( args ) == 1:
5089 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
5090 NodesToKeep = args[1]
5091 unRegister = genObjUnRegister()
5093 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5094 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5095 if not isinstance( NodesToKeep, list ):
5096 NodesToKeep = [ NodesToKeep ]
5097 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
5099 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5101 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
5103 class Pattern(SMESH._objref_SMESH_Pattern):
5105 def LoadFromFile(self, patternTextOrFile ):
5106 text = patternTextOrFile
5107 if os.path.exists( text ):
5108 text = open( patternTextOrFile ).read()
5110 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5112 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5113 decrFun = lambda i: i-1
5114 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5115 theMesh.SetParameters(Parameters)
5116 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5118 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5119 decrFun = lambda i: i-1
5120 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5121 theMesh.SetParameters(Parameters)
5122 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5124 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5125 if isinstance( mesh, Mesh ):
5126 mesh = mesh.GetMesh()
5127 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5129 # Registering the new proxy for Pattern
5130 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5132 ## Private class used to bind methods creating algorithms to the class Mesh
5137 self.defaultAlgoType = ""
5138 self.algoTypeToClass = {}
5140 # Stores a python class of algorithm
5141 def add(self, algoClass):
5142 if type( algoClass ).__name__ == 'classobj' and \
5143 hasattr( algoClass, "algoType"):
5144 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5145 if not self.defaultAlgoType and \
5146 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5147 self.defaultAlgoType = algoClass.algoType
5148 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5150 # creates a copy of self and assign mesh to the copy
5151 def copy(self, mesh):
5152 other = algoCreator()
5153 other.defaultAlgoType = self.defaultAlgoType
5154 other.algoTypeToClass = self.algoTypeToClass
5158 # creates an instance of algorithm
5159 def __call__(self,algo="",geom=0,*args):
5160 algoType = self.defaultAlgoType
5161 for arg in args + (algo,geom):
5162 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5164 if isinstance( arg, str ) and arg:
5166 if not algoType and self.algoTypeToClass:
5167 algoType = self.algoTypeToClass.keys()[0]
5168 if self.algoTypeToClass.has_key( algoType ):
5169 #print "Create algo",algoType
5170 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5171 raise RuntimeError, "No class found for algo type %s" % algoType
5174 ## Private class used to substitute and store variable parameters of hypotheses.
5176 class hypMethodWrapper:
5177 def __init__(self, hyp, method):
5179 self.method = method
5180 #print "REBIND:", method.__name__
5183 # call a method of hypothesis with calling SetVarParameter() before
5184 def __call__(self,*args):
5186 return self.method( self.hyp, *args ) # hypothesis method with no args
5188 #print "MethWrapper.__call__",self.method.__name__, args
5190 parsed = ParseParameters(*args) # replace variables with their values
5191 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5192 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5193 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5194 # maybe there is a replaced string arg which is not variable
5195 result = self.method( self.hyp, *args )
5196 except ValueError, detail: # raised by ParseParameters()
5198 result = self.method( self.hyp, *args )
5199 except omniORB.CORBA.BAD_PARAM:
5200 raise ValueError, detail # wrong variable name
5205 ## A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
5207 class genObjUnRegister:
5209 def __init__(self, genObj=None):
5210 self.genObjList = []
5214 def set(self, genObj):
5215 "Store one or a list of of SALOME.GenericObj'es"
5216 if isinstance( genObj, list ):
5217 self.genObjList.extend( genObj )
5219 self.genObjList.append( genObj )
5223 for genObj in self.genObjList:
5224 if genObj and hasattr( genObj, "UnRegister" ):
5228 ## Bind methods creating mesher plug-ins to the Mesh class
5230 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5232 #print "pluginName: ", pluginName
5233 pluginBuilderName = pluginName + "Builder"
5235 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5236 except Exception, e:
5237 from salome_utils import verbose
5238 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5240 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5241 plugin = eval( pluginBuilderName )
5242 #print " plugin:" , str(plugin)
5244 # add methods creating algorithms to Mesh
5245 for k in dir( plugin ):
5246 if k[0] == '_': continue
5247 algo = getattr( plugin, k )
5248 #print " algo:", str(algo)
5249 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5250 #print " meshMethod:" , str(algo.meshMethod)
5251 if not hasattr( Mesh, algo.meshMethod ):
5252 setattr( Mesh, algo.meshMethod, algoCreator() )
5254 getattr( Mesh, algo.meshMethod ).add( algo )