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