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