1 # Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
30 ## @defgroup l2_construct Constructing meshes
31 ## @defgroup l2_algorithms Defining Algorithms
33 ## @defgroup l3_algos_basic Basic meshing algorithms
34 ## @defgroup l3_algos_proj Projection Algorithms
35 ## @defgroup l3_algos_radialp Radial Prism
36 ## @defgroup l3_algos_segmarv Segments around Vertex
37 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
40 ## @defgroup l2_hypotheses Defining hypotheses
42 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ## @defgroup l3_hypos_additi Additional Hypotheses
49 ## @defgroup l2_submeshes Constructing submeshes
50 ## @defgroup l2_compounds Building Compounds
51 ## @defgroup l2_editing Editing Meshes
54 ## @defgroup l1_meshinfo Mesh Information
55 ## @defgroup l1_controls Quality controls and Filtering
56 ## @defgroup l1_grouping Grouping elements
58 ## @defgroup l2_grps_create Creating groups
59 ## @defgroup l2_grps_edit Editing groups
60 ## @defgroup l2_grps_operon Using operations on groups
61 ## @defgroup l2_grps_delete Deleting Groups
64 ## @defgroup l1_modifying Modifying meshes
66 ## @defgroup l2_modif_add Adding nodes and elements
67 ## @defgroup l2_modif_del Removing nodes and elements
68 ## @defgroup l2_modif_edit Modifying nodes and elements
69 ## @defgroup l2_modif_renumber Renumbering nodes and elements
70 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ## @defgroup l2_modif_movenode Moving nodes
72 ## @defgroup l2_modif_throughp Mesh through point
73 ## @defgroup l2_modif_invdiag Diagonal inversion of elements
74 ## @defgroup l2_modif_unitetri Uniting triangles
75 ## @defgroup l2_modif_changori Changing orientation of elements
76 ## @defgroup l2_modif_cutquadr Cutting elements
77 ## @defgroup l2_modif_smooth Smoothing
78 ## @defgroup l2_modif_extrurev Extrusion and Revolution
79 ## @defgroup l2_modif_patterns Pattern mapping
80 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
83 ## @defgroup l1_measurements Measurements
86 from salome.geom import geomBuilder
88 import SMESH # This is necessary for back compatibility
90 from salome.smesh.smesh_algorithm import Mesh_Algorithm
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
102 def __subclasscheck__(cls, sub):
103 """Implement issubclass(sub, cls)."""
104 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
106 ## @addtogroup l1_auxiliary
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
119 ## Return list of variable values from salome notebook.
120 # The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
132 if isinstance(parameter,str):
133 # check if there is an inexistent variable name
134 if not notebook.isVariable(parameter):
135 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136 parameter = notebook.get(parameter)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
154 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
159 SMESH.PointStruct.__init__ = __initPointStruct
161 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
166 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
167 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
169 SMESH.AxisStruct.__init__ = __initAxisStruct
171 smeshPrecisionConfusion = 1.e-07
172 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
173 if abs(val1 - val2) < tol:
183 if isinstance(obj, SALOMEDS._objref_SObject):
187 ior = salome.orb.object_to_string(obj)
192 studies = salome.myStudyManager.GetOpenStudies()
193 for sname in studies:
194 s = salome.myStudyManager.GetStudyByName(sname)
196 sobj = s.FindObjectIOR(ior)
197 if not sobj: continue
198 return sobj.GetName()
199 if hasattr(obj, "GetName"):
200 # unknown CORBA object, having GetName() method
203 # unknown CORBA object, no GetName() method
206 if hasattr(obj, "GetName"):
207 # unknown non-CORBA object, having GetName() method
210 raise RuntimeError, "Null or invalid object"
212 ## Prints error message if a hypothesis was not assigned.
213 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
215 hypType = "algorithm"
217 hypType = "hypothesis"
220 if hasattr( status, "__getitem__" ):
221 status,reason = status[0],status[1]
222 if status == HYP_UNKNOWN_FATAL :
223 reason = "for unknown reason"
224 elif status == HYP_INCOMPATIBLE :
225 reason = "this hypothesis mismatches the algorithm"
226 elif status == HYP_NOTCONFORM :
227 reason = "a non-conform mesh would be built"
228 elif status == HYP_ALREADY_EXIST :
229 if isAlgo: return # it does not influence anything
230 reason = hypType + " of the same dimension is already assigned to this shape"
231 elif status == HYP_BAD_DIM :
232 reason = hypType + " mismatches the shape"
233 elif status == HYP_CONCURENT :
234 reason = "there are concurrent hypotheses on sub-shapes"
235 elif status == HYP_BAD_SUBSHAPE :
236 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
237 elif status == HYP_BAD_GEOMETRY:
238 reason = "geometry mismatches the expectation of the algorithm"
239 elif status == HYP_HIDDEN_ALGO:
240 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
241 elif status == HYP_HIDING_ALGO:
242 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
243 elif status == HYP_NEED_SHAPE:
244 reason = "algorithm can't work without shape"
245 elif status == HYP_INCOMPAT_HYPS:
251 where = '"%s"' % geomName
253 meshName = GetName( mesh )
254 if meshName and meshName != NO_NAME:
255 where = '"%s" in "%s"' % ( geomName, meshName )
256 if status < HYP_UNKNOWN_FATAL and where:
257 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
259 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
261 print '"%s" was not assigned : %s' %( hypName, reason )
264 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
265 def AssureGeomPublished(mesh, geom, name=''):
266 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
268 if not geom.GetStudyEntry() and \
269 mesh.smeshpyD.GetCurrentStudy():
271 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
272 if studyID != mesh.geompyD.myStudyId:
273 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
275 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
276 # for all groups SubShapeName() returns "Compound_-1"
277 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
279 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
281 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
284 ## Return the first vertex of a geometrical edge by ignoring orientation
285 def FirstVertexOnCurve(mesh, edge):
286 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
288 raise TypeError, "Given object has no vertices"
289 if len( vv ) == 1: return vv[0]
290 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
291 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
292 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
293 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
296 dist1 += abs( xyz[i] - xyz1[i] )
297 dist2 += abs( xyz[i] - xyz2[i] )
303 # end of l1_auxiliary
307 # Warning: smeshInst is a singleton
313 ## This class allows to create, load or manipulate meshes
314 # It has a set of methods to create load or copy meshes, to combine several meshes.
315 # It also has methods to get infos on meshes.
316 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
318 # MirrorType enumeration
319 POINT = SMESH_MeshEditor.POINT
320 AXIS = SMESH_MeshEditor.AXIS
321 PLANE = SMESH_MeshEditor.PLANE
323 # Smooth_Method enumeration
324 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
325 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
327 PrecisionConfusion = smeshPrecisionConfusion
329 # TopAbs_State enumeration
330 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
332 # Methods of splitting a hexahedron into tetrahedra
333 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
339 #print "==== __new__", engine, smeshInst, doLcc
341 if smeshInst is None:
342 # smesh engine is either retrieved from engine, or created
344 # Following test avoids a recursive loop
346 if smeshInst is not None:
347 # smesh engine not created: existing engine found
351 # FindOrLoadComponent called:
352 # 1. CORBA resolution of server
353 # 2. the __new__ method is called again
354 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
355 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
357 # FindOrLoadComponent not called
358 if smeshInst is None:
359 # smeshBuilder instance is created from lcc.FindOrLoadComponent
360 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
361 smeshInst = super(smeshBuilder,cls).__new__(cls)
363 # smesh engine not created: existing engine found
364 #print "==== existing ", engine, smeshInst, doLcc
366 #print "====1 ", smeshInst
369 #print "====2 ", smeshInst
374 #print "--------------- smeshbuilder __init__ ---", created
377 SMESH._objref_SMESH_Gen.__init__(self)
379 ## Dump component to the Python script
380 # This method overrides IDL function to allow default values for the parameters.
381 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
382 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
384 ## Set mode of DumpPython(), \a historical or \a snapshot.
385 # In the \a historical mode, the Python Dump script includes all commands
386 # performed by SMESH engine. In the \a snapshot mode, commands
387 # relating to objects removed from the Study are excluded from the script
388 # as well as commands not influencing the current state of meshes
389 def SetDumpPythonHistorical(self, isHistorical):
390 if isHistorical: val = "true"
392 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
394 ## Sets the current study and Geometry component
395 # @ingroup l1_auxiliary
396 def init_smesh(self,theStudy,geompyD = None):
398 self.SetCurrentStudy(theStudy,geompyD)
401 notebook.myStudy = theStudy
403 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
404 # or a mesh wrapping a CORBA mesh given as a parameter.
405 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
406 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
407 # (2) a Geometrical object for meshing or
409 # @param name the name for the new mesh.
410 # @return an instance of Mesh class.
411 # @ingroup l2_construct
412 def Mesh(self, obj=0, name=0):
413 if isinstance(obj,str):
415 return Mesh(self,self.geompyD,obj,name)
417 ## Returns a long value from enumeration
418 # @ingroup l1_controls
419 def EnumToLong(self,theItem):
422 ## Returns a string representation of the color.
423 # To be used with filters.
424 # @param c color value (SALOMEDS.Color)
425 # @ingroup l1_controls
426 def ColorToString(self,c):
428 if isinstance(c, SALOMEDS.Color):
429 val = "%s;%s;%s" % (c.R, c.G, c.B)
430 elif isinstance(c, str):
433 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
436 ## Gets PointStruct from vertex
437 # @param theVertex a GEOM object(vertex)
438 # @return SMESH.PointStruct
439 # @ingroup l1_auxiliary
440 def GetPointStruct(self,theVertex):
441 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
442 return PointStruct(x,y,z)
444 ## Gets DirStruct from vector
445 # @param theVector a GEOM object(vector)
446 # @return SMESH.DirStruct
447 # @ingroup l1_auxiliary
448 def GetDirStruct(self,theVector):
449 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
450 if(len(vertices) != 2):
451 print "Error: vector object is incorrect."
453 p1 = self.geompyD.PointCoordinates(vertices[0])
454 p2 = self.geompyD.PointCoordinates(vertices[1])
455 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
456 dirst = DirStruct(pnt)
459 ## Makes DirStruct from a triplet
460 # @param x,y,z vector components
461 # @return SMESH.DirStruct
462 # @ingroup l1_auxiliary
463 def MakeDirStruct(self,x,y,z):
464 pnt = PointStruct(x,y,z)
465 return DirStruct(pnt)
467 ## Get AxisStruct from object
468 # @param theObj a GEOM object (line or plane)
469 # @return SMESH.AxisStruct
470 # @ingroup l1_auxiliary
471 def GetAxisStruct(self,theObj):
473 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
476 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
477 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
478 vertex1 = self.geompyD.PointCoordinates(vertex1)
479 vertex2 = self.geompyD.PointCoordinates(vertex2)
480 vertex3 = self.geompyD.PointCoordinates(vertex3)
481 vertex4 = self.geompyD.PointCoordinates(vertex4)
482 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
483 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
484 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] ]
485 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
486 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
487 elif len(edges) == 1:
488 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
489 p1 = self.geompyD.PointCoordinates( vertex1 )
490 p2 = self.geompyD.PointCoordinates( vertex2 )
491 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
492 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
493 elif theObj.GetShapeType() == GEOM.VERTEX:
494 x,y,z = self.geompyD.PointCoordinates( theObj )
495 axis = AxisStruct( x,y,z, 1,0,0,)
496 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
499 # From SMESH_Gen interface:
500 # ------------------------
502 ## Sets the given name to the object
503 # @param obj the object to rename
504 # @param name a new object name
505 # @ingroup l1_auxiliary
506 def SetName(self, obj, name):
507 if isinstance( obj, Mesh ):
509 elif isinstance( obj, Mesh_Algorithm ):
510 obj = obj.GetAlgorithm()
511 ior = salome.orb.object_to_string(obj)
512 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
514 ## Sets the current mode
515 # @ingroup l1_auxiliary
516 def SetEmbeddedMode( self,theMode ):
517 #self.SetEmbeddedMode(theMode)
518 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
520 ## Gets the current mode
521 # @ingroup l1_auxiliary
522 def IsEmbeddedMode(self):
523 #return self.IsEmbeddedMode()
524 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
526 ## Sets the current study. Calling SetCurrentStudy( None ) allows to
527 # switch OFF automatic pubilishing in the Study of mesh objects.
528 # @ingroup l1_auxiliary
529 def SetCurrentStudy( self, theStudy, geompyD = None ):
530 #self.SetCurrentStudy(theStudy)
532 from salome.geom import geomBuilder
533 geompyD = geomBuilder.geom
536 self.SetGeomEngine(geompyD)
537 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
540 notebook = salome_notebook.NoteBook( theStudy )
542 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
544 sb = theStudy.NewBuilder()
545 sc = theStudy.FindComponent("SMESH")
546 if sc: sb.LoadWith(sc, self)
550 ## Gets the current study
551 # @ingroup l1_auxiliary
552 def GetCurrentStudy(self):
553 #return self.GetCurrentStudy()
554 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
556 ## Creates a Mesh object importing data from the given UNV file
557 # @return an instance of Mesh class
559 def CreateMeshesFromUNV( self,theFileName ):
560 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
561 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
564 ## Creates a Mesh object(s) importing data from the given MED file
565 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
567 def CreateMeshesFromMED( self,theFileName ):
568 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
569 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
570 return aMeshes, aStatus
572 ## Creates a Mesh object(s) importing data from the given SAUV file
573 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
575 def CreateMeshesFromSAUV( self,theFileName ):
576 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
577 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
578 return aMeshes, aStatus
580 ## Creates a Mesh object importing data from the given STL file
581 # @return an instance of Mesh class
583 def CreateMeshesFromSTL( self, theFileName ):
584 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
585 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
588 ## Creates Mesh objects importing data from the given CGNS file
589 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
591 def CreateMeshesFromCGNS( self, theFileName ):
592 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
593 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
594 return aMeshes, aStatus
596 ## Creates a Mesh object importing data from the given GMF file.
597 # GMF files must have .mesh extension for the ASCII format and .meshb for
599 # @return [ an instance of Mesh class, SMESH.ComputeError ]
601 def CreateMeshesFromGMF( self, theFileName ):
602 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
605 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
606 return Mesh(self, self.geompyD, aSmeshMesh), error
608 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
609 # present in the new mesh.
610 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
611 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
612 # @param mergeNodesAndElements if true, equal nodes and elements are merged
613 # @param mergeTolerance tolerance for merging nodes
614 # @param allGroups forces creation of groups corresponding to every input mesh
615 # @param name name of a new mesh
616 # @return an instance of Mesh class
617 def Concatenate( self, meshes, uniteIdenticalGroups,
618 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
620 if not meshes: return None
621 for i,m in enumerate(meshes):
622 if isinstance(m, Mesh):
623 meshes[i] = m.GetMesh()
624 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
625 meshes[0].SetParameters(Parameters)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
630 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
635 ## Create a mesh by copying a part of another mesh.
636 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
637 # to copy nodes or elements not contained in any mesh object,
638 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
639 # @param meshName a name of the new mesh
640 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
641 # @param toKeepIDs to preserve order of the copied elements or not
642 # @return an instance of Mesh class
643 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
644 if (isinstance( meshPart, Mesh )):
645 meshPart = meshPart.GetMesh()
646 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
647 return Mesh(self, self.geompyD, mesh)
649 ## From SMESH_Gen interface
650 # @return the list of integer values
651 # @ingroup l1_auxiliary
652 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
653 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
655 ## From SMESH_Gen interface. Creates a pattern
656 # @return an instance of SMESH_Pattern
658 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
659 # @ingroup l2_modif_patterns
660 def GetPattern(self):
661 return SMESH._objref_SMESH_Gen.GetPattern(self)
663 ## Sets number of segments per diagonal of boundary box of geometry by which
664 # default segment length of appropriate 1D hypotheses is defined.
665 # Default value is 10
666 # @ingroup l1_auxiliary
667 def SetBoundaryBoxSegmentation(self, nbSegments):
668 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
670 # Filtering. Auxiliary functions:
671 # ------------------------------
673 ## Creates an empty criterion
674 # @return SMESH.Filter.Criterion
675 # @ingroup l1_controls
676 def GetEmptyCriterion(self):
677 Type = self.EnumToLong(FT_Undefined)
678 Compare = self.EnumToLong(FT_Undefined)
682 UnaryOp = self.EnumToLong(FT_Undefined)
683 BinaryOp = self.EnumToLong(FT_Undefined)
686 Precision = -1 ##@1e-07
687 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
688 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
690 ## Creates a criterion by the given parameters
691 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
692 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
693 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
694 # Type SMESH.FunctorType._items in the Python Console to see all values.
695 # Note that the items starting from FT_LessThan are not suitable for CritType.
696 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
697 # @param Threshold the threshold value (range of ids as string, shape, numeric)
698 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
699 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
701 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
702 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
703 # @return SMESH.Filter.Criterion
705 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
706 # @ingroup l1_controls
707 def GetCriterion(self,elementType,
709 Compare = FT_EqualTo,
711 UnaryOp=FT_Undefined,
712 BinaryOp=FT_Undefined,
714 if not CritType in SMESH.FunctorType._items:
715 raise TypeError, "CritType should be of SMESH.FunctorType"
716 aCriterion = self.GetEmptyCriterion()
717 aCriterion.TypeOfElement = elementType
718 aCriterion.Type = self.EnumToLong(CritType)
719 aCriterion.Tolerance = Tolerance
721 aThreshold = Threshold
723 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
724 aCriterion.Compare = self.EnumToLong(Compare)
725 elif Compare == "=" or Compare == "==":
726 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
728 aCriterion.Compare = self.EnumToLong(FT_LessThan)
730 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
731 elif Compare != FT_Undefined:
732 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
735 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
736 FT_BelongToCylinder, FT_LyingOnGeom]:
737 # Check that Threshold is GEOM object
738 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
739 aCriterion.ThresholdStr = GetName(aThreshold)
740 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
741 if not aCriterion.ThresholdID:
742 name = aCriterion.ThresholdStr
744 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
745 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
746 # or a name of GEOM object
747 elif isinstance( aThreshold, str ):
748 aCriterion.ThresholdStr = aThreshold
750 raise TypeError, "The Threshold should be a shape."
751 if isinstance(UnaryOp,float):
752 aCriterion.Tolerance = UnaryOp
753 UnaryOp = FT_Undefined
755 elif CritType == FT_BelongToMeshGroup:
756 # Check that Threshold is a group
757 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
758 if aThreshold.GetType() != elementType:
759 raise ValueError, "Group type mismatches Element type"
760 aCriterion.ThresholdStr = aThreshold.GetName()
761 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
762 study = self.GetCurrentStudy()
764 so = study.FindObjectIOR( aCriterion.ThresholdID )
768 aCriterion.ThresholdID = entry
770 raise TypeError, "The Threshold should be a Mesh Group"
771 elif CritType == FT_RangeOfIds:
772 # Check that Threshold is string
773 if isinstance(aThreshold, str):
774 aCriterion.ThresholdStr = aThreshold
776 raise TypeError, "The Threshold should be a string."
777 elif CritType == FT_CoplanarFaces:
778 # Check the Threshold
779 if isinstance(aThreshold, int):
780 aCriterion.ThresholdID = str(aThreshold)
781 elif isinstance(aThreshold, str):
784 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
785 aCriterion.ThresholdID = aThreshold
788 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
789 elif CritType == FT_ConnectedElements:
790 # Check the Threshold
791 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
792 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
793 if not aCriterion.ThresholdID:
794 name = aThreshold.GetName()
796 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
797 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
798 elif isinstance(aThreshold, int): # node id
799 aCriterion.Threshold = aThreshold
800 elif isinstance(aThreshold, list): # 3 point coordinates
801 if len( aThreshold ) < 3:
802 raise ValueError, "too few point coordinates, must be 3"
803 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
804 elif isinstance(aThreshold, str):
805 if aThreshold.isdigit():
806 aCriterion.Threshold = aThreshold # node id
808 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
811 "The Threshold should either a VERTEX, or a node ID, "\
812 "or a list of point coordinates and not '%s'"%aThreshold
813 elif CritType == FT_ElemGeomType:
814 # Check the Threshold
816 aCriterion.Threshold = self.EnumToLong(aThreshold)
817 assert( aThreshold in SMESH.GeometryType._items )
819 if isinstance(aThreshold, int):
820 aCriterion.Threshold = aThreshold
822 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
825 elif CritType == FT_EntityType:
826 # Check the Threshold
828 aCriterion.Threshold = self.EnumToLong(aThreshold)
829 assert( aThreshold in SMESH.EntityType._items )
831 if isinstance(aThreshold, int):
832 aCriterion.Threshold = aThreshold
834 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
838 elif CritType == FT_GroupColor:
839 # Check the Threshold
841 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
843 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
845 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
846 FT_LinearOrQuadratic, FT_BadOrientedVolume,
847 FT_BareBorderFace, FT_BareBorderVolume,
848 FT_OverConstrainedFace, FT_OverConstrainedVolume,
849 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
850 # At this point the Threshold is unnecessary
851 if aThreshold == FT_LogicalNOT:
852 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
853 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
854 aCriterion.BinaryOp = aThreshold
858 aThreshold = float(aThreshold)
859 aCriterion.Threshold = aThreshold
861 raise TypeError, "The Threshold should be a number."
864 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
865 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
867 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
868 aCriterion.BinaryOp = self.EnumToLong(Threshold)
870 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
871 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
873 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
874 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
878 ## Creates a filter with the given parameters
879 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
880 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
881 # Type SMESH.FunctorType._items in the Python Console to see all values.
882 # Note that the items starting from FT_LessThan are not suitable for CritType.
883 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
884 # @param Threshold the threshold value (range of ids as string, shape, numeric)
885 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
886 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
887 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
888 # @param mesh the mesh to initialize the filter with
889 # @return SMESH_Filter
891 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
892 # @ingroup l1_controls
893 def GetFilter(self,elementType,
894 CritType=FT_Undefined,
897 UnaryOp=FT_Undefined,
900 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
901 aFilterMgr = self.CreateFilterManager()
902 aFilter = aFilterMgr.CreateFilter()
904 aCriteria.append(aCriterion)
905 aFilter.SetCriteria(aCriteria)
907 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
908 else : aFilter.SetMesh( mesh )
909 aFilterMgr.UnRegister()
912 ## Creates a filter from criteria
913 # @param criteria a list of criteria
914 # @param binOp binary operator used when binary operator of criteria is undefined
915 # @return SMESH_Filter
917 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
918 # @ingroup l1_controls
919 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
920 for i in range( len( criteria ) - 1 ):
921 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
922 criteria[i].BinaryOp = self.EnumToLong( binOp )
923 aFilterMgr = self.CreateFilterManager()
924 aFilter = aFilterMgr.CreateFilter()
925 aFilter.SetCriteria(criteria)
926 aFilterMgr.UnRegister()
929 ## Creates a numerical functor by its type
930 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
931 # Type SMESH.FunctorType._items in the Python Console to see all items.
932 # Note that not all items corresponds to numerical functors.
933 # @return SMESH_NumericalFunctor
934 # @ingroup l1_controls
935 def GetFunctor(self,theCriterion):
936 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
938 aFilterMgr = self.CreateFilterManager()
940 if theCriterion == FT_AspectRatio:
941 functor = aFilterMgr.CreateAspectRatio()
942 elif theCriterion == FT_AspectRatio3D:
943 functor = aFilterMgr.CreateAspectRatio3D()
944 elif theCriterion == FT_Warping:
945 functor = aFilterMgr.CreateWarping()
946 elif theCriterion == FT_MinimumAngle:
947 functor = aFilterMgr.CreateMinimumAngle()
948 elif theCriterion == FT_Taper:
949 functor = aFilterMgr.CreateTaper()
950 elif theCriterion == FT_Skew:
951 functor = aFilterMgr.CreateSkew()
952 elif theCriterion == FT_Area:
953 functor = aFilterMgr.CreateArea()
954 elif theCriterion == FT_Volume3D:
955 functor = aFilterMgr.CreateVolume3D()
956 elif theCriterion == FT_MaxElementLength2D:
957 functor = aFilterMgr.CreateMaxElementLength2D()
958 elif theCriterion == FT_MaxElementLength3D:
959 functor = aFilterMgr.CreateMaxElementLength3D()
960 elif theCriterion == FT_MultiConnection:
961 functor = aFilterMgr.CreateMultiConnection()
962 elif theCriterion == FT_MultiConnection2D:
963 functor = aFilterMgr.CreateMultiConnection2D()
964 elif theCriterion == FT_Length:
965 functor = aFilterMgr.CreateLength()
966 elif theCriterion == FT_Length2D:
967 functor = aFilterMgr.CreateLength2D()
969 print "Error: given parameter is not numerical functor type."
970 aFilterMgr.UnRegister()
973 ## Creates hypothesis
974 # @param theHType mesh hypothesis type (string)
975 # @param theLibName mesh plug-in library name
976 # @return created hypothesis instance
977 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
978 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
980 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
983 # wrap hypothesis methods
984 #print "HYPOTHESIS", theHType
985 for meth_name in dir( hyp.__class__ ):
986 if not meth_name.startswith("Get") and \
987 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
988 method = getattr ( hyp.__class__, meth_name )
990 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
994 ## Gets the mesh statistic
995 # @return dictionary "element type" - "count of elements"
996 # @ingroup l1_meshinfo
997 def GetMeshInfo(self, obj):
998 if isinstance( obj, Mesh ):
1001 if hasattr(obj, "GetMeshInfo"):
1002 values = obj.GetMeshInfo()
1003 for i in range(SMESH.Entity_Last._v):
1004 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1008 ## Get minimum distance between two objects
1010 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1011 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1013 # @param src1 first source object
1014 # @param src2 second source object
1015 # @param id1 node/element id from the first source
1016 # @param id2 node/element id from the second (or first) source
1017 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1018 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1019 # @return minimum distance value
1020 # @sa GetMinDistance()
1021 # @ingroup l1_measurements
1022 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1023 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1027 result = result.value
1030 ## Get measure structure specifying minimum distance data between two objects
1032 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1033 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1035 # @param src1 first source object
1036 # @param src2 second source object
1037 # @param id1 node/element id from the first source
1038 # @param id2 node/element id from the second (or first) source
1039 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1040 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1041 # @return Measure structure or None if input data is invalid
1043 # @ingroup l1_measurements
1044 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1045 if isinstance(src1, Mesh): src1 = src1.mesh
1046 if isinstance(src2, Mesh): src2 = src2.mesh
1047 if src2 is None and id2 != 0: src2 = src1
1048 if not hasattr(src1, "_narrow"): return None
1049 src1 = src1._narrow(SMESH.SMESH_IDSource)
1050 if not src1: return None
1051 unRegister = genObjUnRegister()
1054 e = m.GetMeshEditor()
1056 src1 = e.MakeIDSource([id1], SMESH.FACE)
1058 src1 = e.MakeIDSource([id1], SMESH.NODE)
1059 unRegister.set( src1 )
1061 if hasattr(src2, "_narrow"):
1062 src2 = src2._narrow(SMESH.SMESH_IDSource)
1063 if src2 and id2 != 0:
1065 e = m.GetMeshEditor()
1067 src2 = e.MakeIDSource([id2], SMESH.FACE)
1069 src2 = e.MakeIDSource([id2], SMESH.NODE)
1070 unRegister.set( src2 )
1073 aMeasurements = self.CreateMeasurements()
1074 unRegister.set( aMeasurements )
1075 result = aMeasurements.MinDistance(src1, src2)
1078 ## Get bounding box of the specified object(s)
1079 # @param objects single source object or list of source objects
1080 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1081 # @sa GetBoundingBox()
1082 # @ingroup l1_measurements
1083 def BoundingBox(self, objects):
1084 result = self.GetBoundingBox(objects)
1088 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1091 ## Get measure structure specifying bounding box data of the specified object(s)
1092 # @param objects single source object or list of source objects
1093 # @return Measure structure
1095 # @ingroup l1_measurements
1096 def GetBoundingBox(self, objects):
1097 if isinstance(objects, tuple):
1098 objects = list(objects)
1099 if not isinstance(objects, list):
1103 if isinstance(o, Mesh):
1104 srclist.append(o.mesh)
1105 elif hasattr(o, "_narrow"):
1106 src = o._narrow(SMESH.SMESH_IDSource)
1107 if src: srclist.append(src)
1110 aMeasurements = self.CreateMeasurements()
1111 result = aMeasurements.BoundingBox(srclist)
1112 aMeasurements.UnRegister()
1115 ## Get sum of lengths of all 1D elements in the mesh object.
1116 # @param obj mesh, submesh or group
1117 # @return sum of lengths of all 1D elements
1118 # @ingroup l1_measurements
1119 def GetLength(self, obj):
1120 if isinstance(obj, Mesh): obj = obj.mesh
1121 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1122 aMeasurements = self.CreateMeasurements()
1123 value = aMeasurements.Length(obj)
1124 aMeasurements.UnRegister()
1127 ## Get sum of areas of all 2D elements in the mesh object.
1128 # @param obj mesh, submesh or group
1129 # @return sum of areas of all 2D elements
1130 # @ingroup l1_measurements
1131 def GetArea(self, obj):
1132 if isinstance(obj, Mesh): obj = obj.mesh
1133 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1134 aMeasurements = self.CreateMeasurements()
1135 value = aMeasurements.Area(obj)
1136 aMeasurements.UnRegister()
1139 ## Get sum of volumes of all 3D elements in the mesh object.
1140 # @param obj mesh, submesh or group
1141 # @return sum of volumes of all 3D elements
1142 # @ingroup l1_measurements
1143 def GetVolume(self, obj):
1144 if isinstance(obj, Mesh): obj = obj.mesh
1145 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1146 aMeasurements = self.CreateMeasurements()
1147 value = aMeasurements.Volume(obj)
1148 aMeasurements.UnRegister()
1151 pass # end of class smeshBuilder
1154 #Registering the new proxy for SMESH_Gen
1155 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1157 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1158 # interface to create or load meshes.
1163 # salome.salome_init()
1164 # from salome.smesh import smeshBuilder
1165 # smesh = smeshBuilder.New(theStudy)
1167 # @param study SALOME study, generally obtained by salome.myStudy.
1168 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1169 # @return smeshBuilder instance
1171 def New( study, instance=None):
1173 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1174 interface to create or load meshes.
1178 salome.salome_init()
1179 from salome.smesh import smeshBuilder
1180 smesh = smeshBuilder.New(theStudy)
1183 study SALOME study, generally obtained by salome.myStudy.
1184 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1186 smeshBuilder instance
1194 smeshInst = smeshBuilder()
1195 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1196 smeshInst.init_smesh(study)
1200 # Public class: Mesh
1201 # ==================
1203 ## This class allows defining and managing a mesh.
1204 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1205 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1206 # new nodes and elements and by changing the existing entities), to get information
1207 # about a mesh and to export a mesh into different formats.
1209 __metaclass__ = MeshMeta
1217 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1218 # sets the GUI name of this mesh to \a name.
1219 # @param smeshpyD an instance of smeshBuilder class
1220 # @param geompyD an instance of geomBuilder class
1221 # @param obj Shape to be meshed or SMESH_Mesh object
1222 # @param name Study name of the mesh
1223 # @ingroup l2_construct
1224 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1225 self.smeshpyD=smeshpyD
1226 self.geompyD=geompyD
1231 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1234 # publish geom of mesh (issue 0021122)
1235 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1237 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1238 if studyID != geompyD.myStudyId:
1239 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1242 geo_name = name + " shape"
1244 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1245 geompyD.addToStudy( self.geom, geo_name )
1246 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1248 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1251 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1253 self.smeshpyD.SetName(self.mesh, name)
1255 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1258 self.geom = self.mesh.GetShapeToMesh()
1260 self.editor = self.mesh.GetMeshEditor()
1261 self.functors = [None] * SMESH.FT_Undefined._v
1263 # set self to algoCreator's
1264 for attrName in dir(self):
1265 attr = getattr( self, attrName )
1266 if isinstance( attr, algoCreator ):
1267 setattr( self, attrName, attr.copy( self ))
1272 ## Destructor. Clean-up resources
1275 #self.mesh.UnRegister()
1279 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1280 # @param theMesh a SMESH_Mesh object
1281 # @ingroup l2_construct
1282 def SetMesh(self, theMesh):
1283 # do not call Register() as this prevents mesh servant deletion at closing study
1284 #if self.mesh: self.mesh.UnRegister()
1287 #self.mesh.Register()
1288 self.geom = self.mesh.GetShapeToMesh()
1291 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1292 # @return a SMESH_Mesh object
1293 # @ingroup l2_construct
1297 ## Gets the name of the mesh
1298 # @return the name of the mesh as a string
1299 # @ingroup l2_construct
1301 name = GetName(self.GetMesh())
1304 ## Sets a name to the mesh
1305 # @param name a new name of the mesh
1306 # @ingroup l2_construct
1307 def SetName(self, name):
1308 self.smeshpyD.SetName(self.GetMesh(), name)
1310 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1311 # The subMesh object gives access to the IDs of nodes and elements.
1312 # @param geom a geometrical object (shape)
1313 # @param name a name for the submesh
1314 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1315 # @ingroup l2_submeshes
1316 def GetSubMesh(self, geom, name):
1317 AssureGeomPublished( self, geom, name )
1318 submesh = self.mesh.GetSubMesh( geom, name )
1321 ## Returns the shape associated to the mesh
1322 # @return a GEOM_Object
1323 # @ingroup l2_construct
1327 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1328 # @param geom the shape to be meshed (GEOM_Object)
1329 # @ingroup l2_construct
1330 def SetShape(self, geom):
1331 self.mesh = self.smeshpyD.CreateMesh(geom)
1333 ## Loads mesh from the study after opening the study
1337 ## Returns true if the hypotheses are defined well
1338 # @param theSubObject a sub-shape of a mesh shape
1339 # @return True or False
1340 # @ingroup l2_construct
1341 def IsReadyToCompute(self, theSubObject):
1342 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1344 ## Returns errors of hypotheses definition.
1345 # The list of errors is empty if everything is OK.
1346 # @param theSubObject a sub-shape of a mesh shape
1347 # @return a list of errors
1348 # @ingroup l2_construct
1349 def GetAlgoState(self, theSubObject):
1350 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1352 ## Returns a geometrical object on which the given element was built.
1353 # The returned geometrical object, if not nil, is either found in the
1354 # study or published by this method with the given name
1355 # @param theElementID the id of the mesh element
1356 # @param theGeomName the user-defined name of the geometrical object
1357 # @return GEOM::GEOM_Object instance
1358 # @ingroup l2_construct
1359 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1360 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1362 ## Returns the mesh dimension depending on the dimension of the underlying shape
1363 # or, if the mesh is not based on any shape, basing on deimension of elements
1364 # @return mesh dimension as an integer value [0,3]
1365 # @ingroup l1_auxiliary
1366 def MeshDimension(self):
1367 if self.mesh.HasShapeToMesh():
1368 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1369 if len( shells ) > 0 :
1371 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1373 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1378 if self.NbVolumes() > 0: return 3
1379 if self.NbFaces() > 0: return 2
1380 if self.NbEdges() > 0: return 1
1383 ## Evaluates size of prospective mesh on a shape
1384 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1385 # To know predicted number of e.g. edges, inquire it this way
1386 # Evaluate()[ EnumToLong( Entity_Edge )]
1387 def Evaluate(self, geom=0):
1388 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1390 geom = self.mesh.GetShapeToMesh()
1393 return self.smeshpyD.Evaluate(self.mesh, geom)
1396 ## Computes the mesh and returns the status of the computation
1397 # @param geom geomtrical shape on which mesh data should be computed
1398 # @param discardModifs if True and the mesh has been edited since
1399 # a last total re-compute and that may prevent successful partial re-compute,
1400 # then the mesh is cleaned before Compute()
1401 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1402 # @return True or False
1403 # @ingroup l2_construct
1404 def Compute(self, geom=0, discardModifs=False, refresh=False):
1405 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1407 geom = self.mesh.GetShapeToMesh()
1412 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1414 ok = self.smeshpyD.Compute(self.mesh, geom)
1415 except SALOME.SALOME_Exception, ex:
1416 print "Mesh computation failed, exception caught:"
1417 print " ", ex.details.text
1420 print "Mesh computation failed, exception caught:"
1421 traceback.print_exc()
1425 # Treat compute errors
1426 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1427 for err in computeErrors:
1429 if self.mesh.HasShapeToMesh():
1431 mainIOR = salome.orb.object_to_string(geom)
1432 for sname in salome.myStudyManager.GetOpenStudies():
1433 s = salome.myStudyManager.GetStudyByName(sname)
1435 mainSO = s.FindObjectIOR(mainIOR)
1436 if not mainSO: continue
1437 if err.subShapeID == 1:
1438 shapeText = ' on "%s"' % mainSO.GetName()
1439 subIt = s.NewChildIterator(mainSO)
1441 subSO = subIt.Value()
1443 obj = subSO.GetObject()
1444 if not obj: continue
1445 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1447 ids = go.GetSubShapeIndices()
1448 if len(ids) == 1 and ids[0] == err.subShapeID:
1449 shapeText = ' on "%s"' % subSO.GetName()
1452 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1454 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1456 shapeText = " on subshape #%s" % (err.subShapeID)
1458 shapeText = " on subshape #%s" % (err.subShapeID)
1460 stdErrors = ["OK", #COMPERR_OK
1461 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1462 "std::exception", #COMPERR_STD_EXCEPTION
1463 "OCC exception", #COMPERR_OCC_EXCEPTION
1464 "..", #COMPERR_SLM_EXCEPTION
1465 "Unknown exception", #COMPERR_EXCEPTION
1466 "Memory allocation problem", #COMPERR_MEMORY_PB
1467 "Algorithm failed", #COMPERR_ALGO_FAILED
1468 "Unexpected geometry", #COMPERR_BAD_SHAPE
1469 "Warning", #COMPERR_WARNING
1470 "Computation cancelled",#COMPERR_CANCELED
1471 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1473 if err.code < len(stdErrors): errText = stdErrors[err.code]
1475 errText = "code %s" % -err.code
1476 if errText: errText += ". "
1477 errText += err.comment
1478 if allReasons != "":allReasons += "\n"
1480 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1482 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1486 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1488 if err.isGlobalAlgo:
1496 reason = '%s %sD algorithm is missing' % (glob, dim)
1497 elif err.state == HYP_MISSING:
1498 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1499 % (glob, dim, name, dim))
1500 elif err.state == HYP_NOTCONFORM:
1501 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1502 elif err.state == HYP_BAD_PARAMETER:
1503 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1504 % ( glob, dim, name ))
1505 elif err.state == HYP_BAD_GEOMETRY:
1506 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1507 'geometry' % ( glob, dim, name ))
1508 elif err.state == HYP_HIDDEN_ALGO:
1509 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1510 'algorithm of upper dimension generating %sD mesh'
1511 % ( glob, dim, name, glob, dim ))
1513 reason = ("For unknown reason. "
1514 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1516 if allReasons != "":allReasons += "\n"
1517 allReasons += "- " + reason
1519 if not ok or allReasons != "":
1520 msg = '"' + GetName(self.mesh) + '"'
1521 if ok: msg += " has been computed with warnings"
1522 else: msg += " has not been computed"
1523 if allReasons != "": msg += ":"
1528 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1529 smeshgui = salome.ImportComponentGUI("SMESH")
1530 smeshgui.Init(self.mesh.GetStudyId())
1531 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1532 if refresh: salome.sg.updateObjBrowser(1)
1536 ## Return submesh objects list in meshing order
1537 # @return list of list of submesh objects
1538 # @ingroup l2_construct
1539 def GetMeshOrder(self):
1540 return self.mesh.GetMeshOrder()
1542 ## Return submesh objects list in meshing order
1543 # @return list of list of submesh objects
1544 # @ingroup l2_construct
1545 def SetMeshOrder(self, submeshes):
1546 return self.mesh.SetMeshOrder(submeshes)
1548 ## Removes all nodes and elements
1549 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1550 # @ingroup l2_construct
1551 def Clear(self, refresh=False):
1553 if ( salome.sg.hasDesktop() and
1554 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1555 smeshgui = salome.ImportComponentGUI("SMESH")
1556 smeshgui.Init(self.mesh.GetStudyId())
1557 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1558 if refresh: salome.sg.updateObjBrowser(1)
1560 ## Removes all nodes and elements of indicated shape
1561 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1562 # @param geomId the ID of a sub-shape to remove elements on
1563 # @ingroup l2_construct
1564 def ClearSubMesh(self, geomId, refresh=False):
1565 self.mesh.ClearSubMesh(geomId)
1566 if salome.sg.hasDesktop():
1567 smeshgui = salome.ImportComponentGUI("SMESH")
1568 smeshgui.Init(self.mesh.GetStudyId())
1569 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1570 if refresh: salome.sg.updateObjBrowser(1)
1572 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1573 # @param fineness [0.0,1.0] defines mesh fineness
1574 # @return True or False
1575 # @ingroup l3_algos_basic
1576 def AutomaticTetrahedralization(self, fineness=0):
1577 dim = self.MeshDimension()
1579 self.RemoveGlobalHypotheses()
1580 self.Segment().AutomaticLength(fineness)
1582 self.Triangle().LengthFromEdges()
1587 return self.Compute()
1589 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1590 # @param fineness [0.0, 1.0] defines mesh fineness
1591 # @return True or False
1592 # @ingroup l3_algos_basic
1593 def AutomaticHexahedralization(self, fineness=0):
1594 dim = self.MeshDimension()
1595 # assign the hypotheses
1596 self.RemoveGlobalHypotheses()
1597 self.Segment().AutomaticLength(fineness)
1604 return self.Compute()
1606 ## Assigns a hypothesis
1607 # @param hyp a hypothesis to assign
1608 # @param geom a subhape of mesh geometry
1609 # @return SMESH.Hypothesis_Status
1610 # @ingroup l2_hypotheses
1611 def AddHypothesis(self, hyp, geom=0):
1612 if isinstance( hyp, Mesh_Algorithm ):
1613 hyp = hyp.GetAlgorithm()
1618 geom = self.mesh.GetShapeToMesh()
1621 if self.mesh.HasShapeToMesh():
1622 hyp_type = hyp.GetName()
1623 lib_name = hyp.GetLibName()
1624 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1625 if checkAll and geom:
1626 checkAll = geom.GetType() == 37
1627 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1629 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1630 status = self.mesh.AddHypothesis(geom, hyp)
1632 status = HYP_BAD_GEOMETRY,""
1633 hyp_name = GetName( hyp )
1636 geom_name = geom.GetName()
1637 isAlgo = hyp._narrow( SMESH_Algo )
1638 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1641 ## Return True if an algorithm of hypothesis is assigned to a given shape
1642 # @param hyp a hypothesis to check
1643 # @param geom a subhape of mesh geometry
1644 # @return True of False
1645 # @ingroup l2_hypotheses
1646 def IsUsedHypothesis(self, hyp, geom):
1647 if not hyp: # or not geom
1649 if isinstance( hyp, Mesh_Algorithm ):
1650 hyp = hyp.GetAlgorithm()
1652 hyps = self.GetHypothesisList(geom)
1654 if h.GetId() == hyp.GetId():
1658 ## Unassigns a hypothesis
1659 # @param hyp a hypothesis to unassign
1660 # @param geom a sub-shape of mesh geometry
1661 # @return SMESH.Hypothesis_Status
1662 # @ingroup l2_hypotheses
1663 def RemoveHypothesis(self, hyp, geom=0):
1666 if isinstance( hyp, Mesh_Algorithm ):
1667 hyp = hyp.GetAlgorithm()
1673 if self.IsUsedHypothesis( hyp, shape ):
1674 return self.mesh.RemoveHypothesis( shape, hyp )
1675 hypName = GetName( hyp )
1676 geoName = GetName( shape )
1677 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1680 ## Gets the list of hypotheses added on a geometry
1681 # @param geom a sub-shape of mesh geometry
1682 # @return the sequence of SMESH_Hypothesis
1683 # @ingroup l2_hypotheses
1684 def GetHypothesisList(self, geom):
1685 return self.mesh.GetHypothesisList( geom )
1687 ## Removes all global hypotheses
1688 # @ingroup l2_hypotheses
1689 def RemoveGlobalHypotheses(self):
1690 current_hyps = self.mesh.GetHypothesisList( self.geom )
1691 for hyp in current_hyps:
1692 self.mesh.RemoveHypothesis( self.geom, hyp )
1696 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1697 ## allowing to overwrite the file if it exists or add the exported data to its contents
1698 # @param f is the file name
1699 # @param auto_groups boolean parameter for creating/not creating
1700 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1701 # the typical use is auto_groups=false.
1702 # @param version MED format version(MED_V2_1 or MED_V2_2)
1703 # @param overwrite boolean parameter for overwriting/not overwriting the file
1704 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1705 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1706 # - 1D if all mesh nodes lie on OX coordinate axis, or
1707 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1708 # - 3D in the rest cases.
1709 # If @a autoDimension is @c False, the space dimension is always 3.
1710 # @param fields : list of GEOM fields defined on the shape to mesh.
1711 # @param geomAssocFields : each character of this string means a need to export a
1712 # corresponding field; correspondence between fields and characters is following:
1713 # - 'v' stands for _vertices_ field;
1714 # - 'e' stands for _edges_ field;
1715 # - 'f' stands for _faces_ field;
1716 # - 's' stands for _solids_ field.
1717 # @ingroup l2_impexp
1718 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1719 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1720 if meshPart or fields or geomAssocFields:
1721 unRegister = genObjUnRegister()
1722 if isinstance( meshPart, list ):
1723 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1724 unRegister.set( meshPart )
1725 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1726 fields, geomAssocFields)
1728 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1730 ## Exports the mesh in a file in SAUV format
1731 # @param f is the file name
1732 # @param auto_groups boolean parameter for creating/not creating
1733 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1734 # the typical use is auto_groups=false.
1735 # @ingroup l2_impexp
1736 def ExportSAUV(self, f, auto_groups=0):
1737 self.mesh.ExportSAUV(f, auto_groups)
1739 ## Exports the mesh in a file in DAT format
1740 # @param f the file name
1741 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1742 # @ingroup l2_impexp
1743 def ExportDAT(self, f, meshPart=None):
1745 unRegister = genObjUnRegister()
1746 if isinstance( meshPart, list ):
1747 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1748 unRegister.set( meshPart )
1749 self.mesh.ExportPartToDAT( meshPart, f )
1751 self.mesh.ExportDAT(f)
1753 ## Exports the mesh in a file in UNV format
1754 # @param f the file name
1755 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1756 # @ingroup l2_impexp
1757 def ExportUNV(self, f, meshPart=None):
1759 unRegister = genObjUnRegister()
1760 if isinstance( meshPart, list ):
1761 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1762 unRegister.set( meshPart )
1763 self.mesh.ExportPartToUNV( meshPart, f )
1765 self.mesh.ExportUNV(f)
1767 ## Export the mesh in a file in STL format
1768 # @param f the file name
1769 # @param ascii defines the file encoding
1770 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1771 # @ingroup l2_impexp
1772 def ExportSTL(self, f, ascii=1, meshPart=None):
1774 unRegister = genObjUnRegister()
1775 if isinstance( meshPart, list ):
1776 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1777 unRegister.set( meshPart )
1778 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1780 self.mesh.ExportSTL(f, ascii)
1782 ## Exports the mesh in a file in CGNS format
1783 # @param f is the file name
1784 # @param overwrite boolean parameter for overwriting/not overwriting the file
1785 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1786 # @ingroup l2_impexp
1787 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1788 unRegister = genObjUnRegister()
1789 if isinstance( meshPart, list ):
1790 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1791 unRegister.set( meshPart )
1792 if isinstance( meshPart, Mesh ):
1793 meshPart = meshPart.mesh
1795 meshPart = self.mesh
1796 self.mesh.ExportCGNS(meshPart, f, overwrite)
1798 ## Exports the mesh in a file in GMF format.
1799 # GMF files must have .mesh extension for the ASCII format and .meshb for
1800 # the bynary format. Other extensions are not allowed.
1801 # @param f is 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 ExportGMF(self, f, meshPart=None):
1805 unRegister = genObjUnRegister()
1806 if isinstance( meshPart, list ):
1807 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1808 unRegister.set( meshPart )
1809 if isinstance( meshPart, Mesh ):
1810 meshPart = meshPart.mesh
1812 meshPart = self.mesh
1813 self.mesh.ExportGMF(meshPart, f, True)
1815 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1816 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1817 ## allowing to overwrite the file if it exists or add the exported data to its contents
1818 # @param f the file name
1819 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1820 # @param opt boolean parameter for creating/not creating
1821 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1822 # @param overwrite boolean parameter for overwriting/not overwriting the file
1823 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1824 # - 1D if all mesh nodes lie on OX coordinate axis, or
1825 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1826 # - 3D in the rest cases.
1828 # If @a autoDimension is @c False, the space dimension is always 3.
1829 # @ingroup l2_impexp
1830 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1831 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1833 # Operations with groups:
1834 # ----------------------
1836 ## Creates an empty mesh group
1837 # @param elementType the type of elements in the group; either of
1838 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1839 # @param name the name of the mesh group
1840 # @return SMESH_Group
1841 # @ingroup l2_grps_create
1842 def CreateEmptyGroup(self, elementType, name):
1843 return self.mesh.CreateGroup(elementType, name)
1845 ## Creates a mesh group based on the geometric object \a grp
1846 # and gives a \a name, \n if this parameter is not defined
1847 # the name is the same as the geometric group name \n
1848 # Note: Works like GroupOnGeom().
1849 # @param grp a geometric group, a vertex, an edge, a face or a solid
1850 # @param name the name of the mesh group
1851 # @return SMESH_GroupOnGeom
1852 # @ingroup l2_grps_create
1853 def Group(self, grp, name=""):
1854 return self.GroupOnGeom(grp, name)
1856 ## Creates a mesh group based on the geometrical object \a grp
1857 # and gives a \a name, \n if this parameter is not defined
1858 # the name is the same as the geometrical group name
1859 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1860 # @param name the name of the mesh group
1861 # @param typ the type of elements in the group; either of
1862 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1863 # automatically detected by the type of the geometry
1864 # @return SMESH_GroupOnGeom
1865 # @ingroup l2_grps_create
1866 def GroupOnGeom(self, grp, name="", typ=None):
1867 AssureGeomPublished( self, grp, name )
1869 name = grp.GetName()
1871 typ = self._groupTypeFromShape( grp )
1872 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1874 ## Pivate method to get a type of group on geometry
1875 def _groupTypeFromShape( self, shape ):
1876 tgeo = str(shape.GetShapeType())
1877 if tgeo == "VERTEX":
1879 elif tgeo == "EDGE":
1881 elif tgeo == "FACE" or tgeo == "SHELL":
1883 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1885 elif tgeo == "COMPOUND":
1886 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1888 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1889 return self._groupTypeFromShape( sub[0] )
1892 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1895 ## Creates a mesh group with given \a name based on the \a filter which
1896 ## is a special type of group dynamically updating it's contents during
1897 ## mesh modification
1898 # @param typ 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 # @param filter the filter defining group contents
1902 # @return SMESH_GroupOnFilter
1903 # @ingroup l2_grps_create
1904 def GroupOnFilter(self, typ, name, filter):
1905 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1907 ## Creates a mesh group by the given ids of elements
1908 # @param groupName the name of the mesh group
1909 # @param elementType the type of elements in the group; either of
1910 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1911 # @param elemIDs the list of ids
1912 # @return SMESH_Group
1913 # @ingroup l2_grps_create
1914 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1915 group = self.mesh.CreateGroup(elementType, groupName)
1916 if hasattr( elemIDs, "GetIDs" ):
1917 if hasattr( elemIDs, "SetMesh" ):
1918 elemIDs.SetMesh( self.GetMesh() )
1919 group.AddFrom( elemIDs )
1924 ## Creates a mesh group by the given conditions
1925 # @param groupName the name of the mesh group
1926 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1927 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
1928 # Type SMESH.FunctorType._items in the Python Console to see all values.
1929 # Note that the items starting from FT_LessThan are not suitable for CritType.
1930 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1931 # @param Threshold the threshold value (range of ids as string, shape, numeric)
1932 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
1933 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1934 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
1935 # @return SMESH_GroupOnFilter
1936 # @ingroup l2_grps_create
1940 CritType=FT_Undefined,
1943 UnaryOp=FT_Undefined,
1945 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1946 group = self.MakeGroupByCriterion(groupName, aCriterion)
1949 ## Creates a mesh group by the given criterion
1950 # @param groupName the name of the mesh group
1951 # @param Criterion the instance of Criterion class
1952 # @return SMESH_GroupOnFilter
1953 # @ingroup l2_grps_create
1954 def MakeGroupByCriterion(self, groupName, Criterion):
1955 return self.MakeGroupByCriteria( groupName, [Criterion] )
1957 ## Creates a mesh group by the given criteria (list of criteria)
1958 # @param groupName the name of the mesh group
1959 # @param theCriteria the list of criteria
1960 # @param binOp binary operator used when binary operator of criteria is undefined
1961 # @return SMESH_GroupOnFilter
1962 # @ingroup l2_grps_create
1963 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1964 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1965 group = self.MakeGroupByFilter(groupName, aFilter)
1968 ## Creates a mesh group by the given filter
1969 # @param groupName the name of the mesh group
1970 # @param theFilter the instance of Filter class
1971 # @return SMESH_GroupOnFilter
1972 # @ingroup l2_grps_create
1973 def MakeGroupByFilter(self, groupName, theFilter):
1974 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1975 #theFilter.SetMesh( self.mesh )
1976 #group.AddFrom( theFilter )
1977 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1981 # @ingroup l2_grps_delete
1982 def RemoveGroup(self, group):
1983 self.mesh.RemoveGroup(group)
1985 ## Removes a group with its contents
1986 # @ingroup l2_grps_delete
1987 def RemoveGroupWithContents(self, group):
1988 self.mesh.RemoveGroupWithContents(group)
1990 ## Gets the list of groups existing in the mesh in the order
1991 # of creation (starting from the oldest one)
1992 # @param elemType type of elements the groups contain; either of
1993 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
1994 # by default groups of elements of all types are returned
1995 # @return a sequence of SMESH_GroupBase
1996 # @ingroup l2_grps_create
1997 def GetGroups(self, elemType = SMESH.ALL):
1998 groups = self.mesh.GetGroups()
1999 if elemType == SMESH.ALL:
2003 if g.GetType() == elemType:
2004 typedGroups.append( g )
2009 ## Gets the number of groups existing in the mesh
2010 # @return the quantity of groups as an integer value
2011 # @ingroup l2_grps_create
2013 return self.mesh.NbGroups()
2015 ## Gets the list of names of groups existing in the mesh
2016 # @return list of strings
2017 # @ingroup l2_grps_create
2018 def GetGroupNames(self):
2019 groups = self.GetGroups()
2021 for group in groups:
2022 names.append(group.GetName())
2025 ## Finds groups by name and type
2026 # @param name name of the group of interest
2027 # @param elemType type of elements the groups contain; either of
2028 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2029 # by default one group of any type of elements is returned
2030 # if elemType == SMESH.ALL then all groups of any type are returned
2031 # @return a list of SMESH_GroupBase's
2032 # @ingroup l2_grps_create
2033 def GetGroupByName(self, name, elemType = None):
2035 for group in self.GetGroups():
2036 if group.GetName() == name:
2037 if elemType is None:
2039 if ( elemType == SMESH.ALL or
2040 group.GetType() == elemType ):
2041 groups.append( group )
2044 ## Produces a union of two groups.
2045 # A new group is created. All mesh elements that are
2046 # present in the initial groups are added to the new one
2047 # @return an instance of SMESH_Group
2048 # @ingroup l2_grps_operon
2049 def UnionGroups(self, group1, group2, name):
2050 return self.mesh.UnionGroups(group1, group2, name)
2052 ## Produces a union list of groups.
2053 # New group is created. All mesh elements that are present in
2054 # initial groups are added to the new one
2055 # @return an instance of SMESH_Group
2056 # @ingroup l2_grps_operon
2057 def UnionListOfGroups(self, groups, name):
2058 return self.mesh.UnionListOfGroups(groups, name)
2060 ## Prodices an intersection of two groups.
2061 # A new group is created. All mesh elements that are common
2062 # for the two initial groups are added to the new one.
2063 # @return an instance of SMESH_Group
2064 # @ingroup l2_grps_operon
2065 def IntersectGroups(self, group1, group2, name):
2066 return self.mesh.IntersectGroups(group1, group2, name)
2068 ## Produces an intersection of groups.
2069 # New group is created. All mesh elements that are present in all
2070 # initial groups simultaneously are added to the new one
2071 # @return an instance of SMESH_Group
2072 # @ingroup l2_grps_operon
2073 def IntersectListOfGroups(self, groups, name):
2074 return self.mesh.IntersectListOfGroups(groups, name)
2076 ## Produces a cut of two groups.
2077 # A new group is created. All mesh elements that are present in
2078 # the main group but are not present in the tool group are added to the new one
2079 # @return an instance of SMESH_Group
2080 # @ingroup l2_grps_operon
2081 def CutGroups(self, main_group, tool_group, name):
2082 return self.mesh.CutGroups(main_group, tool_group, name)
2084 ## Produces a cut of groups.
2085 # A new group is created. All mesh elements that are present in main groups
2086 # but do not present in tool groups are added to the new one
2087 # @return an instance of SMESH_Group
2088 # @ingroup l2_grps_operon
2089 def CutListOfGroups(self, main_groups, tool_groups, name):
2090 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2093 # Create a standalone group of entities basing on nodes of other groups.
2094 # \param groups - list of groups, sub-meshes or filters, of any type.
2095 # \param elemType - a type of elements to include to the new group; either of
2096 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2097 # \param name - a name of the new group.
2098 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2099 # basing on number of element nodes common with reference \a groups.
2100 # Meaning of possible values are:
2101 # - SMESH.ALL_NODES - include if all nodes are common,
2102 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2103 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2104 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2105 # \param underlyingOnly - if \c True (default), an element is included to the
2106 # new group provided that it is based on nodes of one element of \a groups.
2107 # @return an instance of SMESH_Group
2108 # @ingroup l2_grps_operon
2109 def CreateDimGroup(self, groups, elemType, name,
2110 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2111 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2113 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2116 ## Convert group on geom into standalone group
2117 # @ingroup l2_grps_delete
2118 def ConvertToStandalone(self, group):
2119 return self.mesh.ConvertToStandalone(group)
2121 # Get some info about mesh:
2122 # ------------------------
2124 ## Returns the log of nodes and elements added or removed
2125 # since the previous clear of the log.
2126 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2127 # @return list of log_block structures:
2132 # @ingroup l1_auxiliary
2133 def GetLog(self, clearAfterGet):
2134 return self.mesh.GetLog(clearAfterGet)
2136 ## Clears the log of nodes and elements added or removed since the previous
2137 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2138 # @ingroup l1_auxiliary
2140 self.mesh.ClearLog()
2142 ## Toggles auto color mode on the object.
2143 # @param theAutoColor the flag which toggles auto color mode.
2144 # @ingroup l1_auxiliary
2145 def SetAutoColor(self, theAutoColor):
2146 self.mesh.SetAutoColor(theAutoColor)
2148 ## Gets flag of object auto color mode.
2149 # @return True or False
2150 # @ingroup l1_auxiliary
2151 def GetAutoColor(self):
2152 return self.mesh.GetAutoColor()
2154 ## Gets the internal ID
2155 # @return integer value, which is the internal Id of the mesh
2156 # @ingroup l1_auxiliary
2158 return self.mesh.GetId()
2161 # @return integer value, which is the study Id of the mesh
2162 # @ingroup l1_auxiliary
2163 def GetStudyId(self):
2164 return self.mesh.GetStudyId()
2166 ## Checks the group names for duplications.
2167 # Consider the maximum group name length stored in MED file.
2168 # @return True or False
2169 # @ingroup l1_auxiliary
2170 def HasDuplicatedGroupNamesMED(self):
2171 return self.mesh.HasDuplicatedGroupNamesMED()
2173 ## Obtains the mesh editor tool
2174 # @return an instance of SMESH_MeshEditor
2175 # @ingroup l1_modifying
2176 def GetMeshEditor(self):
2179 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2180 # can be passed as argument to a method accepting mesh, group or sub-mesh
2181 # @param ids list of IDs
2182 # @param elemType type of elements; this parameter is used to distinguish
2183 # IDs of nodes from IDs of elements; by default ids are treated as
2184 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2185 # @return an instance of SMESH_IDSource
2186 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2187 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2188 # mesh.DoSomething( idSrc )
2189 # idSrc.UnRegister()
2190 # @ingroup l1_auxiliary
2191 def GetIDSource(self, ids, elemType = SMESH.ALL):
2192 return self.editor.MakeIDSource(ids, elemType)
2195 # Get informations about mesh contents:
2196 # ------------------------------------
2198 ## Gets the mesh stattistic
2199 # @return dictionary type element - count of elements
2200 # @ingroup l1_meshinfo
2201 def GetMeshInfo(self, obj = None):
2202 if not obj: obj = self.mesh
2203 return self.smeshpyD.GetMeshInfo(obj)
2205 ## Returns the number of nodes in the mesh
2206 # @return an integer value
2207 # @ingroup l1_meshinfo
2209 return self.mesh.NbNodes()
2211 ## Returns the number of elements in the mesh
2212 # @return an integer value
2213 # @ingroup l1_meshinfo
2214 def NbElements(self):
2215 return self.mesh.NbElements()
2217 ## Returns the number of 0d elements in the mesh
2218 # @return an integer value
2219 # @ingroup l1_meshinfo
2220 def Nb0DElements(self):
2221 return self.mesh.Nb0DElements()
2223 ## Returns the number of ball discrete elements in the mesh
2224 # @return an integer value
2225 # @ingroup l1_meshinfo
2227 return self.mesh.NbBalls()
2229 ## Returns the number of edges in the mesh
2230 # @return an integer value
2231 # @ingroup l1_meshinfo
2233 return self.mesh.NbEdges()
2235 ## Returns the number of edges with the given order in the mesh
2236 # @param elementOrder the order of elements:
2237 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2238 # @return an integer value
2239 # @ingroup l1_meshinfo
2240 def NbEdgesOfOrder(self, elementOrder):
2241 return self.mesh.NbEdgesOfOrder(elementOrder)
2243 ## Returns the number of faces in the mesh
2244 # @return an integer value
2245 # @ingroup l1_meshinfo
2247 return self.mesh.NbFaces()
2249 ## Returns the number of faces with the given order in the mesh
2250 # @param elementOrder the order of elements:
2251 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2252 # @return an integer value
2253 # @ingroup l1_meshinfo
2254 def NbFacesOfOrder(self, elementOrder):
2255 return self.mesh.NbFacesOfOrder(elementOrder)
2257 ## Returns the number of triangles in the mesh
2258 # @return an integer value
2259 # @ingroup l1_meshinfo
2260 def NbTriangles(self):
2261 return self.mesh.NbTriangles()
2263 ## Returns the number of triangles with the given order in the mesh
2264 # @param elementOrder is the order of elements:
2265 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2266 # @return an integer value
2267 # @ingroup l1_meshinfo
2268 def NbTrianglesOfOrder(self, elementOrder):
2269 return self.mesh.NbTrianglesOfOrder(elementOrder)
2271 ## Returns the number of biquadratic triangles in the mesh
2272 # @return an integer value
2273 # @ingroup l1_meshinfo
2274 def NbBiQuadTriangles(self):
2275 return self.mesh.NbBiQuadTriangles()
2277 ## Returns the number of quadrangles in the mesh
2278 # @return an integer value
2279 # @ingroup l1_meshinfo
2280 def NbQuadrangles(self):
2281 return self.mesh.NbQuadrangles()
2283 ## Returns the number of quadrangles with the given order in the mesh
2284 # @param elementOrder the order of elements:
2285 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2286 # @return an integer value
2287 # @ingroup l1_meshinfo
2288 def NbQuadranglesOfOrder(self, elementOrder):
2289 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2291 ## Returns the number of biquadratic quadrangles in the mesh
2292 # @return an integer value
2293 # @ingroup l1_meshinfo
2294 def NbBiQuadQuadrangles(self):
2295 return self.mesh.NbBiQuadQuadrangles()
2297 ## Returns the number of polygons of given order in the mesh
2298 # @param elementOrder the order of elements:
2299 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2300 # @return an integer value
2301 # @ingroup l1_meshinfo
2302 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2303 return self.mesh.NbPolygons(elementOrder)
2305 ## Returns the number of volumes in the mesh
2306 # @return an integer value
2307 # @ingroup l1_meshinfo
2308 def NbVolumes(self):
2309 return self.mesh.NbVolumes()
2311 ## Returns the number of volumes with the given order in the mesh
2312 # @param elementOrder the order of elements:
2313 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2314 # @return an integer value
2315 # @ingroup l1_meshinfo
2316 def NbVolumesOfOrder(self, elementOrder):
2317 return self.mesh.NbVolumesOfOrder(elementOrder)
2319 ## Returns the number of tetrahedrons in the mesh
2320 # @return an integer value
2321 # @ingroup l1_meshinfo
2323 return self.mesh.NbTetras()
2325 ## Returns the number of tetrahedrons with the given order in the mesh
2326 # @param elementOrder the order of elements:
2327 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2328 # @return an integer value
2329 # @ingroup l1_meshinfo
2330 def NbTetrasOfOrder(self, elementOrder):
2331 return self.mesh.NbTetrasOfOrder(elementOrder)
2333 ## Returns the number of hexahedrons in the mesh
2334 # @return an integer value
2335 # @ingroup l1_meshinfo
2337 return self.mesh.NbHexas()
2339 ## Returns the number of hexahedrons with the given order in the mesh
2340 # @param elementOrder the order of elements:
2341 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2342 # @return an integer value
2343 # @ingroup l1_meshinfo
2344 def NbHexasOfOrder(self, elementOrder):
2345 return self.mesh.NbHexasOfOrder(elementOrder)
2347 ## Returns the number of triquadratic hexahedrons in the mesh
2348 # @return an integer value
2349 # @ingroup l1_meshinfo
2350 def NbTriQuadraticHexas(self):
2351 return self.mesh.NbTriQuadraticHexas()
2353 ## Returns the number of pyramids in the mesh
2354 # @return an integer value
2355 # @ingroup l1_meshinfo
2356 def NbPyramids(self):
2357 return self.mesh.NbPyramids()
2359 ## Returns the number of pyramids with the given order in the mesh
2360 # @param elementOrder the order of elements:
2361 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2362 # @return an integer value
2363 # @ingroup l1_meshinfo
2364 def NbPyramidsOfOrder(self, elementOrder):
2365 return self.mesh.NbPyramidsOfOrder(elementOrder)
2367 ## Returns the number of prisms in the mesh
2368 # @return an integer value
2369 # @ingroup l1_meshinfo
2371 return self.mesh.NbPrisms()
2373 ## Returns the number of prisms with the given order in the mesh
2374 # @param elementOrder the order of elements:
2375 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2376 # @return an integer value
2377 # @ingroup l1_meshinfo
2378 def NbPrismsOfOrder(self, elementOrder):
2379 return self.mesh.NbPrismsOfOrder(elementOrder)
2381 ## Returns the number of hexagonal prisms in the mesh
2382 # @return an integer value
2383 # @ingroup l1_meshinfo
2384 def NbHexagonalPrisms(self):
2385 return self.mesh.NbHexagonalPrisms()
2387 ## Returns the number of polyhedrons in the mesh
2388 # @return an integer value
2389 # @ingroup l1_meshinfo
2390 def NbPolyhedrons(self):
2391 return self.mesh.NbPolyhedrons()
2393 ## Returns the number of submeshes in the mesh
2394 # @return an integer value
2395 # @ingroup l1_meshinfo
2396 def NbSubMesh(self):
2397 return self.mesh.NbSubMesh()
2399 ## Returns the list of mesh elements IDs
2400 # @return the list of integer values
2401 # @ingroup l1_meshinfo
2402 def GetElementsId(self):
2403 return self.mesh.GetElementsId()
2405 ## Returns the list of IDs of mesh elements with the given type
2406 # @param elementType the required type of elements, either of
2407 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2408 # @return list of integer values
2409 # @ingroup l1_meshinfo
2410 def GetElementsByType(self, elementType):
2411 return self.mesh.GetElementsByType(elementType)
2413 ## Returns the list of mesh nodes IDs
2414 # @return the list of integer values
2415 # @ingroup l1_meshinfo
2416 def GetNodesId(self):
2417 return self.mesh.GetNodesId()
2419 # Get the information about mesh elements:
2420 # ------------------------------------
2422 ## Returns the type of mesh element
2423 # @return the value from SMESH::ElementType enumeration
2424 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2425 # @ingroup l1_meshinfo
2426 def GetElementType(self, id, iselem=True):
2427 return self.mesh.GetElementType(id, iselem)
2429 ## Returns the geometric type of mesh element
2430 # @return the value from SMESH::EntityType enumeration
2431 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2432 # @ingroup l1_meshinfo
2433 def GetElementGeomType(self, id):
2434 return self.mesh.GetElementGeomType(id)
2436 ## Returns the shape type of mesh element
2437 # @return the value from SMESH::GeometryType enumeration.
2438 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2439 # @ingroup l1_meshinfo
2440 def GetElementShape(self, id):
2441 return self.mesh.GetElementShape(id)
2443 ## Returns the list of submesh elements IDs
2444 # @param Shape a geom object(sub-shape) IOR
2445 # Shape must be the sub-shape of a ShapeToMesh()
2446 # @return the list of integer values
2447 # @ingroup l1_meshinfo
2448 def GetSubMeshElementsId(self, Shape):
2449 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2450 ShapeID = Shape.GetSubShapeIndices()[0]
2453 return self.mesh.GetSubMeshElementsId(ShapeID)
2455 ## Returns the list of submesh nodes IDs
2456 # @param Shape a geom object(sub-shape) IOR
2457 # Shape must be the sub-shape of a ShapeToMesh()
2458 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2459 # @return the list of integer values
2460 # @ingroup l1_meshinfo
2461 def GetSubMeshNodesId(self, Shape, all):
2462 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2463 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2466 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2468 ## Returns type of elements on given shape
2469 # @param Shape a geom object(sub-shape) IOR
2470 # Shape must be a sub-shape of a ShapeToMesh()
2471 # @return element type
2472 # @ingroup l1_meshinfo
2473 def GetSubMeshElementType(self, Shape):
2474 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2475 ShapeID = Shape.GetSubShapeIndices()[0]
2478 return self.mesh.GetSubMeshElementType(ShapeID)
2480 ## Gets the mesh description
2481 # @return string value
2482 # @ingroup l1_meshinfo
2484 return self.mesh.Dump()
2487 # Get the information about nodes and elements of a mesh by its IDs:
2488 # -----------------------------------------------------------
2490 ## Gets XYZ coordinates of a node
2491 # \n If there is no nodes for the given ID - returns an empty list
2492 # @return a list of double precision values
2493 # @ingroup l1_meshinfo
2494 def GetNodeXYZ(self, id):
2495 return self.mesh.GetNodeXYZ(id)
2497 ## Returns list of IDs of inverse elements for the given node
2498 # \n If there is no node for the given ID - returns an empty list
2499 # @return a list of integer values
2500 # @ingroup l1_meshinfo
2501 def GetNodeInverseElements(self, id):
2502 return self.mesh.GetNodeInverseElements(id)
2504 ## @brief Returns the position of a node on the shape
2505 # @return SMESH::NodePosition
2506 # @ingroup l1_meshinfo
2507 def GetNodePosition(self,NodeID):
2508 return self.mesh.GetNodePosition(NodeID)
2510 ## @brief Returns the position of an element on the shape
2511 # @return SMESH::ElementPosition
2512 # @ingroup l1_meshinfo
2513 def GetElementPosition(self,ElemID):
2514 return self.mesh.GetElementPosition(ElemID)
2516 ## Returns the ID of the shape, on which the given node was generated.
2517 # @return an integer value > 0 or -1 if there is no node for the given
2518 # ID or the node is not assigned to any geometry
2519 # @ingroup l1_meshinfo
2520 def GetShapeID(self, id):
2521 return self.mesh.GetShapeID(id)
2523 ## Returns the ID of the shape, on which the given element was generated.
2524 # @return an integer value > 0 or -1 if there is no element for the given
2525 # ID or the element is not assigned to any geometry
2526 # @ingroup l1_meshinfo
2527 def GetShapeIDForElem(self,id):
2528 return self.mesh.GetShapeIDForElem(id)
2530 ## Returns the number of nodes of the given element
2531 # @return an integer value > 0 or -1 if there is no element for the given ID
2532 # @ingroup l1_meshinfo
2533 def GetElemNbNodes(self, id):
2534 return self.mesh.GetElemNbNodes(id)
2536 ## Returns the node ID the given (zero based) index for the given element
2537 # \n If there is no element for the given ID - returns -1
2538 # \n If there is no node for the given index - returns -2
2539 # @return an integer value
2540 # @ingroup l1_meshinfo
2541 def GetElemNode(self, id, index):
2542 return self.mesh.GetElemNode(id, index)
2544 ## Returns the IDs of nodes of the given element
2545 # @return a list of integer values
2546 # @ingroup l1_meshinfo
2547 def GetElemNodes(self, id):
2548 return self.mesh.GetElemNodes(id)
2550 ## Returns true if the given node is the medium node in the given quadratic element
2551 # @ingroup l1_meshinfo
2552 def IsMediumNode(self, elementID, nodeID):
2553 return self.mesh.IsMediumNode(elementID, nodeID)
2555 ## Returns true if the given node is the medium node in one of quadratic elements
2556 # @param nodeID ID of the node
2557 # @param elementType the type of elements to check a state of the node, either of
2558 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2559 # @ingroup l1_meshinfo
2560 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2561 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2563 ## Returns the number of edges for the given element
2564 # @ingroup l1_meshinfo
2565 def ElemNbEdges(self, id):
2566 return self.mesh.ElemNbEdges(id)
2568 ## Returns the number of faces for the given element
2569 # @ingroup l1_meshinfo
2570 def ElemNbFaces(self, id):
2571 return self.mesh.ElemNbFaces(id)
2573 ## Returns nodes of given face (counted from zero) for given volumic element.
2574 # @ingroup l1_meshinfo
2575 def GetElemFaceNodes(self,elemId, faceIndex):
2576 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2578 ## Returns three components of normal of given mesh face
2579 # (or an empty array in KO case)
2580 # @ingroup l1_meshinfo
2581 def GetFaceNormal(self, faceId, normalized=False):
2582 return self.mesh.GetFaceNormal(faceId,normalized)
2584 ## Returns an element based on all given nodes.
2585 # @ingroup l1_meshinfo
2586 def FindElementByNodes(self,nodes):
2587 return self.mesh.FindElementByNodes(nodes)
2589 ## Returns true if the given element is a polygon
2590 # @ingroup l1_meshinfo
2591 def IsPoly(self, id):
2592 return self.mesh.IsPoly(id)
2594 ## Returns true if the given element is quadratic
2595 # @ingroup l1_meshinfo
2596 def IsQuadratic(self, id):
2597 return self.mesh.IsQuadratic(id)
2599 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2600 # @ingroup l1_meshinfo
2601 def GetBallDiameter(self, id):
2602 return self.mesh.GetBallDiameter(id)
2604 ## Returns XYZ coordinates of the barycenter of the given element
2605 # \n If there is no element for the given ID - returns an empty list
2606 # @return a list of three double values
2607 # @ingroup l1_meshinfo
2608 def BaryCenter(self, id):
2609 return self.mesh.BaryCenter(id)
2611 ## Passes mesh elements through the given filter and return IDs of fitting elements
2612 # @param theFilter SMESH_Filter
2613 # @return a list of ids
2614 # @ingroup l1_controls
2615 def GetIdsFromFilter(self, theFilter):
2616 theFilter.SetMesh( self.mesh )
2617 return theFilter.GetIDs()
2619 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2620 # Returns a list of special structures (borders).
2621 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2622 # @ingroup l1_controls
2623 def GetFreeBorders(self):
2624 aFilterMgr = self.smeshpyD.CreateFilterManager()
2625 aPredicate = aFilterMgr.CreateFreeEdges()
2626 aPredicate.SetMesh(self.mesh)
2627 aBorders = aPredicate.GetBorders()
2628 aFilterMgr.UnRegister()
2632 # Get mesh measurements information:
2633 # ------------------------------------
2635 ## Get minimum distance between two nodes, elements or distance to the origin
2636 # @param id1 first node/element id
2637 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2638 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2639 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2640 # @return minimum distance value
2641 # @sa GetMinDistance()
2642 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2643 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2644 return aMeasure.value
2646 ## Get measure structure specifying minimum distance data between two objects
2647 # @param id1 first node/element id
2648 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2649 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2650 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2651 # @return Measure structure
2653 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2655 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2657 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2660 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2662 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2667 aMeasurements = self.smeshpyD.CreateMeasurements()
2668 aMeasure = aMeasurements.MinDistance(id1, id2)
2669 genObjUnRegister([aMeasurements,id1, id2])
2672 ## Get bounding box of the specified object(s)
2673 # @param objects single source object or list of source objects or list of nodes/elements IDs
2674 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2675 # @c False specifies that @a objects are nodes
2676 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2677 # @sa GetBoundingBox()
2678 def BoundingBox(self, objects=None, isElem=False):
2679 result = self.GetBoundingBox(objects, isElem)
2683 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2686 ## Get measure structure specifying bounding box data of the specified object(s)
2687 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2688 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2689 # @c False specifies that @a objects are nodes
2690 # @return Measure structure
2692 def GetBoundingBox(self, IDs=None, isElem=False):
2695 elif isinstance(IDs, tuple):
2697 if not isinstance(IDs, list):
2699 if len(IDs) > 0 and isinstance(IDs[0], int):
2702 unRegister = genObjUnRegister()
2704 if isinstance(o, Mesh):
2705 srclist.append(o.mesh)
2706 elif hasattr(o, "_narrow"):
2707 src = o._narrow(SMESH.SMESH_IDSource)
2708 if src: srclist.append(src)
2710 elif isinstance(o, list):
2712 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2714 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2715 unRegister.set( srclist[-1] )
2718 aMeasurements = self.smeshpyD.CreateMeasurements()
2719 unRegister.set( aMeasurements )
2720 aMeasure = aMeasurements.BoundingBox(srclist)
2723 # Mesh edition (SMESH_MeshEditor functionality):
2724 # ---------------------------------------------
2726 ## Removes the elements from the mesh by ids
2727 # @param IDsOfElements is a list of ids of elements to remove
2728 # @return True or False
2729 # @ingroup l2_modif_del
2730 def RemoveElements(self, IDsOfElements):
2731 return self.editor.RemoveElements(IDsOfElements)
2733 ## Removes nodes from mesh by ids
2734 # @param IDsOfNodes is a list of ids of nodes to remove
2735 # @return True or False
2736 # @ingroup l2_modif_del
2737 def RemoveNodes(self, IDsOfNodes):
2738 return self.editor.RemoveNodes(IDsOfNodes)
2740 ## Removes all orphan (free) nodes from mesh
2741 # @return number of the removed nodes
2742 # @ingroup l2_modif_del
2743 def RemoveOrphanNodes(self):
2744 return self.editor.RemoveOrphanNodes()
2746 ## Add a node to the mesh by coordinates
2747 # @return Id of the new node
2748 # @ingroup l2_modif_add
2749 def AddNode(self, x, y, z):
2750 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2751 if hasVars: self.mesh.SetParameters(Parameters)
2752 return self.editor.AddNode( x, y, z)
2754 ## Creates a 0D element on a node with given number.
2755 # @param IDOfNode the ID of node for creation of the element.
2756 # @return the Id of the new 0D element
2757 # @ingroup l2_modif_add
2758 def Add0DElement(self, IDOfNode):
2759 return self.editor.Add0DElement(IDOfNode)
2761 ## Create 0D elements on all nodes of the given elements except those
2762 # nodes on which a 0D element already exists.
2763 # @param theObject an object on whose nodes 0D elements will be created.
2764 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2765 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2766 # @param theGroupName optional name of a group to add 0D elements created
2767 # and/or found on nodes of \a theObject.
2768 # @return an object (a new group or a temporary SMESH_IDSource) holding
2769 # IDs of new and/or found 0D elements. IDs of 0D elements
2770 # can be retrieved from the returned object by calling GetIDs()
2771 # @ingroup l2_modif_add
2772 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2773 unRegister = genObjUnRegister()
2774 if isinstance( theObject, Mesh ):
2775 theObject = theObject.GetMesh()
2776 if isinstance( theObject, list ):
2777 theObject = self.GetIDSource( theObject, SMESH.ALL )
2778 unRegister.set( theObject )
2779 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2781 ## Creates a ball element on a node with given ID.
2782 # @param IDOfNode the ID of node for creation of the element.
2783 # @param diameter the bal diameter.
2784 # @return the Id of the new ball element
2785 # @ingroup l2_modif_add
2786 def AddBall(self, IDOfNode, diameter):
2787 return self.editor.AddBall( IDOfNode, diameter )
2789 ## Creates a linear or quadratic edge (this is determined
2790 # by the number of given nodes).
2791 # @param IDsOfNodes the list of node IDs for creation of the element.
2792 # The order of nodes in this list should correspond to the description
2793 # of MED. \n This description is located by the following link:
2794 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2795 # @return the Id of the new edge
2796 # @ingroup l2_modif_add
2797 def AddEdge(self, IDsOfNodes):
2798 return self.editor.AddEdge(IDsOfNodes)
2800 ## Creates a linear or quadratic face (this is determined
2801 # by the number of given nodes).
2802 # @param IDsOfNodes the list of node IDs for creation of the element.
2803 # The order of nodes in this list should correspond to the description
2804 # of MED. \n This description is located by the following link:
2805 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2806 # @return the Id of the new face
2807 # @ingroup l2_modif_add
2808 def AddFace(self, IDsOfNodes):
2809 return self.editor.AddFace(IDsOfNodes)
2811 ## Adds a polygonal face to the mesh by the list of node IDs
2812 # @param IdsOfNodes the list of node IDs for creation of the element.
2813 # @return the Id of the new face
2814 # @ingroup l2_modif_add
2815 def AddPolygonalFace(self, IdsOfNodes):
2816 return self.editor.AddPolygonalFace(IdsOfNodes)
2818 ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2819 # @param IdsOfNodes the list of node IDs for creation of the element;
2820 # corner nodes follow first.
2821 # @return the Id of the new face
2822 # @ingroup l2_modif_add
2823 def AddQuadPolygonalFace(self, IdsOfNodes):
2824 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2826 ## Creates both simple and quadratic volume (this is determined
2827 # by the number of given nodes).
2828 # @param IDsOfNodes the list of node IDs for creation of the element.
2829 # The order of nodes in this list should correspond to the description
2830 # of MED. \n This description is located by the following link:
2831 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2832 # @return the Id of the new volumic element
2833 # @ingroup l2_modif_add
2834 def AddVolume(self, IDsOfNodes):
2835 return self.editor.AddVolume(IDsOfNodes)
2837 ## Creates a volume of many faces, giving nodes for each face.
2838 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2839 # @param Quantities the list of integer values, Quantities[i]
2840 # gives the quantity of nodes in face number i.
2841 # @return the Id of the new volumic element
2842 # @ingroup l2_modif_add
2843 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2844 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2846 ## Creates a volume of many faces, giving the IDs of the existing faces.
2847 # @param IdsOfFaces the list of face IDs for volume creation.
2849 # Note: The created volume will refer only to the nodes
2850 # of the given faces, not to the faces themselves.
2851 # @return the Id of the new volumic element
2852 # @ingroup l2_modif_add
2853 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2854 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2857 ## @brief Binds a node to a vertex
2858 # @param NodeID a node ID
2859 # @param Vertex a vertex or vertex ID
2860 # @return True if succeed else raises an exception
2861 # @ingroup l2_modif_add
2862 def SetNodeOnVertex(self, NodeID, Vertex):
2863 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2864 VertexID = Vertex.GetSubShapeIndices()[0]
2868 self.editor.SetNodeOnVertex(NodeID, VertexID)
2869 except SALOME.SALOME_Exception, inst:
2870 raise ValueError, inst.details.text
2874 ## @brief Stores the node position on an edge
2875 # @param NodeID a node ID
2876 # @param Edge an edge or edge ID
2877 # @param paramOnEdge a parameter on the edge where the node is located
2878 # @return True if succeed else raises an exception
2879 # @ingroup l2_modif_add
2880 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2881 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2882 EdgeID = Edge.GetSubShapeIndices()[0]
2886 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2887 except SALOME.SALOME_Exception, inst:
2888 raise ValueError, inst.details.text
2891 ## @brief Stores node position on a face
2892 # @param NodeID a node ID
2893 # @param Face a face or face ID
2894 # @param u U parameter on the face where the node is located
2895 # @param v V parameter on the face where the node is located
2896 # @return True if succeed else raises an exception
2897 # @ingroup l2_modif_add
2898 def SetNodeOnFace(self, NodeID, Face, u, v):
2899 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2900 FaceID = Face.GetSubShapeIndices()[0]
2904 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2905 except SALOME.SALOME_Exception, inst:
2906 raise ValueError, inst.details.text
2909 ## @brief Binds a node to a solid
2910 # @param NodeID a node ID
2911 # @param Solid a solid or solid ID
2912 # @return True if succeed else raises an exception
2913 # @ingroup l2_modif_add
2914 def SetNodeInVolume(self, NodeID, Solid):
2915 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2916 SolidID = Solid.GetSubShapeIndices()[0]
2920 self.editor.SetNodeInVolume(NodeID, SolidID)
2921 except SALOME.SALOME_Exception, inst:
2922 raise ValueError, inst.details.text
2925 ## @brief Bind an element to a shape
2926 # @param ElementID an element ID
2927 # @param Shape a shape or shape ID
2928 # @return True if succeed else raises an exception
2929 # @ingroup l2_modif_add
2930 def SetMeshElementOnShape(self, ElementID, Shape):
2931 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2932 ShapeID = Shape.GetSubShapeIndices()[0]
2936 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2937 except SALOME.SALOME_Exception, inst:
2938 raise ValueError, inst.details.text
2942 ## Moves the node with the given id
2943 # @param NodeID the id of the node
2944 # @param x a new X coordinate
2945 # @param y a new Y coordinate
2946 # @param z a new Z coordinate
2947 # @return True if succeed else False
2948 # @ingroup l2_modif_movenode
2949 def MoveNode(self, NodeID, x, y, z):
2950 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2951 if hasVars: self.mesh.SetParameters(Parameters)
2952 return self.editor.MoveNode(NodeID, x, y, z)
2954 ## Finds the node closest to a point and moves it to a point location
2955 # @param x the X coordinate of a point
2956 # @param y the Y coordinate of a point
2957 # @param z the Z coordinate of a point
2958 # @param NodeID if specified (>0), the node with this ID is moved,
2959 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2960 # @return the ID of a node
2961 # @ingroup l2_modif_throughp
2962 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2963 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2964 if hasVars: self.mesh.SetParameters(Parameters)
2965 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2967 ## Finds the node closest to a point
2968 # @param x the X coordinate of a point
2969 # @param y the Y coordinate of a point
2970 # @param z the Z coordinate of a point
2971 # @return the ID of a node
2972 # @ingroup l2_modif_throughp
2973 def FindNodeClosestTo(self, x, y, z):
2974 #preview = self.mesh.GetMeshEditPreviewer()
2975 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2976 return self.editor.FindNodeClosestTo(x, y, z)
2978 ## Finds the elements where a point lays IN or ON
2979 # @param x the X coordinate of a point
2980 # @param y the Y coordinate of a point
2981 # @param z the Z coordinate of a point
2982 # @param elementType type of elements to find; either of
2983 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
2984 # means elements of any type excluding nodes, discrete and 0D elements.
2985 # @param meshPart a part of mesh (group, sub-mesh) to search within
2986 # @return list of IDs of found elements
2987 # @ingroup l2_modif_throughp
2988 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2990 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2992 return self.editor.FindElementsByPoint(x, y, z, elementType)
2994 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2995 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2996 # UNKNOWN state means that either mesh is wrong or the analysis fails.
2997 def GetPointState(self, x, y, z):
2998 return self.editor.GetPointState(x, y, z)
3000 ## Finds the node closest to a point and moves it to a point location
3001 # @param x the X coordinate of a point
3002 # @param y the Y coordinate of a point
3003 # @param z the Z coordinate of a point
3004 # @return the ID of a moved node
3005 # @ingroup l2_modif_throughp
3006 def MeshToPassThroughAPoint(self, x, y, z):
3007 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3009 ## Replaces two neighbour triangles sharing Node1-Node2 link
3010 # with the triangles built on the same 4 nodes but having other common link.
3011 # @param NodeID1 the ID of the first node
3012 # @param NodeID2 the ID of the second node
3013 # @return false if proper faces were not found
3014 # @ingroup l2_modif_invdiag
3015 def InverseDiag(self, NodeID1, NodeID2):
3016 return self.editor.InverseDiag(NodeID1, NodeID2)
3018 ## Replaces two neighbour triangles sharing Node1-Node2 link
3019 # with a quadrangle built on the same 4 nodes.
3020 # @param NodeID1 the ID of the first node
3021 # @param NodeID2 the ID of the second node
3022 # @return false if proper faces were not found
3023 # @ingroup l2_modif_unitetri
3024 def DeleteDiag(self, NodeID1, NodeID2):
3025 return self.editor.DeleteDiag(NodeID1, NodeID2)
3027 ## Reorients elements by ids
3028 # @param IDsOfElements if undefined reorients all mesh elements
3029 # @return True if succeed else False
3030 # @ingroup l2_modif_changori
3031 def Reorient(self, IDsOfElements=None):
3032 if IDsOfElements == None:
3033 IDsOfElements = self.GetElementsId()
3034 return self.editor.Reorient(IDsOfElements)
3036 ## Reorients all elements of the object
3037 # @param theObject mesh, submesh or group
3038 # @return True if succeed else False
3039 # @ingroup l2_modif_changori
3040 def ReorientObject(self, theObject):
3041 if ( isinstance( theObject, Mesh )):
3042 theObject = theObject.GetMesh()
3043 return self.editor.ReorientObject(theObject)
3045 ## Reorient faces contained in \a the2DObject.
3046 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3047 # @param theDirection is a desired direction of normal of \a theFace.
3048 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3049 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3050 # compared with theDirection. It can be either ID of face or a point
3051 # by which the face will be found. The point can be given as either
3052 # a GEOM vertex or a list of point coordinates.
3053 # @return number of reoriented faces
3054 # @ingroup l2_modif_changori
3055 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3056 unRegister = genObjUnRegister()
3058 if isinstance( the2DObject, Mesh ):
3059 the2DObject = the2DObject.GetMesh()
3060 if isinstance( the2DObject, list ):
3061 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3062 unRegister.set( the2DObject )
3063 # check theDirection
3064 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3065 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3066 if isinstance( theDirection, list ):
3067 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3068 # prepare theFace and thePoint
3069 theFace = theFaceOrPoint
3070 thePoint = PointStruct(0,0,0)
3071 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3072 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3074 if isinstance( theFaceOrPoint, list ):
3075 thePoint = PointStruct( *theFaceOrPoint )
3077 if isinstance( theFaceOrPoint, PointStruct ):
3078 thePoint = theFaceOrPoint
3080 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3082 ## Reorient faces according to adjacent volumes.
3083 # @param the2DObject is a mesh, sub-mesh, group or list of
3084 # either IDs of faces or face groups.
3085 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3086 # @param theOutsideNormal to orient faces to have their normals
3087 # pointing either \a outside or \a inside the adjacent volumes.
3088 # @return number of reoriented faces.
3089 # @ingroup l2_modif_changori
3090 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3091 unRegister = genObjUnRegister()
3093 if not isinstance( the2DObject, list ):
3094 the2DObject = [ the2DObject ]
3095 elif the2DObject and isinstance( the2DObject[0], int ):
3096 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3097 unRegister.set( the2DObject )
3098 the2DObject = [ the2DObject ]
3099 for i,obj2D in enumerate( the2DObject ):
3100 if isinstance( obj2D, Mesh ):
3101 the2DObject[i] = obj2D.GetMesh()
3102 if isinstance( obj2D, list ):
3103 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3104 unRegister.set( the2DObject[i] )
3106 if isinstance( the3DObject, Mesh ):
3107 the3DObject = the3DObject.GetMesh()
3108 if isinstance( the3DObject, list ):
3109 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3110 unRegister.set( the3DObject )
3111 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3113 ## Fuses the neighbouring triangles into quadrangles.
3114 # @param IDsOfElements The triangles to be fused.
3115 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3116 # choose a neighbour to fuse with.
3117 # Type SMESH.FunctorType._items in the Python Console to see all items.
3118 # Note that not all items corresponds to numerical functors.
3119 # @param MaxAngle is the maximum angle between element normals at which the fusion
3120 # is still performed; theMaxAngle is mesured in radians.
3121 # Also it could be a name of variable which defines angle in degrees.
3122 # @return TRUE in case of success, FALSE otherwise.
3123 # @ingroup l2_modif_unitetri
3124 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3125 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3126 self.mesh.SetParameters(Parameters)
3127 if not IDsOfElements:
3128 IDsOfElements = self.GetElementsId()
3129 Functor = self.smeshpyD.GetFunctor(theCriterion)
3130 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3132 ## Fuses the neighbouring triangles of the object into quadrangles
3133 # @param theObject is mesh, submesh or group
3134 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3135 # choose a neighbour to fuse with.
3136 # Type SMESH.FunctorType._items in the Python Console to see all items.
3137 # Note that not all items corresponds to numerical functors.
3138 # @param MaxAngle a max angle between element normals at which the fusion
3139 # is still performed; theMaxAngle is mesured in radians.
3140 # @return TRUE in case of success, FALSE otherwise.
3141 # @ingroup l2_modif_unitetri
3142 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3143 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3144 self.mesh.SetParameters(Parameters)
3145 if isinstance( theObject, Mesh ):
3146 theObject = theObject.GetMesh()
3147 Functor = self.smeshpyD.GetFunctor(theCriterion)
3148 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3150 ## Splits quadrangles into triangles.
3151 # @param IDsOfElements the faces to be splitted.
3152 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3153 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3154 # value, then quadrangles will be split by the smallest diagonal.
3155 # Type SMESH.FunctorType._items in the Python Console to see all items.
3156 # Note that not all items corresponds to numerical functors.
3157 # @return TRUE in case of success, FALSE otherwise.
3158 # @ingroup l2_modif_cutquadr
3159 def QuadToTri (self, IDsOfElements, theCriterion = None):
3160 if IDsOfElements == []:
3161 IDsOfElements = self.GetElementsId()
3162 if theCriterion is None:
3163 theCriterion = FT_MaxElementLength2D
3164 Functor = self.smeshpyD.GetFunctor(theCriterion)
3165 return self.editor.QuadToTri(IDsOfElements, Functor)
3167 ## Splits quadrangles into triangles.
3168 # @param theObject the object from which the list of elements is taken,
3169 # this is mesh, submesh or group
3170 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3171 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3172 # value, then quadrangles will be split by the smallest diagonal.
3173 # Type SMESH.FunctorType._items in the Python Console to see all items.
3174 # Note that not all items corresponds to numerical functors.
3175 # @return TRUE in case of success, FALSE otherwise.
3176 # @ingroup l2_modif_cutquadr
3177 def QuadToTriObject (self, theObject, theCriterion = None):
3178 if ( isinstance( theObject, Mesh )):
3179 theObject = theObject.GetMesh()
3180 if theCriterion is None:
3181 theCriterion = FT_MaxElementLength2D
3182 Functor = self.smeshpyD.GetFunctor(theCriterion)
3183 return self.editor.QuadToTriObject(theObject, Functor)
3185 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3187 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3188 # group or a list of face IDs. By default all quadrangles are split
3189 # @ingroup l2_modif_cutquadr
3190 def QuadTo4Tri (self, theElements=[]):
3191 unRegister = genObjUnRegister()
3192 if isinstance( theElements, Mesh ):
3193 theElements = theElements.mesh
3194 elif not theElements:
3195 theElements = self.mesh
3196 elif isinstance( theElements, list ):
3197 theElements = self.GetIDSource( theElements, SMESH.FACE )
3198 unRegister.set( theElements )
3199 return self.editor.QuadTo4Tri( theElements )
3201 ## Splits quadrangles into triangles.
3202 # @param IDsOfElements the faces to be splitted
3203 # @param Diag13 is used to choose a diagonal for splitting.
3204 # @return TRUE in case of success, FALSE otherwise.
3205 # @ingroup l2_modif_cutquadr
3206 def SplitQuad (self, IDsOfElements, Diag13):
3207 if IDsOfElements == []:
3208 IDsOfElements = self.GetElementsId()
3209 return self.editor.SplitQuad(IDsOfElements, Diag13)
3211 ## Splits quadrangles into triangles.
3212 # @param theObject the object from which the list of elements is taken,
3213 # this is mesh, submesh or group
3214 # @param Diag13 is used to choose a diagonal for splitting.
3215 # @return TRUE in case of success, FALSE otherwise.
3216 # @ingroup l2_modif_cutquadr
3217 def SplitQuadObject (self, theObject, Diag13):
3218 if ( isinstance( theObject, Mesh )):
3219 theObject = theObject.GetMesh()
3220 return self.editor.SplitQuadObject(theObject, Diag13)
3222 ## Finds a better splitting of the given quadrangle.
3223 # @param IDOfQuad the ID of the quadrangle to be splitted.
3224 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3225 # choose a diagonal for splitting.
3226 # Type SMESH.FunctorType._items in the Python Console to see all items.
3227 # Note that not all items corresponds to numerical functors.
3228 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3229 # diagonal is better, 0 if error occurs.
3230 # @ingroup l2_modif_cutquadr
3231 def BestSplit (self, IDOfQuad, theCriterion):
3232 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3234 ## Splits volumic elements into tetrahedrons
3235 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3236 # @param method flags passing splitting method:
3237 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3238 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3239 # @ingroup l2_modif_cutquadr
3240 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3241 unRegister = genObjUnRegister()
3242 if isinstance( elems, Mesh ):
3243 elems = elems.GetMesh()
3244 if ( isinstance( elems, list )):
3245 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3246 unRegister.set( elems )
3247 self.editor.SplitVolumesIntoTetra(elems, method)
3250 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3251 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3252 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3253 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3254 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3255 # will be split in order to keep the mesh conformal.
3256 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3257 # if None (default), all bi-quadratic elements will be split
3258 # @ingroup l2_modif_cutquadr
3259 def SplitBiQuadraticIntoLinear(self, elems=None):
3260 unRegister = genObjUnRegister()
3261 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3262 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3263 unRegister.set( elems )
3265 elems = [ self.GetMesh() ]
3266 if isinstance( elems, Mesh ):
3267 elems = [ elems.GetMesh() ]
3268 if not isinstance( elems, list ):
3270 self.editor.SplitBiQuadraticIntoLinear( elems )
3272 ## Splits hexahedra into prisms
3273 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3274 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3275 # gives a normal vector defining facets to split into triangles.
3276 # @a startHexPoint can be either a triple of coordinates or a vertex.
3277 # @param facetNormal a normal to a facet to split into triangles of a
3278 # hexahedron found by @a startHexPoint.
3279 # @a facetNormal can be either a triple of coordinates or an edge.
3280 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3281 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3282 # @param allDomains if @c False, only hexahedra adjacent to one closest
3283 # to @a startHexPoint are split, else @a startHexPoint
3284 # is used to find the facet to split in all domains present in @a elems.
3285 # @ingroup l2_modif_cutquadr
3286 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3287 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3289 unRegister = genObjUnRegister()
3290 if isinstance( elems, Mesh ):
3291 elems = elems.GetMesh()
3292 if ( isinstance( elems, list )):
3293 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3294 unRegister.set( elems )
3297 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3298 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3299 elif isinstance( startHexPoint, list ):
3300 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3303 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3304 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3305 elif isinstance( facetNormal, list ):
3306 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3309 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3311 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3313 ## Splits quadrangle faces near triangular facets of volumes
3315 # @ingroup l1_auxiliary
3316 def SplitQuadsNearTriangularFacets(self):
3317 faces_array = self.GetElementsByType(SMESH.FACE)
3318 for face_id in faces_array:
3319 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3320 quad_nodes = self.mesh.GetElemNodes(face_id)
3321 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3322 isVolumeFound = False
3323 for node1_elem in node1_elems:
3324 if not isVolumeFound:
3325 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3326 nb_nodes = self.GetElemNbNodes(node1_elem)
3327 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3328 volume_elem = node1_elem
3329 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3330 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3331 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3332 isVolumeFound = True
3333 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3334 self.SplitQuad([face_id], False) # diagonal 2-4
3335 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3336 isVolumeFound = True
3337 self.SplitQuad([face_id], True) # diagonal 1-3
3338 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3339 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3340 isVolumeFound = True
3341 self.SplitQuad([face_id], True) # diagonal 1-3
3343 ## @brief Splits hexahedrons into tetrahedrons.
3345 # This operation uses pattern mapping functionality for splitting.
3346 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3347 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3348 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3349 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3350 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3351 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3352 # @return TRUE in case of success, FALSE otherwise.
3353 # @ingroup l1_auxiliary
3354 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3355 # Pattern: 5.---------.6
3360 # (0,0,1) 4.---------.7 * |
3367 # (0,0,0) 0.---------.3
3368 pattern_tetra = "!!! Nb of points: \n 8 \n\
3378 !!! Indices of points of 6 tetras: \n\
3386 pattern = self.smeshpyD.GetPattern()
3387 isDone = pattern.LoadFromFile(pattern_tetra)
3389 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3392 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3393 isDone = pattern.MakeMesh(self.mesh, False, False)
3394 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3396 # split quafrangle faces near triangular facets of volumes
3397 self.SplitQuadsNearTriangularFacets()
3401 ## @brief Split hexahedrons into prisms.
3403 # Uses the pattern mapping functionality for splitting.
3404 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3405 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3406 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3407 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3408 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3409 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3410 # @return TRUE in case of success, FALSE otherwise.
3411 # @ingroup l1_auxiliary
3412 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3413 # Pattern: 5.---------.6
3418 # (0,0,1) 4.---------.7 |
3425 # (0,0,0) 0.---------.3
3426 pattern_prism = "!!! Nb of points: \n 8 \n\
3436 !!! Indices of points of 2 prisms: \n\
3440 pattern = self.smeshpyD.GetPattern()
3441 isDone = pattern.LoadFromFile(pattern_prism)
3443 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3446 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3447 isDone = pattern.MakeMesh(self.mesh, False, False)
3448 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3450 # Splits quafrangle faces near triangular facets of volumes
3451 self.SplitQuadsNearTriangularFacets()
3455 ## Smoothes elements
3456 # @param IDsOfElements the list if ids of elements to smooth
3457 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3458 # Note that nodes built on edges and boundary nodes are always fixed.
3459 # @param MaxNbOfIterations the maximum number of iterations
3460 # @param MaxAspectRatio varies in range [1.0, inf]
3461 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3462 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3463 # @return TRUE in case of success, FALSE otherwise.
3464 # @ingroup l2_modif_smooth
3465 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3466 MaxNbOfIterations, MaxAspectRatio, Method):
3467 if IDsOfElements == []:
3468 IDsOfElements = self.GetElementsId()
3469 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3470 self.mesh.SetParameters(Parameters)
3471 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3472 MaxNbOfIterations, MaxAspectRatio, Method)
3474 ## Smoothes elements which belong to the given object
3475 # @param theObject the object to smooth
3476 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3477 # Note that nodes built on edges and boundary nodes are always fixed.
3478 # @param MaxNbOfIterations the maximum number of iterations
3479 # @param MaxAspectRatio varies in range [1.0, inf]
3480 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3481 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3482 # @return TRUE in case of success, FALSE otherwise.
3483 # @ingroup l2_modif_smooth
3484 def SmoothObject(self, theObject, IDsOfFixedNodes,
3485 MaxNbOfIterations, MaxAspectRatio, Method):
3486 if ( isinstance( theObject, Mesh )):
3487 theObject = theObject.GetMesh()
3488 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3489 MaxNbOfIterations, MaxAspectRatio, Method)
3491 ## Parametrically smoothes the given elements
3492 # @param IDsOfElements the list if ids of elements to smooth
3493 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3494 # Note that nodes built on edges and boundary nodes are always fixed.
3495 # @param MaxNbOfIterations the maximum number of iterations
3496 # @param MaxAspectRatio varies in range [1.0, inf]
3497 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3498 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3499 # @return TRUE in case of success, FALSE otherwise.
3500 # @ingroup l2_modif_smooth
3501 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3502 MaxNbOfIterations, MaxAspectRatio, Method):
3503 if IDsOfElements == []:
3504 IDsOfElements = self.GetElementsId()
3505 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3506 self.mesh.SetParameters(Parameters)
3507 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3508 MaxNbOfIterations, MaxAspectRatio, Method)
3510 ## Parametrically smoothes the elements which belong to the given object
3511 # @param theObject the object to smooth
3512 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3513 # Note that nodes built on edges and boundary nodes are always fixed.
3514 # @param MaxNbOfIterations the maximum number of iterations
3515 # @param MaxAspectRatio varies in range [1.0, inf]
3516 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3517 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3518 # @return TRUE in case of success, FALSE otherwise.
3519 # @ingroup l2_modif_smooth
3520 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3521 MaxNbOfIterations, MaxAspectRatio, Method):
3522 if ( isinstance( theObject, Mesh )):
3523 theObject = theObject.GetMesh()
3524 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3525 MaxNbOfIterations, MaxAspectRatio, Method)
3527 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3528 # them with quadratic with the same id.
3529 # @param theForce3d new node creation method:
3530 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3531 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3532 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3533 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3534 # @ingroup l2_modif_tofromqu
3535 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3536 if isinstance( theSubMesh, Mesh ):
3537 theSubMesh = theSubMesh.mesh
3539 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3542 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3544 self.editor.ConvertToQuadratic(theForce3d)
3545 error = self.editor.GetLastError()
3546 if error and error.comment:
3549 ## Converts the mesh from quadratic to ordinary,
3550 # deletes old quadratic elements, \n replacing
3551 # them with ordinary mesh elements with the same id.
3552 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3553 # @ingroup l2_modif_tofromqu
3554 def ConvertFromQuadratic(self, theSubMesh=None):
3556 self.editor.ConvertFromQuadraticObject(theSubMesh)
3558 return self.editor.ConvertFromQuadratic()
3560 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3561 # @return TRUE if operation has been completed successfully, FALSE otherwise
3562 # @ingroup l2_modif_edit
3563 def Make2DMeshFrom3D(self):
3564 return self.editor. Make2DMeshFrom3D()
3566 ## Creates missing boundary elements
3567 # @param elements - elements whose boundary is to be checked:
3568 # mesh, group, sub-mesh or list of elements
3569 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3570 # @param dimension - defines type of boundary elements to create, either of
3571 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3572 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3573 # @param groupName - a name of group to store created boundary elements in,
3574 # "" means not to create the group
3575 # @param meshName - a name of new mesh to store created boundary elements in,
3576 # "" means not to create the new mesh
3577 # @param toCopyElements - if true, the checked elements will be copied into
3578 # the new mesh else only boundary elements will be copied into the new mesh
3579 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3580 # boundary elements will be copied into the new mesh
3581 # @return tuple (mesh, group) where boundary elements were added to
3582 # @ingroup l2_modif_edit
3583 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3584 toCopyElements=False, toCopyExistingBondary=False):
3585 unRegister = genObjUnRegister()
3586 if isinstance( elements, Mesh ):
3587 elements = elements.GetMesh()
3588 if ( isinstance( elements, list )):
3589 elemType = SMESH.ALL
3590 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3591 elements = self.editor.MakeIDSource(elements, elemType)
3592 unRegister.set( elements )
3593 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3594 toCopyElements,toCopyExistingBondary)
3595 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3599 # @brief Creates missing boundary elements around either the whole mesh or
3600 # groups of elements
3601 # @param dimension - defines type of boundary elements to create, either of
3602 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3603 # @param groupName - a name of group to store all boundary elements in,
3604 # "" means not to create the group
3605 # @param meshName - a name of a new mesh, which is a copy of the initial
3606 # mesh + created boundary elements; "" means not to create the new mesh
3607 # @param toCopyAll - if true, the whole initial mesh will be copied into
3608 # the new mesh else only boundary elements will be copied into the new mesh
3609 # @param groups - groups of elements to make boundary around
3610 # @retval tuple( long, mesh, groups )
3611 # long - number of added boundary elements
3612 # mesh - the mesh where elements were added to
3613 # group - the group of boundary elements or None
3615 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3616 toCopyAll=False, groups=[]):
3617 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3619 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3620 return nb, mesh, group
3622 ## Renumber mesh nodes (Obsolete, does nothing)
3623 # @ingroup l2_modif_renumber
3624 def RenumberNodes(self):
3625 self.editor.RenumberNodes()
3627 ## Renumber mesh elements (Obsole, does nothing)
3628 # @ingroup l2_modif_renumber
3629 def RenumberElements(self):
3630 self.editor.RenumberElements()
3632 ## Private method converting \a arg into a list of SMESH_IdSource's
3633 def _getIdSourceList(self, arg, idType, unRegister):
3634 if arg and isinstance( arg, list ):
3635 if isinstance( arg[0], int ):
3636 arg = self.GetIDSource( arg, idType )
3637 unRegister.set( arg )
3638 elif isinstance( arg[0], Mesh ):
3639 arg[0] = arg[0].GetMesh()
3640 elif isinstance( arg, Mesh ):
3642 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3646 ## Generates new elements by rotation of the given elements and nodes around the axis
3647 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3648 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3649 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3650 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3651 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3652 # which defines angle in degrees
3653 # @param NbOfSteps the number of steps
3654 # @param Tolerance tolerance
3655 # @param MakeGroups forces the generation of new groups from existing ones
3656 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3657 # of all steps, else - size of each step
3658 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3659 # @ingroup l2_modif_extrurev
3660 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3661 MakeGroups=False, TotalAngle=False):
3662 unRegister = genObjUnRegister()
3663 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3664 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3665 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3667 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3668 Axis = self.smeshpyD.GetAxisStruct( Axis )
3669 if isinstance( Axis, list ):
3670 Axis = SMESH.AxisStruct( *Axis )
3672 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3673 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3674 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3675 self.mesh.SetParameters(Parameters)
3676 if TotalAngle and NbOfSteps:
3677 AngleInRadians /= NbOfSteps
3678 return self.editor.RotationSweepObjects( nodes, edges, faces,
3679 Axis, AngleInRadians,
3680 NbOfSteps, Tolerance, MakeGroups)
3682 ## Generates new elements by rotation of the elements around the axis
3683 # @param IDsOfElements the list of ids of elements to sweep
3684 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3685 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3686 # @param NbOfSteps the number of steps
3687 # @param Tolerance tolerance
3688 # @param MakeGroups forces the generation of new groups from existing ones
3689 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3690 # of all steps, else - size of each step
3691 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3692 # @ingroup l2_modif_extrurev
3693 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3694 MakeGroups=False, TotalAngle=False):
3695 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3696 AngleInRadians, NbOfSteps, Tolerance,
3697 MakeGroups, TotalAngle)
3699 ## Generates new elements by rotation of the elements of object around the axis
3700 # @param theObject object which elements should be sweeped.
3701 # It can be a mesh, a sub mesh or a group.
3702 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3703 # @param AngleInRadians the angle of Rotation
3704 # @param NbOfSteps number of steps
3705 # @param Tolerance tolerance
3706 # @param MakeGroups forces the generation of new groups from existing ones
3707 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3708 # of all steps, else - size of each step
3709 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3710 # @ingroup l2_modif_extrurev
3711 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3712 MakeGroups=False, TotalAngle=False):
3713 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3714 AngleInRadians, NbOfSteps, Tolerance,
3715 MakeGroups, TotalAngle )
3717 ## Generates new elements by rotation of the elements of object around the axis
3718 # @param theObject object which elements should be sweeped.
3719 # It can be a mesh, a sub mesh or a group.
3720 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3721 # @param AngleInRadians the angle of Rotation
3722 # @param NbOfSteps number of steps
3723 # @param Tolerance tolerance
3724 # @param MakeGroups forces the generation of new groups from existing ones
3725 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3726 # of all steps, else - size of each step
3727 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3728 # @ingroup l2_modif_extrurev
3729 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3730 MakeGroups=False, TotalAngle=False):
3731 return self.RotationSweepObjects([],theObject,[], Axis,
3732 AngleInRadians, NbOfSteps, Tolerance,
3733 MakeGroups, TotalAngle)
3735 ## Generates new elements by rotation of the elements of object around the axis
3736 # @param theObject object which elements should be sweeped.
3737 # It can be a mesh, a sub mesh or a group.
3738 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3739 # @param AngleInRadians the angle of Rotation
3740 # @param NbOfSteps number of steps
3741 # @param Tolerance tolerance
3742 # @param MakeGroups forces the generation of new groups from existing ones
3743 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3744 # of all steps, else - size of each step
3745 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3746 # @ingroup l2_modif_extrurev
3747 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3748 MakeGroups=False, TotalAngle=False):
3749 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3750 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3752 ## Generates new elements by extrusion of the given elements and nodes
3753 # @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3754 # @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3755 # @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3756 # @param StepVector vector or DirStruct or 3 vector components, defining
3757 # the direction and value of extrusion for one step (the total extrusion
3758 # length will be NbOfSteps * ||StepVector||)
3759 # @param NbOfSteps the number of steps
3760 # @param MakeGroups forces the generation of new groups from existing ones
3761 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3762 # @ingroup l2_modif_extrurev
3763 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3764 unRegister = genObjUnRegister()
3765 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3766 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3767 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3769 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3770 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3771 if isinstance( StepVector, list ):
3772 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3774 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3775 Parameters = StepVector.PS.parameters + var_separator + Parameters
3776 self.mesh.SetParameters(Parameters)
3778 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3779 StepVector, NbOfSteps, MakeGroups)
3782 ## Generates new elements by extrusion of the elements with given ids
3783 # @param IDsOfElements the list of elements ids for extrusion
3784 # @param StepVector vector or DirStruct or 3 vector components, defining
3785 # the direction and value of extrusion for one step (the total extrusion
3786 # length will be NbOfSteps * ||StepVector||)
3787 # @param NbOfSteps the number of steps
3788 # @param MakeGroups forces the generation of new groups from existing ones
3789 # @param IsNodes is True if elements with given ids are nodes
3790 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3791 # @ingroup l2_modif_extrurev
3792 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3794 if IsNodes: n = IDsOfElements
3795 else : e,f, = IDsOfElements,IDsOfElements
3796 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3798 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3799 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh
3800 # Only faces can be extruded so far. Sub-mesh should be a sub-mesh on geom faces.
3801 # @param StepSize length of one extrusion step (the total extrusion
3802 # length will be \a NbOfSteps * \a StepSize ).
3803 # @param NbOfSteps number of extrusion steps.
3804 # @param ByAverageNormal if True each node is translated by \a StepSize
3805 # along the average of the normal vectors to the faces sharing the node;
3806 # else each node is translated along the same average normal till
3807 # intersection with the plane got by translation of the face sharing
3808 # the node along its own normal by \a StepSize.
3809 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3810 # for every node of \a Elements.
3811 # @param MakeGroups forces generation of new groups from existing ones.
3812 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3813 # is not yet implemented. This parameter is used if \a Elements contains
3814 # both faces and edges, i.e. \a Elements is a Mesh.
3815 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3816 # empty list otherwise.
3817 # @ingroup l2_modif_extrurev
3818 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3819 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3820 unRegister = genObjUnRegister()
3821 if isinstance( Elements, Mesh ):
3822 Elements = [ Elements.GetMesh() ]
3823 if isinstance( Elements, list ):
3825 raise RuntimeError, "Elements empty!"
3826 if isinstance( Elements[0], int ):
3827 Elements = self.GetIDSource( Elements, SMESH.ALL )
3828 unRegister.set( Elements )
3829 if not isinstance( Elements, list ):
3830 Elements = [ Elements ]
3831 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3832 self.mesh.SetParameters(Parameters)
3833 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3834 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3836 ## Generates new elements by extrusion of the elements which belong to the object
3837 # @param theObject the object which elements should be processed.
3838 # It can be a mesh, a sub mesh or a group.
3839 # @param StepVector vector or DirStruct or 3 vector components, defining
3840 # the direction and value of extrusion for one step (the total extrusion
3841 # length will be NbOfSteps * ||StepVector||)
3842 # @param NbOfSteps the number of steps
3843 # @param MakeGroups forces the generation of new groups from existing ones
3844 # @param IsNodes is True if elements to extrude are nodes
3845 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3846 # @ingroup l2_modif_extrurev
3847 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3849 if IsNodes: n = theObject
3850 else : e,f, = theObject,theObject
3851 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3853 ## Generates new elements by extrusion of the elements which belong to the object
3854 # @param theObject object which elements should be processed.
3855 # It can be a mesh, a sub mesh or a group.
3856 # @param StepVector vector or DirStruct or 3 vector components, defining
3857 # the direction and value of extrusion for one step (the total extrusion
3858 # length will be NbOfSteps * ||StepVector||)
3859 # @param NbOfSteps the number of steps
3860 # @param MakeGroups to generate new groups from existing ones
3861 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3862 # @ingroup l2_modif_extrurev
3863 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3864 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3866 ## Generates new elements by extrusion of the elements which belong to the object
3867 # @param theObject object which elements should be processed.
3868 # It can be a mesh, a sub mesh or a group.
3869 # @param StepVector vector or DirStruct or 3 vector components, defining
3870 # the direction and value of extrusion for one step (the total extrusion
3871 # length will be NbOfSteps * ||StepVector||)
3872 # @param NbOfSteps the number of steps
3873 # @param MakeGroups forces the generation of new groups from existing ones
3874 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3875 # @ingroup l2_modif_extrurev
3876 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3877 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3879 ## Generates new elements by extrusion of the elements with given ids
3880 # @param IDsOfElements is ids of elements
3881 # @param StepVector vector or DirStruct or 3 vector components, defining
3882 # the direction and value of extrusion for one step (the total extrusion
3883 # length will be NbOfSteps * ||StepVector||)
3884 # @param NbOfSteps the number of steps
3885 # @param ExtrFlags sets flags for extrusion
3886 # @param SewTolerance uses for comparing locations of nodes if flag
3887 # EXTRUSION_FLAG_SEW is set
3888 # @param MakeGroups forces the generation of new groups from existing ones
3889 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3890 # @ingroup l2_modif_extrurev
3891 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3892 ExtrFlags, SewTolerance, MakeGroups=False):
3893 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3894 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3895 if isinstance( StepVector, list ):
3896 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3897 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3898 ExtrFlags, SewTolerance, MakeGroups)
3900 ## Generates new elements by extrusion of the given elements and nodes along the path.
3901 # The path of extrusion must be a meshed edge.
3902 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3903 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3904 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3905 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3906 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3907 # contains not only path segments, else it can be None
3908 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3909 # @param HasAngles allows the shape to be rotated around the path
3910 # to get the resulting mesh in a helical fashion
3911 # @param Angles list of angles
3912 # @param LinearVariation forces the computation of rotation angles as linear
3913 # variation of the given Angles along path steps
3914 # @param HasRefPoint allows using the reference point
3915 # @param RefPoint the point around which the shape is rotated (the mass center of the
3916 # shape by default). The User can specify any point as the Reference Point.
3917 # @param MakeGroups forces the generation of new groups from existing ones
3918 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3919 # @ingroup l2_modif_extrurev
3920 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3921 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3922 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3923 unRegister = genObjUnRegister()
3924 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3925 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3926 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3928 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3929 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3930 if isinstance( RefPoint, list ):
3931 RefPoint = SMESH.PointStruct( *RefPoint )
3932 if isinstance( PathMesh, Mesh ):
3933 PathMesh = PathMesh.GetMesh()
3934 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3935 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3936 self.mesh.SetParameters(Parameters)
3937 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3938 PathMesh, PathShape, NodeStart,
3939 HasAngles, Angles, LinearVariation,
3940 HasRefPoint, RefPoint, MakeGroups)
3942 ## Generates new elements by extrusion of the given elements
3943 # The path of extrusion must be a meshed edge.
3944 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3945 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3946 # @param NodeStart the start node from Path. Defines the direction of extrusion
3947 # @param HasAngles allows the shape to be rotated around the path
3948 # to get the resulting mesh in a helical fashion
3949 # @param Angles list of angles in radians
3950 # @param LinearVariation forces the computation of rotation angles as linear
3951 # variation of the given Angles along path steps
3952 # @param HasRefPoint allows using the reference point
3953 # @param RefPoint the point around which the elements are rotated (the mass
3954 # center of the elements by default).
3955 # The User can specify any point as the Reference Point.
3956 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3957 # @param MakeGroups forces the generation of new groups from existing ones
3958 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3959 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3960 # only SMESH::Extrusion_Error otherwise
3961 # @ingroup l2_modif_extrurev
3962 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3963 HasAngles, Angles, LinearVariation,
3964 HasRefPoint, RefPoint, MakeGroups, ElemType):
3966 if ElemType == SMESH.NODE: n = Base
3967 if ElemType == SMESH.EDGE: e = Base
3968 if ElemType == SMESH.FACE: f = Base
3969 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
3970 HasAngles, Angles, LinearVariation,
3971 HasRefPoint, RefPoint, MakeGroups)
3972 if MakeGroups: return gr,er
3975 ## Generates new elements by extrusion of the given elements
3976 # The path of extrusion must be a meshed edge.
3977 # @param IDsOfElements ids of elements
3978 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3979 # @param PathShape shape(edge) defines the sub-mesh for the path
3980 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3981 # @param HasAngles allows the shape to be rotated around the path
3982 # to get the resulting mesh in a helical fashion
3983 # @param Angles list of angles in radians
3984 # @param HasRefPoint allows using the reference point
3985 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3986 # The User can specify any point as the Reference Point.
3987 # @param MakeGroups forces the generation of new groups from existing ones
3988 # @param LinearVariation forces the computation of rotation angles as linear
3989 # variation of the given Angles along path steps
3990 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3991 # only SMESH::Extrusion_Error otherwise
3992 # @ingroup l2_modif_extrurev
3993 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3994 HasAngles, Angles, HasRefPoint, RefPoint,
3995 MakeGroups=False, LinearVariation=False):
3996 n,e,f = [],IDsOfElements,IDsOfElements
3997 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
3998 NodeStart, HasAngles, Angles,
4000 HasRefPoint, RefPoint, MakeGroups)
4001 if MakeGroups: return gr,er
4004 ## Generates new elements by extrusion of the elements which belong to the object
4005 # The path of extrusion must be a meshed edge.
4006 # @param theObject the object which elements should be processed.
4007 # It can be a mesh, a sub-mesh or a group.
4008 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4009 # @param PathShape shape(edge) defines the sub-mesh for the path
4010 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4011 # @param HasAngles allows the shape to be rotated around the path
4012 # to get the resulting mesh in a helical fashion
4013 # @param Angles list of angles
4014 # @param HasRefPoint allows using the reference point
4015 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4016 # The User can specify any point as the Reference Point.
4017 # @param MakeGroups forces the generation of new groups from existing ones
4018 # @param LinearVariation forces the computation of rotation angles as linear
4019 # variation of the given Angles along path steps
4020 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4021 # only SMESH::Extrusion_Error otherwise
4022 # @ingroup l2_modif_extrurev
4023 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4024 HasAngles, Angles, HasRefPoint, RefPoint,
4025 MakeGroups=False, LinearVariation=False):
4026 n,e,f = [],theObject,theObject
4027 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4028 HasAngles, Angles, LinearVariation,
4029 HasRefPoint, RefPoint, MakeGroups)
4030 if MakeGroups: return gr,er
4033 ## Generates new elements by extrusion of the elements which belong to the object
4034 # The path of extrusion must be a meshed edge.
4035 # @param theObject the object which elements should be processed.
4036 # It can be a mesh, a sub mesh or a group.
4037 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4038 # @param PathShape shape(edge) defines the sub-mesh for the path
4039 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4040 # @param HasAngles allows the shape to be rotated around the path
4041 # to get the resulting mesh in a helical fashion
4042 # @param Angles list of angles
4043 # @param HasRefPoint allows using the reference point
4044 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4045 # The User can specify any point as the Reference Point.
4046 # @param MakeGroups forces the generation of new groups from existing ones
4047 # @param LinearVariation forces the computation of rotation angles as linear
4048 # variation of the given Angles along path steps
4049 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4050 # only SMESH::Extrusion_Error otherwise
4051 # @ingroup l2_modif_extrurev
4052 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4053 HasAngles, Angles, HasRefPoint, RefPoint,
4054 MakeGroups=False, LinearVariation=False):
4055 n,e,f = [],theObject,[]
4056 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4057 HasAngles, Angles, LinearVariation,
4058 HasRefPoint, RefPoint, MakeGroups)
4059 if MakeGroups: return gr,er
4062 ## Generates new elements by extrusion of the elements which belong to the object
4063 # The path of extrusion must be a meshed edge.
4064 # @param theObject the object which elements should be processed.
4065 # It can be a mesh, a sub mesh or a group.
4066 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4067 # @param PathShape shape(edge) defines the sub-mesh for the path
4068 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4069 # @param HasAngles allows the shape to be rotated around the path
4070 # to get the resulting mesh in a helical fashion
4071 # @param Angles list of angles
4072 # @param HasRefPoint allows using the reference point
4073 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4074 # The User can specify any point as the Reference Point.
4075 # @param MakeGroups forces the generation of new groups from existing ones
4076 # @param LinearVariation forces the computation of rotation angles as linear
4077 # variation of the given Angles along path steps
4078 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4079 # only SMESH::Extrusion_Error otherwise
4080 # @ingroup l2_modif_extrurev
4081 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4082 HasAngles, Angles, HasRefPoint, RefPoint,
4083 MakeGroups=False, LinearVariation=False):
4084 n,e,f = [],[],theObject
4085 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4086 HasAngles, Angles, LinearVariation,
4087 HasRefPoint, RefPoint, MakeGroups)
4088 if MakeGroups: return gr,er
4091 ## Creates a symmetrical copy of mesh elements
4092 # @param IDsOfElements list of elements ids
4093 # @param Mirror is AxisStruct or geom object(point, line, plane)
4094 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4095 # If the Mirror is a geom object this parameter is unnecessary
4096 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4097 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4098 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4099 # @ingroup l2_modif_trsf
4100 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4101 if IDsOfElements == []:
4102 IDsOfElements = self.GetElementsId()
4103 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4104 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4105 theMirrorType = Mirror._mirrorType
4107 self.mesh.SetParameters(Mirror.parameters)
4108 if Copy and MakeGroups:
4109 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4110 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4113 ## Creates a new mesh by a symmetrical copy of mesh elements
4114 # @param IDsOfElements the list of elements ids
4115 # @param Mirror is AxisStruct or geom object (point, line, plane)
4116 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4117 # If the Mirror is a geom object this parameter is unnecessary
4118 # @param MakeGroups to generate new groups from existing ones
4119 # @param NewMeshName a name of the new mesh to create
4120 # @return instance of Mesh class
4121 # @ingroup l2_modif_trsf
4122 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4123 if IDsOfElements == []:
4124 IDsOfElements = self.GetElementsId()
4125 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4126 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4127 theMirrorType = Mirror._mirrorType
4129 self.mesh.SetParameters(Mirror.parameters)
4130 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4131 MakeGroups, NewMeshName)
4132 return Mesh(self.smeshpyD,self.geompyD,mesh)
4134 ## Creates a symmetrical copy of the object
4135 # @param theObject mesh, submesh or group
4136 # @param Mirror AxisStruct or geom object (point, line, plane)
4137 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4138 # If the Mirror is a geom object this parameter is unnecessary
4139 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4140 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4141 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4142 # @ingroup l2_modif_trsf
4143 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4144 if ( isinstance( theObject, Mesh )):
4145 theObject = theObject.GetMesh()
4146 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4147 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4148 theMirrorType = Mirror._mirrorType
4150 self.mesh.SetParameters(Mirror.parameters)
4151 if Copy and MakeGroups:
4152 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4153 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4156 ## Creates a new mesh by a symmetrical copy of the object
4157 # @param theObject mesh, submesh or group
4158 # @param Mirror AxisStruct or geom object (point, line, plane)
4159 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4160 # If the Mirror is a geom object this parameter is unnecessary
4161 # @param MakeGroups forces the generation of new groups from existing ones
4162 # @param NewMeshName the name of the new mesh to create
4163 # @return instance of Mesh class
4164 # @ingroup l2_modif_trsf
4165 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4166 if ( isinstance( theObject, Mesh )):
4167 theObject = theObject.GetMesh()
4168 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4169 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4170 theMirrorType = Mirror._mirrorType
4172 self.mesh.SetParameters(Mirror.parameters)
4173 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4174 MakeGroups, NewMeshName)
4175 return Mesh( self.smeshpyD,self.geompyD,mesh )
4177 ## Translates the elements
4178 # @param IDsOfElements list of elements ids
4179 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4180 # @param Copy allows copying the translated elements
4181 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4182 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4183 # @ingroup l2_modif_trsf
4184 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4185 if IDsOfElements == []:
4186 IDsOfElements = self.GetElementsId()
4187 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4188 Vector = self.smeshpyD.GetDirStruct(Vector)
4189 if isinstance( Vector, list ):
4190 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4191 self.mesh.SetParameters(Vector.PS.parameters)
4192 if Copy and MakeGroups:
4193 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4194 self.editor.Translate(IDsOfElements, Vector, Copy)
4197 ## Creates a new mesh of translated elements
4198 # @param IDsOfElements list of elements ids
4199 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4200 # @param MakeGroups forces the generation of new groups from existing ones
4201 # @param NewMeshName the name of the newly created mesh
4202 # @return instance of Mesh class
4203 # @ingroup l2_modif_trsf
4204 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4205 if IDsOfElements == []:
4206 IDsOfElements = self.GetElementsId()
4207 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4208 Vector = self.smeshpyD.GetDirStruct(Vector)
4209 if isinstance( Vector, list ):
4210 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4211 self.mesh.SetParameters(Vector.PS.parameters)
4212 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4213 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4215 ## Translates the object
4216 # @param theObject the object to translate (mesh, submesh, or group)
4217 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4218 # @param Copy allows copying the translated elements
4219 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4220 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4221 # @ingroup l2_modif_trsf
4222 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4223 if ( isinstance( theObject, Mesh )):
4224 theObject = theObject.GetMesh()
4225 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4226 Vector = self.smeshpyD.GetDirStruct(Vector)
4227 if isinstance( Vector, list ):
4228 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4229 self.mesh.SetParameters(Vector.PS.parameters)
4230 if Copy and MakeGroups:
4231 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4232 self.editor.TranslateObject(theObject, Vector, Copy)
4235 ## Creates a new mesh from the translated object
4236 # @param theObject the object to translate (mesh, submesh, or group)
4237 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4238 # @param MakeGroups forces the generation of new groups from existing ones
4239 # @param NewMeshName the name of the newly created mesh
4240 # @return instance of Mesh class
4241 # @ingroup l2_modif_trsf
4242 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4243 if isinstance( theObject, Mesh ):
4244 theObject = theObject.GetMesh()
4245 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4246 Vector = self.smeshpyD.GetDirStruct(Vector)
4247 if isinstance( Vector, list ):
4248 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4249 self.mesh.SetParameters(Vector.PS.parameters)
4250 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4251 return Mesh( self.smeshpyD, self.geompyD, mesh )
4255 ## Scales the object
4256 # @param theObject - the object to translate (mesh, submesh, or group)
4257 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4258 # @param theScaleFact - list of 1-3 scale factors for axises
4259 # @param Copy - allows copying the translated elements
4260 # @param MakeGroups - forces the generation of new groups from existing
4262 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4263 # empty list otherwise
4264 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4265 unRegister = genObjUnRegister()
4266 if ( isinstance( theObject, Mesh )):
4267 theObject = theObject.GetMesh()
4268 if ( isinstance( theObject, list )):
4269 theObject = self.GetIDSource(theObject, SMESH.ALL)
4270 unRegister.set( theObject )
4271 if ( isinstance( thePoint, list )):
4272 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4273 if ( isinstance( theScaleFact, float )):
4274 theScaleFact = [theScaleFact]
4275 if ( isinstance( theScaleFact, int )):
4276 theScaleFact = [ float(theScaleFact)]
4278 self.mesh.SetParameters(thePoint.parameters)
4280 if Copy and MakeGroups:
4281 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4282 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4285 ## Creates a new mesh from the translated object
4286 # @param theObject - the object to translate (mesh, submesh, or group)
4287 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4288 # @param theScaleFact - list of 1-3 scale factors for axises
4289 # @param MakeGroups - forces the generation of new groups from existing ones
4290 # @param NewMeshName - the name of the newly created mesh
4291 # @return instance of Mesh class
4292 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4293 unRegister = genObjUnRegister()
4294 if (isinstance(theObject, Mesh)):
4295 theObject = theObject.GetMesh()
4296 if ( isinstance( theObject, list )):
4297 theObject = self.GetIDSource(theObject,SMESH.ALL)
4298 unRegister.set( theObject )
4299 if ( isinstance( thePoint, list )):
4300 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4301 if ( isinstance( theScaleFact, float )):
4302 theScaleFact = [theScaleFact]
4303 if ( isinstance( theScaleFact, int )):
4304 theScaleFact = [ float(theScaleFact)]
4306 self.mesh.SetParameters(thePoint.parameters)
4307 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4308 MakeGroups, NewMeshName)
4309 return Mesh( self.smeshpyD, self.geompyD, mesh )
4313 ## Rotates the elements
4314 # @param IDsOfElements list of elements ids
4315 # @param Axis the axis of rotation (AxisStruct or geom line)
4316 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4317 # @param Copy allows copying the rotated elements
4318 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4319 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4320 # @ingroup l2_modif_trsf
4321 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4322 if IDsOfElements == []:
4323 IDsOfElements = self.GetElementsId()
4324 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4325 Axis = self.smeshpyD.GetAxisStruct(Axis)
4326 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4327 Parameters = Axis.parameters + var_separator + Parameters
4328 self.mesh.SetParameters(Parameters)
4329 if Copy and MakeGroups:
4330 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4331 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4334 ## Creates a new mesh of rotated elements
4335 # @param IDsOfElements list of element ids
4336 # @param Axis the axis of rotation (AxisStruct or geom line)
4337 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4338 # @param MakeGroups forces the generation of new groups from existing ones
4339 # @param NewMeshName the name of the newly created mesh
4340 # @return instance of Mesh class
4341 # @ingroup l2_modif_trsf
4342 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4343 if IDsOfElements == []:
4344 IDsOfElements = self.GetElementsId()
4345 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4346 Axis = self.smeshpyD.GetAxisStruct(Axis)
4347 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4348 Parameters = Axis.parameters + var_separator + Parameters
4349 self.mesh.SetParameters(Parameters)
4350 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4351 MakeGroups, NewMeshName)
4352 return Mesh( self.smeshpyD, self.geompyD, mesh )
4354 ## Rotates the object
4355 # @param theObject the object to rotate( mesh, submesh, or group)
4356 # @param Axis the axis of rotation (AxisStruct or geom line)
4357 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4358 # @param Copy allows copying the rotated elements
4359 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4360 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4361 # @ingroup l2_modif_trsf
4362 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4363 if (isinstance(theObject, Mesh)):
4364 theObject = theObject.GetMesh()
4365 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4366 Axis = self.smeshpyD.GetAxisStruct(Axis)
4367 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4368 Parameters = Axis.parameters + ":" + Parameters
4369 self.mesh.SetParameters(Parameters)
4370 if Copy and MakeGroups:
4371 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4372 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4375 ## Creates a new mesh from the rotated object
4376 # @param theObject the object to rotate (mesh, submesh, or group)
4377 # @param Axis the axis of rotation (AxisStruct or geom line)
4378 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4379 # @param MakeGroups forces the generation of new groups from existing ones
4380 # @param NewMeshName the name of the newly created mesh
4381 # @return instance of Mesh class
4382 # @ingroup l2_modif_trsf
4383 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4384 if (isinstance( theObject, Mesh )):
4385 theObject = theObject.GetMesh()
4386 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4387 Axis = self.smeshpyD.GetAxisStruct(Axis)
4388 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4389 Parameters = Axis.parameters + ":" + Parameters
4390 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4391 MakeGroups, NewMeshName)
4392 self.mesh.SetParameters(Parameters)
4393 return Mesh( self.smeshpyD, self.geompyD, mesh )
4395 ## Finds groups of adjacent nodes within Tolerance.
4396 # @param Tolerance the value of tolerance
4397 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4398 # corner and medium nodes in separate groups thus preventing
4399 # their further merge.
4400 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4401 # @ingroup l2_modif_trsf
4402 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4403 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4405 ## Finds groups of ajacent nodes within Tolerance.
4406 # @param Tolerance the value of tolerance
4407 # @param SubMeshOrGroup SubMesh or Group
4408 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4409 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4410 # corner and medium nodes in separate groups thus preventing
4411 # their further merge.
4412 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4413 # @ingroup l2_modif_trsf
4414 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4415 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4416 unRegister = genObjUnRegister()
4417 if (isinstance( SubMeshOrGroup, Mesh )):
4418 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4419 if not isinstance( exceptNodes, list ):
4420 exceptNodes = [ exceptNodes ]
4421 if exceptNodes and isinstance( exceptNodes[0], int ):
4422 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4423 unRegister.set( exceptNodes )
4424 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4425 exceptNodes, SeparateCornerAndMediumNodes)
4428 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4429 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4430 # by nodes 1 and 25 correspondingly in all elements and groups
4431 # @ingroup l2_modif_trsf
4432 def MergeNodes (self, GroupsOfNodes):
4433 self.editor.MergeNodes(GroupsOfNodes)
4435 ## Finds the elements built on the same nodes.
4436 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4437 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4438 # @ingroup l2_modif_trsf
4439 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4440 if not MeshOrSubMeshOrGroup:
4441 MeshOrSubMeshOrGroup=self.mesh
4442 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4443 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4444 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4446 ## Merges elements in each given group.
4447 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4448 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4449 # replaced by elements 1 and 25 in all groups)
4450 # @ingroup l2_modif_trsf
4451 def MergeElements(self, GroupsOfElementsID):
4452 self.editor.MergeElements(GroupsOfElementsID)
4454 ## Leaves one element and removes all other elements built on the same nodes.
4455 # @ingroup l2_modif_trsf
4456 def MergeEqualElements(self):
4457 self.editor.MergeEqualElements()
4459 ## Sews free borders
4460 # @return SMESH::Sew_Error
4461 # @ingroup l2_modif_trsf
4462 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4463 FirstNodeID2, SecondNodeID2, LastNodeID2,
4464 CreatePolygons, CreatePolyedrs):
4465 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4466 FirstNodeID2, SecondNodeID2, LastNodeID2,
4467 CreatePolygons, CreatePolyedrs)
4469 ## Sews conform free borders
4470 # @return SMESH::Sew_Error
4471 # @ingroup l2_modif_trsf
4472 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4473 FirstNodeID2, SecondNodeID2):
4474 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4475 FirstNodeID2, SecondNodeID2)
4477 ## Sews border to side
4478 # @return SMESH::Sew_Error
4479 # @ingroup l2_modif_trsf
4480 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4481 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4482 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4483 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4485 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4486 # merged with the nodes of elements of Side2.
4487 # The number of elements in theSide1 and in theSide2 must be
4488 # equal and they should have similar nodal connectivity.
4489 # The nodes to merge should belong to side borders and
4490 # the first node should be linked to the second.
4491 # @return SMESH::Sew_Error
4492 # @ingroup l2_modif_trsf
4493 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4494 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4495 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4496 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4497 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4498 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4500 ## Sets new nodes for the given element.
4501 # @param ide the element id
4502 # @param newIDs nodes ids
4503 # @return If the number of nodes does not correspond to the type of element - returns false
4504 # @ingroup l2_modif_edit
4505 def ChangeElemNodes(self, ide, newIDs):
4506 return self.editor.ChangeElemNodes(ide, newIDs)
4508 ## If during the last operation of MeshEditor some nodes were
4509 # created, this method returns the list of their IDs, \n
4510 # if new nodes were not created - returns empty list
4511 # @return the list of integer values (can be empty)
4512 # @ingroup l1_auxiliary
4513 def GetLastCreatedNodes(self):
4514 return self.editor.GetLastCreatedNodes()
4516 ## If during the last operation of MeshEditor some elements were
4517 # created this method returns the list of their IDs, \n
4518 # if new elements were not created - returns empty list
4519 # @return the list of integer values (can be empty)
4520 # @ingroup l1_auxiliary
4521 def GetLastCreatedElems(self):
4522 return self.editor.GetLastCreatedElems()
4524 ## Clears sequences of nodes and elements created by mesh edition oparations
4525 # @ingroup l1_auxiliary
4526 def ClearLastCreated(self):
4527 self.editor.ClearLastCreated()
4529 ## Creates Duplicates given elements, i.e. creates new elements based on the
4530 # same nodes as the given ones.
4531 # @param theElements - container of elements to duplicate. It can be a Mesh,
4532 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4533 # a Mesh, elements of highest dimension are duplicated
4534 # @param theGroupName - a name of group to contain the generated elements.
4535 # If a group with such a name already exists, the new elements
4536 # are added to the existng group, else a new group is created.
4537 # If \a theGroupName is empty, new elements are not added
4539 # @return a group where the new elements are added. None if theGroupName == "".
4540 # @ingroup l2_modif_edit
4541 def DoubleElements(self, theElements, theGroupName=""):
4542 unRegister = genObjUnRegister()
4543 if isinstance( theElements, Mesh ):
4544 theElements = theElements.mesh
4545 elif isinstance( theElements, list ):
4546 theElements = self.GetIDSource( theElements, SMESH.ALL )
4547 unRegister.set( theElements )
4548 return self.editor.DoubleElements(theElements, theGroupName)
4550 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4551 # @param theNodes identifiers of nodes to be doubled
4552 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4553 # nodes. If list of element identifiers is empty then nodes are doubled but
4554 # they not assigned to elements
4555 # @return TRUE if operation has been completed successfully, FALSE otherwise
4556 # @ingroup l2_modif_edit
4557 def DoubleNodes(self, theNodes, theModifiedElems):
4558 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4560 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4561 # This method provided for convenience works as DoubleNodes() described above.
4562 # @param theNodeId identifiers of node to be doubled
4563 # @param theModifiedElems identifiers of elements to be updated
4564 # @return TRUE if operation has been completed successfully, FALSE otherwise
4565 # @ingroup l2_modif_edit
4566 def DoubleNode(self, theNodeId, theModifiedElems):
4567 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4569 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4570 # This method provided for convenience works as DoubleNodes() described above.
4571 # @param theNodes group of nodes to be doubled
4572 # @param theModifiedElems group of elements to be updated.
4573 # @param theMakeGroup forces the generation of a group containing new nodes.
4574 # @return TRUE or a created group if operation has been completed successfully,
4575 # FALSE or None otherwise
4576 # @ingroup l2_modif_edit
4577 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4579 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4580 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4582 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4583 # This method provided for convenience works as DoubleNodes() described above.
4584 # @param theNodes list of groups of nodes to be doubled
4585 # @param theModifiedElems list of groups of elements to be updated.
4586 # @param theMakeGroup forces the generation of a group containing new nodes.
4587 # @return TRUE if operation has been completed successfully, FALSE otherwise
4588 # @ingroup l2_modif_edit
4589 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4591 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4592 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4594 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4595 # @param theElems - the list of elements (edges or faces) to be replicated
4596 # The nodes for duplication could be found from these elements
4597 # @param theNodesNot - list of nodes to NOT replicate
4598 # @param theAffectedElems - the list of elements (cells and edges) to which the
4599 # replicated nodes should be associated to.
4600 # @return TRUE if operation has been completed successfully, FALSE otherwise
4601 # @ingroup l2_modif_edit
4602 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4603 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4605 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4606 # @param theElems - the list of elements (edges or faces) to be replicated
4607 # The nodes for duplication could be found from these elements
4608 # @param theNodesNot - list of nodes to NOT replicate
4609 # @param theShape - shape to detect affected elements (element which geometric center
4610 # located on or inside shape).
4611 # The replicated nodes should be associated to affected elements.
4612 # @return TRUE if operation has been completed successfully, FALSE otherwise
4613 # @ingroup l2_modif_edit
4614 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4615 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4617 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4618 # This method provided for convenience works as DoubleNodes() described above.
4619 # @param theElems - group of of elements (edges or faces) to be replicated
4620 # @param theNodesNot - group of nodes not to replicated
4621 # @param theAffectedElems - group of elements to which the replicated nodes
4622 # should be associated to.
4623 # @param theMakeGroup forces the generation of a group containing new elements.
4624 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4625 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4626 # FALSE or None otherwise
4627 # @ingroup l2_modif_edit
4628 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4629 theMakeGroup=False, theMakeNodeGroup=False):
4630 if theMakeGroup or theMakeNodeGroup:
4631 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4633 theMakeGroup, theMakeNodeGroup)
4634 if theMakeGroup and theMakeNodeGroup:
4637 return twoGroups[ int(theMakeNodeGroup) ]
4638 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4640 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4641 # This method provided for convenience works as DoubleNodes() described above.
4642 # @param theElems - group of of elements (edges or faces) to be replicated
4643 # @param theNodesNot - group of nodes not to replicated
4644 # @param theShape - shape to detect affected elements (element which geometric center
4645 # located on or inside shape).
4646 # The replicated nodes should be associated to affected elements.
4647 # @ingroup l2_modif_edit
4648 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4649 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4651 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4652 # This method provided for convenience works as DoubleNodes() described above.
4653 # @param theElems - list of groups of elements (edges or faces) to be replicated
4654 # @param theNodesNot - list of groups of nodes not to replicated
4655 # @param theAffectedElems - group of elements to which the replicated nodes
4656 # should be associated to.
4657 # @param theMakeGroup forces the generation of a group containing new elements.
4658 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4659 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4660 # FALSE or None otherwise
4661 # @ingroup l2_modif_edit
4662 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4663 theMakeGroup=False, theMakeNodeGroup=False):
4664 if theMakeGroup or theMakeNodeGroup:
4665 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4667 theMakeGroup, theMakeNodeGroup)
4668 if theMakeGroup and theMakeNodeGroup:
4671 return twoGroups[ int(theMakeNodeGroup) ]
4672 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4674 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4675 # This method provided for convenience works as DoubleNodes() described above.
4676 # @param theElems - list of groups of elements (edges or faces) to be replicated
4677 # @param theNodesNot - list of groups of nodes not to replicated
4678 # @param theShape - shape to detect affected elements (element which geometric center
4679 # located on or inside shape).
4680 # The replicated nodes should be associated to affected elements.
4681 # @return TRUE if operation has been completed successfully, FALSE otherwise
4682 # @ingroup l2_modif_edit
4683 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4684 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4686 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4687 # This method is the first step of DoubleNodeElemGroupsInRegion.
4688 # @param theElems - list of groups of elements (edges or faces) to be replicated
4689 # @param theNodesNot - list of groups of nodes not to replicated
4690 # @param theShape - shape to detect affected elements (element which geometric center
4691 # located on or inside shape).
4692 # The replicated nodes should be associated to affected elements.
4693 # @return groups of affected elements
4694 # @ingroup l2_modif_edit
4695 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4696 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4698 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4699 # The list of groups must describe a partition of the mesh volumes.
4700 # The nodes of the internal faces at the boundaries of the groups are doubled.
4701 # In option, the internal faces are replaced by flat elements.
4702 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4703 # @param theDomains - list of groups of volumes
4704 # @param createJointElems - if TRUE, create the elements
4705 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4706 # the boundary between \a theDomains and the rest mesh
4707 # @return TRUE if operation has been completed successfully, FALSE otherwise
4708 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4709 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4711 ## Double nodes on some external faces and create flat elements.
4712 # Flat elements are mainly used by some types of mechanic calculations.
4714 # Each group of the list must be constituted of faces.
4715 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4716 # @param theGroupsOfFaces - list of groups of faces
4717 # @return TRUE if operation has been completed successfully, FALSE otherwise
4718 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4719 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4721 ## identify all the elements around a geom shape, get the faces delimiting the hole
4723 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4724 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4726 def _getFunctor(self, funcType ):
4727 fn = self.functors[ funcType._v ]
4729 fn = self.smeshpyD.GetFunctor(funcType)
4730 fn.SetMesh(self.mesh)
4731 self.functors[ funcType._v ] = fn
4734 ## Returns value of a functor for a given element
4735 # @param funcType an item of SMESH.FunctorType enum
4736 # @param elemId element or node ID
4737 # @param isElem @a elemId is ID of element or node
4738 # @return the functor value or zero in case of invalid arguments
4739 def FunctorValue(self, funcType, elemId, isElem=True):
4740 fn = self._getFunctor( funcType )
4741 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4742 val = fn.GetValue(elemId)
4747 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4748 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4749 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4750 # @ingroup l1_measurements
4751 def GetLength(self, elemId=None):
4754 length = self.smeshpyD.GetLength(self)
4756 length = self.FunctorValue(SMESH.FT_Length, elemId)
4759 ## Get area of 2D element or sum of areas of all 2D mesh elements
4760 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4761 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4762 # @ingroup l1_measurements
4763 def GetArea(self, elemId=None):
4766 area = self.smeshpyD.GetArea(self)
4768 area = self.FunctorValue(SMESH.FT_Area, elemId)
4771 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4772 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4773 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4774 # @ingroup l1_measurements
4775 def GetVolume(self, elemId=None):
4778 volume = self.smeshpyD.GetVolume(self)
4780 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4783 ## Get maximum element length.
4784 # @param elemId mesh element ID
4785 # @return element's maximum length value
4786 # @ingroup l1_measurements
4787 def GetMaxElementLength(self, elemId):
4788 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4789 ftype = SMESH.FT_MaxElementLength3D
4791 ftype = SMESH.FT_MaxElementLength2D
4792 return self.FunctorValue(ftype, elemId)
4794 ## Get aspect ratio of 2D or 3D element.
4795 # @param elemId mesh element ID
4796 # @return element's aspect ratio value
4797 # @ingroup l1_measurements
4798 def GetAspectRatio(self, elemId):
4799 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4800 ftype = SMESH.FT_AspectRatio3D
4802 ftype = SMESH.FT_AspectRatio
4803 return self.FunctorValue(ftype, elemId)
4805 ## Get warping angle of 2D element.
4806 # @param elemId mesh element ID
4807 # @return element's warping angle value
4808 # @ingroup l1_measurements
4809 def GetWarping(self, elemId):
4810 return self.FunctorValue(SMESH.FT_Warping, elemId)
4812 ## Get minimum angle of 2D element.
4813 # @param elemId mesh element ID
4814 # @return element's minimum angle value
4815 # @ingroup l1_measurements
4816 def GetMinimumAngle(self, elemId):
4817 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4819 ## Get taper of 2D element.
4820 # @param elemId mesh element ID
4821 # @return element's taper value
4822 # @ingroup l1_measurements
4823 def GetTaper(self, elemId):
4824 return self.FunctorValue(SMESH.FT_Taper, elemId)
4826 ## Get skew of 2D element.
4827 # @param elemId mesh element ID
4828 # @return element's skew value
4829 # @ingroup l1_measurements
4830 def GetSkew(self, elemId):
4831 return self.FunctorValue(SMESH.FT_Skew, elemId)
4833 ## Return minimal and maximal value of a given functor.
4834 # @param funType a functor type, an item of SMESH.FunctorType enum
4835 # (one of SMESH.FunctorType._items)
4836 # @param meshPart a part of mesh (group, sub-mesh) to treat
4837 # @return tuple (min,max)
4838 # @ingroup l1_measurements
4839 def GetMinMax(self, funType, meshPart=None):
4840 unRegister = genObjUnRegister()
4841 if isinstance( meshPart, list ):
4842 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4843 unRegister.set( meshPart )
4844 if isinstance( meshPart, Mesh ):
4845 meshPart = meshPart.mesh
4846 fun = self._getFunctor( funType )
4849 hist = fun.GetLocalHistogram( 1, False, meshPart )
4851 hist = fun.GetHistogram( 1, False )
4853 return hist[0].min, hist[0].max
4856 pass # end of Mesh class
4858 ## class used to add to SMESH_MeshEditor methods removed from its CORBA API
4860 class meshEditor(SMESH._objref_SMESH_MeshEditor):
4862 SMESH._objref_SMESH_MeshEditor.__init__(self)
4864 def __getattr__(self, name ): # method called if an attribute not found
4865 if not self.mesh: # look for name() method in Mesh class
4866 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
4867 if hasattr( self.mesh, name ):
4868 return getattr( self.mesh, name )
4869 if name == "ExtrusionAlongPathObjX":
4870 return getattr( self.mesh, "ExtrusionAlongPathX" )
4871 print name, "meshEditor: attribute '%s' NOT FOUND" % name
4873 def __deepcopy__(self, memo=None):
4874 new = self.__class__()
4877 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
4879 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4881 class Pattern(SMESH._objref_SMESH_Pattern):
4883 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4884 decrFun = lambda i: i-1
4885 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4886 theMesh.SetParameters(Parameters)
4887 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4889 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4890 decrFun = lambda i: i-1
4891 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4892 theMesh.SetParameters(Parameters)
4893 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4895 # Registering the new proxy for Pattern
4896 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4898 ## Private class used to bind methods creating algorithms to the class Mesh
4903 self.defaultAlgoType = ""
4904 self.algoTypeToClass = {}
4906 # Stores a python class of algorithm
4907 def add(self, algoClass):
4908 if type( algoClass ).__name__ == 'classobj' and \
4909 hasattr( algoClass, "algoType"):
4910 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4911 if not self.defaultAlgoType and \
4912 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4913 self.defaultAlgoType = algoClass.algoType
4914 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4916 # creates a copy of self and assign mesh to the copy
4917 def copy(self, mesh):
4918 other = algoCreator()
4919 other.defaultAlgoType = self.defaultAlgoType
4920 other.algoTypeToClass = self.algoTypeToClass
4924 # creates an instance of algorithm
4925 def __call__(self,algo="",geom=0,*args):
4926 algoType = self.defaultAlgoType
4927 for arg in args + (algo,geom):
4928 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4930 if isinstance( arg, str ) and arg:
4932 if not algoType and self.algoTypeToClass:
4933 algoType = self.algoTypeToClass.keys()[0]
4934 if self.algoTypeToClass.has_key( algoType ):
4935 #print "Create algo",algoType
4936 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4937 raise RuntimeError, "No class found for algo type %s" % algoType
4940 # Private class used to substitute and store variable parameters of hypotheses.
4942 class hypMethodWrapper:
4943 def __init__(self, hyp, method):
4945 self.method = method
4946 #print "REBIND:", method.__name__
4949 # call a method of hypothesis with calling SetVarParameter() before
4950 def __call__(self,*args):
4952 return self.method( self.hyp, *args ) # hypothesis method with no args
4954 #print "MethWrapper.__call__",self.method.__name__, args
4956 parsed = ParseParameters(*args) # replace variables with their values
4957 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4958 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4959 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4960 # maybe there is a replaced string arg which is not variable
4961 result = self.method( self.hyp, *args )
4962 except ValueError, detail: # raised by ParseParameters()
4964 result = self.method( self.hyp, *args )
4965 except omniORB.CORBA.BAD_PARAM:
4966 raise ValueError, detail # wrong variable name
4971 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4972 class genObjUnRegister:
4974 def __init__(self, genObj=None):
4975 self.genObjList = []
4979 def set(self, genObj):
4980 "Store one or a list of of SALOME.GenericObj'es"
4981 if isinstance( genObj, list ):
4982 self.genObjList.extend( genObj )
4984 self.genObjList.append( genObj )
4988 for genObj in self.genObjList:
4989 if genObj and hasattr( genObj, "UnRegister" ):
4992 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4994 #print "pluginName: ", pluginName
4995 pluginBuilderName = pluginName + "Builder"
4997 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4998 except Exception, e:
4999 from salome_utils import verbose
5000 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5002 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5003 plugin = eval( pluginBuilderName )
5004 #print " plugin:" , str(plugin)
5006 # add methods creating algorithms to Mesh
5007 for k in dir( plugin ):
5008 if k[0] == '_': continue
5009 algo = getattr( plugin, k )
5010 #print " algo:", str(algo)
5011 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5012 #print " meshMethod:" , str(algo.meshMethod)
5013 if not hasattr( Mesh, algo.meshMethod ):
5014 setattr( Mesh, algo.meshMethod, algoCreator() )
5016 getattr( Mesh, algo.meshMethod ).add( algo )